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 namespace UnityEditor.PackageManager.UI.Internal { internal class PackageDeprecatedTagLabel : PackageBaseTagLabel { public PackageDeprecatedTagLabel() { name = "tagDeprecated"; text = L10n.Tr("Deprecated"); } public override void Refresh(IPackageVersion version) { var showDeprecatedVersion = version.HasTag(PackageTag.Deprecated); var showDeprecatedPackage = version.package.isDeprecated; var visible = showDeprecatedVersion || showDeprecatedPackage; UIUtils.SetElementDisplay(this, visible); if (!visible) return; EnableInClassList("DeprecatedVersion", showDeprecatedVersion); EnableInClassList("DeprecatedPackage", showDeprecatedPackage); } } }
UnityCsReference/Modules/PackageManagerUI/Editor/UI/PackageTagLabel/PackageDeprecatedTagLabel.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/UI/PackageTagLabel/PackageDeprecatedTagLabel.cs", "repo_id": "UnityCsReference", "token_count": 389 }
413
// 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 SidebarRow : VisualElement { public const string k_SelectedClassName = "selected"; public const string k_IndentedClassName = "indented"; public const string k_SidebarIconClassName = "sidebarIcon"; public const string k_SidebarTitleClassName = "sidebarTitle"; public string pageId { get; } private Label m_RowTitle; private VisualElement m_RowIcon; public SidebarRow(string pageId, string rowTitle, Icon icon = Icon.None, bool isIndented = false) { tooltip = rowTitle; this.pageId = pageId; m_RowIcon = new VisualElement(); m_RowIcon.classList.Add(k_SidebarIconClassName); m_RowIcon.classList.Add(icon.ClassName()); Add(m_RowIcon); m_RowTitle = new Label { text = rowTitle }; m_RowTitle.classList.Add(k_SidebarTitleClassName); Add(m_RowTitle); EnableInClassList(k_IndentedClassName, isIndented); } public void SetSelected(bool select) { EnableInClassList(k_SelectedClassName, select); } }
UnityCsReference/Modules/PackageManagerUI/Editor/UI/Sidebar/SidebarRow.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/UI/Sidebar/SidebarRow.cs", "repo_id": "UnityCsReference", "token_count": 474 }
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.Generic; using System.Globalization; using System.Linq; using UnityEditor.Overlays; using UnityEditor.ShortcutManagement; using UnityEngine; using UnityEngine.Rendering; // The ParticleEffectUI displays one or more ParticleSystemUIs. namespace UnityEditor { internal interface ParticleEffectUIOwner { void Repaint(); Editor customEditor { get; } } internal class ParticleEffectUI { public ParticleEffectUIOwner m_Owner; // Can be InspectorWindow or ParticleSystemWindow static ParticleEffectUI s_EffectUi; public ParticleSystemUI[] m_Emitters; // Contains UI for all ParticleSystem children of the root ParticleSystem for this effect bool m_EmittersActiveInHierarchy; public bool m_SubEmitterSelected; ParticleSystemCurveEditor m_ParticleSystemCurveEditor; // The curve editor used by ParticleSystem modules List<ParticleSystem> m_SelectedParticleSystems; // This is the array of selected particle systems and used to find the root ParticleSystem and for the inspector TimeHelper m_TimeHelper = new TimeHelper(); public static ParticleSystem m_MainPlaybackSystem; public static bool m_ShowBounds = false; public static bool m_ShowOnlySelected = false; public static bool m_VerticalLayout; const string k_SimulationStateId = "SimulationState"; enum PlayState { Stopped = 0, Playing = 1, Paused = 2 } // ParticleSystemWindow Layout static readonly Vector2 k_MinEmitterAreaSize = new Vector2(125f, 100); static readonly Vector2 k_MinCurveAreaSize = new Vector2(100, 100); float m_EmitterAreaWidth = 230; // Only used in ParticleSystemWindow for horizontal layout float m_CurveEditorAreaHeight = 330; // Only used in ParticleSystemWindow for vertical layout Vector2 m_EmitterAreaScrollPos = Vector2.zero; static readonly Color k_DarkSkinDisabledColor = new Color(0.66f, 0.66f, 0.66f, 0.95f); static readonly Color k_LightSkinDisabledColor = new Color(0.84f, 0.84f, 0.84f, 0.95f); private enum OwnerType { Inspector, ParticleSystemWindow } internal class Texts { public GUIContent previewSpeed = EditorGUIUtility.TrTextContent("Playback Speed", "Playback Speed is also affected by the Time Scale setting in the Time Manager."); public GUIContent previewSpeedDisabled = EditorGUIUtility.TrTextContent("Playback Speed", "Playback Speed is locked to 0.0, because the Time Scale in the Time Manager is set to 0.0."); public GUIContent previewTime = EditorGUIUtility.TrTextContent("Playback Time"); public GUIContent particleCount = EditorGUIUtility.TrTextContent("Particles"); public GUIContent subEmitterParticleCount = EditorGUIUtility.TrTextContent("Sub Emitter Particles"); public GUIContent particleSpeeds = EditorGUIUtility.TrTextContent("Speed Range"); public GUIContent play = EditorGUIUtility.TrTextContent("Play"); public GUIContent playDisabled = EditorGUIUtility.TrTextContent("Play", "Play is disabled, because the Time Scale in the Time Manager is set to 0.0."); public GUIContent stop = EditorGUIUtility.TrTextContent("Stop"); public GUIContent pause = EditorGUIUtility.TrTextContent("Pause"); public GUIContent restart = EditorGUIUtility.TrTextContent("Restart"); public GUIContent addParticleSystem = EditorGUIUtility.TrTextContent("", "Create Particle System"); public GUIContent showBounds = EditorGUIUtility.TrTextContent("Show Bounds", "Show world space bounding boxes."); public GUIContent showOnlySelected = EditorGUIUtility.TrTextContent("Show Only Selected", "Hide all unselected Particle Systems in the current Effect."); public GUIContent resimulation = EditorGUIUtility.TrTextContent("Resimulate", "If resimulate is enabled, the Particle System will show changes made to the system immediately (including changes made to the Particle System Transform)."); public GUIContent previewLayers = EditorGUIUtility.TrTextContent("Simulate Layers", "Automatically preview all looping Particle Systems on the chosen layers, in addition to the selected Game Objects."); public string secondsFloatFieldFormatString = "f2"; public string speedFloatFieldFormatString = "f1"; } private static Texts s_Texts; internal static Texts texts { get { if (s_Texts == null) s_Texts = new Texts(); return s_Texts; } } static Event CreateCommandEvent(string commandName) { return new Event { type = EventType.ExecuteCommand, commandName = "ParticleSystem/" + commandName }; } static Event s_PlayEvent = CreateCommandEvent("Play"); static Event s_StopEvent = CreateCommandEvent("Stop"); static Event s_RestartEvent = CreateCommandEvent("Restart"); static Event s_ResimulationEvent = CreateCommandEvent("Resimulation"); static Event s_ShowBoundsEvent = CreateCommandEvent("ShowBounds"); static Event s_ShowOnlySelectedEvent = CreateCommandEvent("ShowOnlySelected"); static Event s_ForwardBeginEvent = CreateCommandEvent("ForwardBegin"); static Event s_ForwardEndEvent = CreateCommandEvent("ForwardEnd"); static Event s_ReverseBeginEvent = CreateCommandEvent("ReverseBegin"); static Event s_ReverseEndEvent = CreateCommandEvent("ReverseEnd"); static void DispatchShortcutEvent(Event evt) { var sceneView = SceneView.lastActiveSceneView; if (sceneView != null) { if (sceneView.SendEvent(evt)) return; } var inspectors = Resources.FindObjectsOfTypeAll<ParticleSystemInspector>(); foreach (var inspector in inspectors) { if (inspector != null) { if (inspector.HandleShortcutEvent(evt)) return; } } var windows = Resources.FindObjectsOfTypeAll<ParticleSystemWindow>(); foreach (var window in windows) { if (window != null) { if (window.HandleShortcutEvent(evt)) return; } } } [FormerlyPrefKeyAs("ParticleSystem/Play", ",")] [Shortcut("ParticleSystem/Play", typeof(ParticleSystemInspector.ShortcutContext), KeyCode.Comma)] static void PlayPauseShortcut(ShortcutArguments args) { DispatchShortcutEvent(s_PlayEvent); } [FormerlyPrefKeyAs("ParticleSystem/Stop", ".")] [Shortcut("ParticleSystem/Stop", typeof(ParticleSystemInspector.ShortcutContext), KeyCode.Period)] static void StopShortcut(ShortcutArguments args) { DispatchShortcutEvent(s_StopEvent); } [Shortcut("ParticleSystem/Restart", typeof(ParticleSystemInspector.ShortcutContext), KeyCode.Slash)] static void RestartShortcut(ShortcutArguments args) { DispatchShortcutEvent(s_RestartEvent); } [Shortcut("ParticleSystem/Resimulation", typeof(ParticleSystemInspector.ShortcutContext))] static void ResimulationShortcut(ShortcutArguments args) { DispatchShortcutEvent(s_ResimulationEvent); } [Shortcut("ParticleSystem/ShowBounds", typeof(ParticleSystemInspector.ShortcutContext))] static void ShowBoundsShortcut(ShortcutArguments args) { DispatchShortcutEvent(s_ShowBoundsEvent); } [Shortcut("ParticleSystem/ShowOnlySelected", typeof(ParticleSystemInspector.ShortcutContext))] static void ShowOnlySelectedShortcut(ShortcutArguments args) { DispatchShortcutEvent(s_ShowOnlySelectedEvent); } [FormerlyPrefKeyAs("ParticleSystem/Forward", "m")] [ClutchShortcut("ParticleSystem/Forward", typeof(ParticleSystemInspector.ShortcutContext), KeyCode.M)] static void ForwardShortcut(ShortcutArguments args) { DispatchShortcutEvent(args.stage == ShortcutStage.Begin ? s_ForwardBeginEvent : s_ForwardEndEvent); } [FormerlyPrefKeyAs("ParticleSystem/Reverse", "n")] [ClutchShortcut("ParticleSystem/Reverse", typeof(ParticleSystemInspector.ShortcutContext), KeyCode.N)] static void ReverseShortcut(ShortcutArguments args) { DispatchShortcutEvent(args.stage == ShortcutStage.Begin ? s_ReverseBeginEvent : s_ReverseEndEvent); } public ParticleEffectUI(ParticleEffectUIOwner owner) { m_Owner = owner; System.Diagnostics.Debug.Assert(m_Owner is ParticleSystemInspector || m_Owner is ParticleSystemWindow); } public bool multiEdit { get { return (m_SelectedParticleSystems != null) && (m_SelectedParticleSystems.Count > 1); } } private bool ShouldManagePlaybackState(ParticleSystem root) { bool active = false; if (root != null) active = root.gameObject.activeInHierarchy; return active && !Application.IsPlaying(root.gameObject); } static Color GetDisabledColor() { return (!EditorGUIUtility.isProSkin) ? k_LightSkinDisabledColor : k_DarkSkinDisabledColor; } // Returns a list with 'root' and all its direct children. static internal ParticleSystem[] GetParticleSystems(ParticleSystem root) { List<ParticleSystem> particleSystems = new List<ParticleSystem>(); particleSystems.Add(root); GetDirectParticleSystemChildrenRecursive(root.transform, particleSystems); return particleSystems.ToArray(); } // Adds only active Particle Systems static private void GetDirectParticleSystemChildrenRecursive(Transform transform, List<ParticleSystem> particleSystems) { foreach (Transform childTransform in transform) { ParticleSystem ps = childTransform.gameObject.GetComponent<ParticleSystem>(); if (ps != null) { // Note: we do not check for if the gameobject is active (we want inactive particle systems as well due prefabs) particleSystems.Add(ps); GetDirectParticleSystemChildrenRecursive(childTransform, particleSystems); } } } // Should be called often to ensure we catch if selected Particle System is dragged in/out of root hierarchy public bool InitializeIfNeeded(IEnumerable<ParticleSystem> systems) { bool anyAdded = false; ParticleSystem[] allSystems = systems.ToArray(); bool usingMultiEdit = (allSystems.Length > 1); bool initializeRequired = false; ParticleSystem mainSystem = null; foreach (ParticleSystem shuriken in allSystems) { ParticleSystem[] shurikens; if (!usingMultiEdit) { ParticleSystem root = ParticleSystemEditorUtils.GetRoot(shuriken); if (root == null) continue; shurikens = GetParticleSystems(root); mainSystem = root; // Check if we need to re-initialize? if (m_SelectedParticleSystems != null && m_SelectedParticleSystems.Count > 0) { if (root == ParticleSystemEditorUtils.GetRoot(m_SelectedParticleSystems[0])) { if (m_ParticleSystemCurveEditor != null && m_Emitters != null && shurikens.Length == m_Emitters.Length && shuriken.gameObject.activeInHierarchy == m_EmittersActiveInHierarchy) { m_SelectedParticleSystems = new List<ParticleSystem>(); m_SelectedParticleSystems.Add(shuriken); if (m_ShowOnlySelected) SetShowOnlySelectedMode(m_ShowOnlySelected); // always refresh continue; } } } } else { // in multi-edit mode, we explicitly choose the systems to edit, so don't automatically add child systems or search for the root shurikens = new ParticleSystem[] { shuriken }; mainSystem = shuriken; } // Cleanup before initializing if (m_ParticleSystemCurveEditor != null) Clear(); // Now initialize initializeRequired = true; if (!anyAdded) { m_SelectedParticleSystems = new List<ParticleSystem>(); anyAdded = true; } m_SelectedParticleSystems.Add(shuriken); // Single edit emitter setup if (!usingMultiEdit) { // Init CurveEditor before modules (they may add curves during construction) m_ParticleSystemCurveEditor = new ParticleSystemCurveEditor(); m_ParticleSystemCurveEditor.Init(); int numEmitters = shurikens.Length; if (numEmitters > 0) { m_Emitters = new ParticleSystemUI[numEmitters]; for (int i = 0; i < numEmitters; ++i) { m_Emitters[i] = new ParticleSystemUI(); m_Emitters[i].Init(this, new ParticleSystem[] { shurikens[i] }); } m_EmittersActiveInHierarchy = shuriken.gameObject.activeInHierarchy; } } } if (initializeRequired) { // Multi-edit emitter setup if (usingMultiEdit) { // Init CurveEditor before modules (they may add curves during construction) m_ParticleSystemCurveEditor = new ParticleSystemCurveEditor(); m_ParticleSystemCurveEditor.Init(); int numEmitters = m_SelectedParticleSystems.Count; if (numEmitters > 0) { m_Emitters = new ParticleSystemUI[1]; m_Emitters[0] = new ParticleSystemUI(); m_Emitters[0].Init(this, m_SelectedParticleSystems.ToArray()); m_EmittersActiveInHierarchy = m_SelectedParticleSystems[0].gameObject.activeInHierarchy; } } // Allow modules to validate their state (the user can have moved emitters around in the hierarchy) foreach (ParticleSystemUI e in m_Emitters) foreach (ModuleUI m in e.m_Modules) if (m != null) m.Validate(); // Sync to state if (GetAllModulesVisible()) SetAllModulesVisible(true); m_EmitterAreaWidth = EditorPrefs.GetFloat("ParticleSystemEmitterAreaWidth", k_MinEmitterAreaSize.x); m_CurveEditorAreaHeight = EditorPrefs.GetFloat("ParticleSystemCurveEditorAreaHeight", k_MinCurveAreaSize.y); SetShowOnlySelectedMode(m_ShowOnlySelected); m_EmitterAreaScrollPos.x = SessionState.GetFloat("CurrentEmitterAreaScroll", 0.0f); if (ShouldManagePlaybackState(mainSystem)) { TryRestorePlayState(mainSystem); // Play when selecting a new particle effect if (m_MainPlaybackSystem != mainSystem) Play(); } } m_MainPlaybackSystem = mainSystem; return initializeRequired; } void SavePlayState(ParticleSystem particleSystem) { if (particleSystem == null) return; // Store simulation state of current effect as Vector3 (rootInstanceID, PlayState, playBackTime) in Session cache int rootInstanceId = particleSystem.GetInstanceID(); Vector3 state = new Vector3(rootInstanceId, (int)GetCurrentPlayState(), ParticleSystemEditorUtils.playbackTime); SessionState.SetVector3(k_SimulationStateId + rootInstanceId, state); } void TryRestorePlayState(ParticleSystem particleSystem) { if (particleSystem == null) return; Vector3 simulationState = SessionState.GetVector3(k_SimulationStateId + particleSystem.GetInstanceID(), Vector3.zero); if (particleSystem.GetInstanceID() == (int)simulationState.x) { float lastPlayBackTime = simulationState.z; if (lastPlayBackTime > 0f) { if (m_MainPlaybackSystem != particleSystem) ParticleSystemEditorUtils.PerformCompleteResimulation(); ParticleSystemEditorUtils.playbackTime = lastPlayBackTime; } PlayState playState = (PlayState)simulationState.y; switch (playState) { case PlayState.Stopped: Stop(); break; case PlayState.Playing: Play(); break; case PlayState.Paused: Pause(); break; } } } PlayState GetCurrentPlayState() { PlayState playState; if (IsPlaying()) playState = PlayState.Playing; else if (IsPaused()) playState = PlayState.Paused; else playState = PlayState.Stopped; return playState; } internal void UndoRedoPerformed(in UndoRedoInfo info) { Refresh(); foreach (ParticleSystemUI e in m_Emitters) { foreach (ModuleUI moduleUI in e.m_Modules) { if (moduleUI != null) { moduleUI.CheckVisibilityState(); if (moduleUI.foldout) moduleUI.UndoRedoPerformed(info); } } } // Undo will deactivate the ParticleSystem and therefore stop it, here we resume the playback state for the user (UUM-28514) RestorePlayBackStateForCurrentSelectedParticleSystem(); m_Owner.Repaint(); } internal void PrefabInstanceUpdated(GameObject instance) { // Any update to prefab instances will have stopped the play back here we resume the playback state for the user (UUM-28514) RestorePlayBackStateForCurrentSelectedParticleSystem(); } internal void PrefabInstanceReverted(GameObject instance) { // Any update to prefab instances will have stopped the play back here we resume the playback state for the user (UUM-28514) RestorePlayBackStateForCurrentSelectedParticleSystem(); } void RestorePlayBackStateForCurrentSelectedParticleSystem() { if (m_SelectedParticleSystems == null || m_SelectedParticleSystems.Count == 0) return; ParticleSystem root = ParticleSystemEditorUtils.GetRoot(m_SelectedParticleSystems[0]); if (ShouldManagePlaybackState(root)) { TryRestorePlayState(root); } } public void Clear() { ParticleSystem root = ParticleSystemEditorUtils.GetRoot(m_SelectedParticleSystems[0]); // root can have been deleted if (ShouldManagePlaybackState(root)) { SavePlayState(root); // Stop the ParticleSystem here (prevents it being frozen on screen) //Stop(); } m_ParticleSystemCurveEditor.OnDisable(); Tools.s_Hidden = false; // The collisionmodule might have hidden the tools if (s_EffectUi == this) s_EffectUi = null; SetShowOnlySelectedMode(false); PlayModeView.RepaintAll(); SceneView.RepaintAll(); } public void ClearSelectedSystems() { // We cant clear the selected systems inside of Clear as this method is also used during InitializeIfNeeded when // the list is created and calling Clear each time would corrupt the list when multi editing. (case 1254599) m_SelectedParticleSystems?.Clear(); } static public Vector2 GetMinSize() { return k_MinEmitterAreaSize + k_MinCurveAreaSize; } public void Refresh() { UpdateProperties(); m_ParticleSystemCurveEditor.Refresh(); } public string GetNextParticleSystemName() { string nextName = ""; for (int i = 2; i < 50; ++i) { nextName = L10n.Tr("Particle System ") + i; bool found = false; foreach (ParticleSystemUI e in m_Emitters) { if (e.m_ParticleSystems.FirstOrDefault(o => o.name == nextName) != null) { found = true; break; } } if (!found) return nextName; } return L10n.Tr("Particle System"); } public bool IsParticleSystemUIVisible(ParticleSystemUI psUI) { OwnerType ownerType = m_Owner is ParticleSystemInspector ? OwnerType.Inspector : OwnerType.ParticleSystemWindow; if (ownerType == OwnerType.ParticleSystemWindow) return true; // ownerType == OwnerType.Inspector foreach (ParticleSystem ps in psUI.m_ParticleSystems) { if (m_SelectedParticleSystems.FirstOrDefault(o => o == ps) != null) return true; } return false; } public void PlayOnAwakeChanged(bool newPlayOnAwake) { foreach (ParticleSystemUI psUI in m_Emitters) { InitialModuleUI initialModule = psUI.m_Modules[0] as InitialModuleUI; System.Diagnostics.Debug.Assert(initialModule != null); initialModule.m_PlayOnAwake.boolValue = newPlayOnAwake; psUI.ApplyProperties(); } } public GameObject CreateParticleSystem(ParticleSystem parentOfNewParticleSystem, SubModuleUI.SubEmitterType defaultType) { string name = GetNextParticleSystemName(); GameObject go = new GameObject(name, typeof(ParticleSystem)); if (go) { if (parentOfNewParticleSystem) go.transform.parent = parentOfNewParticleSystem.transform; go.transform.localPosition = Vector3.zero; go.transform.localRotation = Quaternion.identity; // Setup particle system based on type ParticleSystem ps = go.GetComponent<ParticleSystem>(); if (defaultType != SubModuleUI.SubEmitterType.None) ps.SetupDefaultType((ParticleSystemSubEmitterType)defaultType); SessionState.SetFloat("CurrentEmitterAreaScroll", m_EmitterAreaScrollPos.x); // Assign default material ParticleSystemRenderer renderer = go.GetComponent<ParticleSystemRenderer>(); Material particleMat = null; if (GraphicsSettings.currentRenderPipeline != null) particleMat = GraphicsSettings.currentRenderPipeline.defaultParticleMaterial; if (particleMat == null) particleMat = AssetDatabase.GetBuiltinExtraResource<Material>("Default-ParticleSystem.mat"); renderer.material = particleMat; Undo.RegisterCreatedObjectUndo(go, "Create ParticleSystem"); return go; } return null; } public ParticleSystemCurveEditor GetParticleSystemCurveEditor() { return m_ParticleSystemCurveEditor; } public void OnSceneViewGUI() { ParticleSystem root = ParticleSystemEditorUtils.GetRoot(m_SelectedParticleSystems[0]); if (root && root.gameObject.activeInHierarchy) s_EffectUi = this; else s_EffectUi = null; foreach (ParticleSystemUI e in m_Emitters) e.OnSceneViewGUI(); } int m_IsDraggingTimeHotControlID = -1; internal void PlayBackInfoGUI(bool isPlayMode) { EventType oldEventType = Event.current.type; int oldHotControl = GUIUtility.hotControl; string oldFormat = EditorGUI.kFloatFieldFormatString; EditorGUIUtility.labelWidth = 110.0f; if (!isPlayMode) { EditorGUI.kFloatFieldFormatString = s_Texts.secondsFloatFieldFormatString; if (Time.timeScale == 0.0f) { using (new EditorGUI.DisabledScope(true)) { EditorGUILayout.FloatField(s_Texts.previewSpeedDisabled, 0.0f); } } else { ParticleSystemEditorUtils.simulationSpeed = Mathf.Clamp(EditorGUILayout.FloatField(s_Texts.previewSpeed, ParticleSystemEditorUtils.simulationSpeed), 0f, 10f); } EditorGUI.kFloatFieldFormatString = oldFormat; EditorGUI.BeginChangeCheck(); EditorGUI.kFloatFieldFormatString = s_Texts.secondsFloatFieldFormatString; float playbackTime = EditorGUILayout.FloatField(s_Texts.previewTime, ParticleSystemEditorUtils.playbackTime); EditorGUI.kFloatFieldFormatString = oldFormat; if (EditorGUI.EndChangeCheck()) { if (oldEventType == EventType.MouseDrag) { ParticleSystemEditorUtils.playbackIsScrubbing = true; float previewSpeed = ParticleSystemEditorUtils.simulationSpeed; float oldplaybackTime = ParticleSystemEditorUtils.playbackTime; float timeDiff = playbackTime - oldplaybackTime; playbackTime = oldplaybackTime + timeDiff * (0.05F * previewSpeed); } playbackTime = Mathf.Max(playbackTime, 0.0F); ParticleSystemEditorUtils.playbackTime = playbackTime; foreach (ParticleSystem ps in m_SelectedParticleSystems) { ParticleSystem root = ParticleSystemEditorUtils.GetRoot(ps); if (root.isStopped) { root.Play(); root.Pause(); } } ParticleSystemEditorUtils.PerformCompleteResimulation(); } // Detect start dragging if (oldEventType == EventType.MouseDown && GUIUtility.hotControl != oldHotControl) { m_IsDraggingTimeHotControlID = GUIUtility.hotControl; ParticleSystemEditorUtils.playbackIsScrubbing = true; } // Detect stop dragging if (m_IsDraggingTimeHotControlID != -1 && GUIUtility.hotControl != m_IsDraggingTimeHotControlID) { m_IsDraggingTimeHotControlID = -1; ParticleSystemEditorUtils.playbackIsScrubbing = false; } } int particleCount = 0; float fastestParticle = 0.0f; float slowestParticle = Mathf.Infinity; foreach (ParticleSystem ps in m_SelectedParticleSystems) { if (ps != null) ps.CalculateEffectUIData(ref particleCount, ref fastestParticle, ref slowestParticle); } EditorGUILayout.LabelField(s_Texts.particleCount, GUIContent.Temp(particleCount.ToString())); bool hasSubEmitters = false; int subEmitterParticles = 0; foreach (ParticleSystem ps in m_SelectedParticleSystems) { int subEmitterParticlesCurrent = 0; if (ps != null && ps.CalculateEffectUISubEmitterData(ref subEmitterParticlesCurrent, ref fastestParticle, ref slowestParticle)) { hasSubEmitters = true; subEmitterParticles += subEmitterParticlesCurrent; } } if (hasSubEmitters) EditorGUILayout.LabelField(s_Texts.subEmitterParticleCount, GUIContent.Temp(subEmitterParticles.ToString())); if (fastestParticle >= slowestParticle) EditorGUILayout.LabelField(s_Texts.particleSpeeds, GUIContent.Temp(slowestParticle.ToString(s_Texts.speedFloatFieldFormatString, CultureInfo.InvariantCulture.NumberFormat) + " - " + fastestParticle.ToString(s_Texts.speedFloatFieldFormatString, CultureInfo.InvariantCulture.NumberFormat))); else EditorGUILayout.LabelField(s_Texts.particleSpeeds, GUIContent.Temp("0.0 - 0.0")); if (!isPlayMode) { ParticleSystemEditorUtils.previewLayers = EditorGUILayout.LayerMaskField(ParticleSystemEditorUtils.previewLayers, s_Texts.previewLayers); ParticleSystemEditorUtils.resimulation = GUILayout.Toggle(ParticleSystemEditorUtils.resimulation, s_Texts.resimulation, EditorStyles.toggle); } m_ShowBounds = GUILayout.Toggle(m_ShowBounds, texts.showBounds, EditorStyles.toggle); EditorGUI.BeginChangeCheck(); m_ShowOnlySelected = GUILayout.Toggle(m_ShowOnlySelected, texts.showOnlySelected, EditorStyles.toggle); if (EditorGUI.EndChangeCheck()) SetShowOnlySelectedMode(m_ShowOnlySelected); EditorGUIUtility.labelWidth = 0.0f; } bool m_ScrubForward; bool m_ScrubReverse; float m_ScrubNextUpdate; void HandleScrubbing() { if ((!m_ScrubForward && !m_ScrubReverse) || Time.realtimeSinceStartup < m_ScrubNextUpdate) return; var evt = Event.current; var changeTime = 0; if (m_ScrubForward) changeTime++; if (m_ScrubReverse) changeTime--; ParticleSystemEditorUtils.playbackIsScrubbing = true; float previewSpeed = ParticleSystemEditorUtils.simulationSpeed; float timeDiff = (evt.shift ? 3f : 1f) * m_TimeHelper.deltaTime * (changeTime * 3f); ParticleSystemEditorUtils.playbackTime = Mathf.Max(0f, ParticleSystemEditorUtils.playbackTime + timeDiff * (previewSpeed)); foreach (ParticleSystem ps in m_SelectedParticleSystems) { ParticleSystem root = ParticleSystemEditorUtils.GetRoot(ps); if (root.isStopped) { root.Play(); root.Pause(); } } ParticleSystemEditorUtils.PerformCompleteResimulation(); // Mimic previous behavior that relied on key repeat m_ScrubNextUpdate = Time.realtimeSinceStartup + 1f / 15f; } internal bool HandleShortcutEvent(Event evt) { if (evt.commandName == s_PlayEvent.commandName) { if (EditorApplication.isPlaying) { // If world is playing Pause is not handled, just restart instead Stop(); Play(); } else { // In Edit mode we have full play/pause functionality if (!ParticleSystemEditorUtils.playbackIsPlaying) Play(); else Pause(); } return true; } else if (evt.commandName == s_StopEvent.commandName) { Stop(); return true; } else if (evt.commandName == s_RestartEvent.commandName) { Stop(); Play(); return true; } else if (evt.commandName == s_ResimulationEvent.commandName) { ParticleSystemEditorUtils.resimulation = !ParticleSystemEditorUtils.resimulation; return true; } else if (evt.commandName == s_ShowBoundsEvent.commandName) { m_ShowBounds = !m_ShowBounds; return true; } else if (evt.commandName == s_ShowOnlySelectedEvent.commandName) { m_ShowOnlySelected = !m_ShowOnlySelected; return true; } else if (evt.commandName == s_ForwardBeginEvent.commandName) { m_ScrubForward = true; return true; } else if (evt.commandName == s_ForwardEndEvent.commandName) { m_ScrubForward = false; if (!m_ScrubReverse) ParticleSystemEditorUtils.playbackIsScrubbing = false; return true; } else if (evt.commandName == s_ReverseBeginEvent.commandName) { m_ScrubReverse = true; return true; } else if (evt.commandName == s_ReverseEndEvent.commandName) { m_ScrubReverse = false; if (!m_ScrubForward) ParticleSystemEditorUtils.playbackIsScrubbing = false; return true; } return false; } private void HandleKeyboardShortcuts() { var evt = Event.current; if (evt.type == EventType.ExecuteCommand) { if (HandleShortcutEvent(evt)) evt.Use(); } HandleScrubbing(); } internal static bool IsStopped(ParticleSystem root) { return (!ParticleSystemEditorUtils.playbackIsPlaying && !ParticleSystemEditorUtils.playbackIsPaused) && !ParticleSystemEditorUtils.playbackIsScrubbing; } internal bool IsPaused() { return !IsPlaying() && !IsStopped(ParticleSystemEditorUtils.GetRoot(m_SelectedParticleSystems[0])); } internal bool IsPlaying() { return ParticleSystemEditorUtils.playbackIsPlaying; } internal void Play() { bool anyPlayed = false; foreach (ParticleSystem ps in m_SelectedParticleSystems) { ParticleSystem root = ParticleSystemEditorUtils.GetRoot(ps); if (root) { root.Play(); anyPlayed = true; } } if (anyPlayed) { ParticleSystemEditorUtils.playbackIsScrubbing = false; m_Owner.Repaint(); } } internal void Pause() { bool anyPaused = false; foreach (ParticleSystem ps in m_SelectedParticleSystems) { ParticleSystem root = ParticleSystemEditorUtils.GetRoot(ps); if (root) { root.Pause(); anyPaused = true; } } if (anyPaused) { ParticleSystemEditorUtils.playbackIsScrubbing = true; m_Owner.Repaint(); } } internal void Stop() { ParticleSystemEditorUtils.playbackIsScrubbing = false; ParticleSystemEditorUtils.playbackTime = 0.0F; ParticleSystemEffectUtils.StopEffect(); m_Owner.Repaint(); } internal void PlayStopGUI() { if (s_Texts == null) s_Texts = new Texts(); Event evt = Event.current; if (evt.type == EventType.Layout) m_TimeHelper.Update(); bool disablePlayButton = (Time.timeScale == 0.0f); GUIContent playText = disablePlayButton ? s_Texts.playDisabled : s_Texts.play; if (!EditorApplication.isPlaying) { // Edit Mode: Play/Stop buttons GUILayout.BeginHorizontal(GUILayout.Width(220.0f)); { using (new EditorGUI.DisabledScope(disablePlayButton)) { bool isPlaying = ParticleSystemEditorUtils.playbackIsPlaying && !ParticleSystemEditorUtils.playbackIsPaused && !disablePlayButton; if (GUILayout.Button(isPlaying ? s_Texts.pause : playText, "ButtonLeft")) { if (isPlaying) Pause(); else Play(); } } if (GUILayout.Button(s_Texts.restart, "ButtonMid")) { Stop(); Play(); } if (GUILayout.Button(s_Texts.stop, "ButtonRight")) { Stop(); } } GUILayout.EndHorizontal(); } else { // Play mode: we only handle play/stop (due to problems with determining if a system with subemitters is playing we cannot pause) GUILayout.BeginHorizontal(); { using (new EditorGUI.DisabledScope(disablePlayButton)) { if (GUILayout.Button(playText)) { Stop(); Play(); } } if (GUILayout.Button(s_Texts.stop)) { Stop(); } } GUILayout.EndHorizontal(); } // Playback info PlayBackInfoGUI(EditorApplication.isPlaying); // Handle shortcut keys last so we do not activate them if inputfield has used the event HandleKeyboardShortcuts(); } private void InspectorParticleSystemGUI() { GUILayout.BeginVertical(ParticleSystemStyles.Get().effectBgStyle); { ParticleSystem selectedSystem = (m_SelectedParticleSystems.Count > 0) ? m_SelectedParticleSystems[0] : null; if (selectedSystem != null) { ParticleSystemUI psUI = m_Emitters.FirstOrDefault(o => o.m_ParticleSystems[0] == selectedSystem); if (psUI != null) { float width = GUIClip.visibleRect.width - 18; // -10 is effect_bg padding, -8 is inspector padding psUI.OnGUI(width, false); } } } GUILayout.EndVertical(); GUILayout.FlexibleSpace(); HandleKeyboardShortcuts(); } private void DrawSelectionMarker(Rect rect) { rect.x += 1; rect.y += 1; rect.width -= 2; rect.height -= 2; ParticleSystemStyles.Get().selectionMarker.Draw(rect, GUIContent.none, false, true, true, false); } private List<ParticleSystemUI> GetSelectedParticleSystemUIs() { List<ParticleSystemUI> result = new List<ParticleSystemUI>(); int[] selectedInstanceIDs = Selection.instanceIDs; foreach (ParticleSystemUI psUI in m_Emitters) { if (selectedInstanceIDs.Contains(psUI.m_ParticleSystems[0].gameObject.GetInstanceID())) result.Add(psUI); } return result; } private void MultiParticleSystemGUI(bool verticalLayout) { // Background GUILayout.BeginVertical(ParticleSystemStyles.Get().effectBgStyle); m_EmitterAreaScrollPos = EditorGUILayout.BeginScrollView(m_EmitterAreaScrollPos); { Rect emitterAreaRect = EditorGUILayout.BeginVertical(); { // Click-Drag with Alt pressed in entire area m_EmitterAreaScrollPos -= EditorGUI.MouseDeltaReader(emitterAreaRect, Event.current.alt); // Top padding GUILayout.Space(3); GUILayout.BeginHorizontal(); // Left padding GUILayout.Space(3); // added because cannot use padding due to clippling // Draw Emitters Color orgColor = GUI.color; bool isRepaintEvent = Event.current.type == EventType.Repaint; bool isShowOnlySelected = m_ShowOnlySelected; List<ParticleSystemUI> selectedSystems = GetSelectedParticleSystemUIs(); for (int i = 0; i < m_Emitters.Length; ++i) { if (i != 0) GUILayout.Space(ModuleUI.k_SpaceBetweenModules); bool isSelected = selectedSystems.Contains(m_Emitters[i]); ModuleUI rendererModuleUI = m_Emitters[i].GetParticleSystemRendererModuleUI(); if (isRepaintEvent && rendererModuleUI != null && !rendererModuleUI.enabled) GUI.color = GetDisabledColor(); if (isRepaintEvent && isShowOnlySelected && !isSelected) GUI.color = GetDisabledColor(); Rect psRect = EditorGUILayout.BeginVertical(); { if (isRepaintEvent && isSelected && m_Emitters.Length > 1) DrawSelectionMarker(psRect); m_Emitters[i].OnGUI(ModuleUI.k_CompactFixedModuleWidth, true); } EditorGUILayout.EndVertical(); GUI.color = orgColor; } // Do not show the Add button when editing a prefab asset (case 1287185) if (!PrefabUtility.IsPartOfPrefabAsset(m_SelectedParticleSystems[0])) { GUILayout.Space(5); if (GUILayout.Button(s_Texts.addParticleSystem, "OL Plus", GUILayout.Width(20))) { // Store state of inspector before creating new particle system that will reload the inspector (new selected object) //SessionState.SetFloat("CurrentEmitterAreaScroll", m_EmitterAreaScrollPos.x); CreateParticleSystem(ParticleSystemEditorUtils.GetRoot(m_SelectedParticleSystems[0]), SubModuleUI.SubEmitterType.None); } } GUILayout.FlexibleSpace(); // prevent centering GUILayout.EndHorizontal(); GUILayout.Space(4); // Click-Drag in background (does not require Alt pressed) m_EmitterAreaScrollPos -= EditorGUI.MouseDeltaReader(emitterAreaRect, true); GUILayout.FlexibleSpace(); // Makes the emitter area background extend to bottom } EditorGUILayout.EndVertical(); // EmitterAreaRect } EditorGUILayout.EndScrollView(); GUILayout.EndVertical(); // Background //GUILayout.FlexibleSpace(); // Makes the emitter area background align to bottom of highest emitter // Handle shortcut keys last so we do not activate them if inputfield has used the event HandleKeyboardShortcuts(); } private void WindowCurveEditorGUI(bool verticalLayout) { Rect rect; if (verticalLayout) { rect = GUILayoutUtility.GetRect(13, m_CurveEditorAreaHeight, GUILayout.MinHeight(m_CurveEditorAreaHeight)); } else { EditorWindow win = (EditorWindow)m_Owner; System.Diagnostics.Debug.Assert(win != null); rect = GUILayoutUtility.GetRect(win.position.width - m_EmitterAreaWidth, win.position.height - 17); } // Get mouse down event before curve editor ResizeHandling(verticalLayout); m_ParticleSystemCurveEditor.OnGUI(rect); } void ResizeHandling(bool verticalLayout) { Rect dragRect; const float dragWidth = 5f; if (verticalLayout) { dragRect = GUILayoutUtility.GetLastRect(); dragRect.y += -dragWidth; dragRect.height = dragWidth; // For horizontal layout we add a vertical size controller to adjust emitter area width float deltaY = EditorGUI.MouseDeltaReader(dragRect, true).y; if (deltaY != 0f) { m_CurveEditorAreaHeight -= deltaY; ClampWindowContentSizes(); EditorPrefs.SetFloat("ParticleSystemCurveEditorAreaHeight", m_CurveEditorAreaHeight); } if (Event.current.type == EventType.Repaint) EditorGUIUtility.AddCursorRect(dragRect, MouseCursor.SplitResizeUpDown); } else { // For horizontal layout we add a vertical size controller to adjust emitter area width dragRect = new Rect(m_EmitterAreaWidth - dragWidth, 0, dragWidth, GUIClip.visibleRect.height); float deltaX = EditorGUI.MouseDeltaReader(dragRect, true).x; if (deltaX != 0f) { m_EmitterAreaWidth += deltaX; ClampWindowContentSizes(); EditorPrefs.SetFloat("ParticleSystemEmitterAreaWidth", m_EmitterAreaWidth); } if (Event.current.type == EventType.Repaint) EditorGUIUtility.AddCursorRect(dragRect, MouseCursor.SplitResizeLeftRight); } } void ClampWindowContentSizes() { EventType type = Event.current.type; if (type != EventType.Layout) { float width = GUIClip.visibleRect.width; float height = GUIClip.visibleRect.height; bool verticalLayout = m_VerticalLayout; if (verticalLayout) m_CurveEditorAreaHeight = Mathf.Clamp(m_CurveEditorAreaHeight, k_MinCurveAreaSize.y, height - k_MinEmitterAreaSize.y); else m_EmitterAreaWidth = Mathf.Clamp(m_EmitterAreaWidth, k_MinEmitterAreaSize.x, width - k_MinCurveAreaSize.x); } } public void OnGUI() { // Init (if needed) if (s_Texts == null) s_Texts = new Texts(); if (m_Emitters == null) { return; } // Cache play state so we can resume play after undo'ing and updating prefab instances (UUM-28514) if (Event.current.type == EventType.Repaint) { ParticleSystem root = ParticleSystemEditorUtils.GetRoot(m_SelectedParticleSystems[0]); if (ShouldManagePlaybackState(root)) { SavePlayState(root); } } // Grab the latest data from the object UpdateProperties(); OwnerType ownerType = m_Owner is ParticleSystemInspector ? OwnerType.Inspector : OwnerType.ParticleSystemWindow; switch (ownerType) { case OwnerType.ParticleSystemWindow: { ClampWindowContentSizes(); bool verticalLayout = m_VerticalLayout; // GUIClip.visibleRect.width < GUIClip.visibleRect.height; if (verticalLayout) { MultiParticleSystemGUI(verticalLayout); WindowCurveEditorGUI(verticalLayout); } else { GUILayout.BeginHorizontal(); MultiParticleSystemGUI(verticalLayout); WindowCurveEditorGUI(verticalLayout); GUILayout.EndHorizontal(); } } break; case OwnerType.Inspector: // The inspector window already has added a vertical scrollview so no need to do it here InspectorParticleSystemGUI(); break; default: Debug.LogError("Unhandled enum"); break; } // Apply the property, handle undo ApplyModifiedProperties(); } void ApplyModifiedProperties() { // Apply the properties, handles undo for (int i = 0; i < m_Emitters.Length; ++i) m_Emitters[i].ApplyProperties(); } internal void UpdateProperties() { for (int i = 0; i < m_Emitters.Length; ++i) m_Emitters[i].UpdateProperties(); } static internal bool GetAllModulesVisible() { return EditorPrefs.GetBool("ParticleSystemShowAllModules", true); } internal void SetAllModulesVisible(bool showAll) { EditorPrefs.SetBool("ParticleSystemShowAllModules", showAll); foreach (var particleSystemUI in m_Emitters) { for (int i = 0; i < particleSystemUI.m_Modules.Length; ++i) { ModuleUI moduleUi = particleSystemUI.m_Modules[i]; if (moduleUi != null) { if (showAll) { if (!moduleUi.visibleUI) moduleUi.visibleUI = true; } else { bool allowHiding = true; if (moduleUi as RendererModuleUI != null) { if (particleSystemUI.m_ParticleSystems.FirstOrDefault(o => o.GetComponent<ParticleSystemRenderer>() == null) == null) allowHiding = false; } if (allowHiding && !moduleUi.enabled) moduleUi.visibleUI = false; } } } } } internal void SetShowOnlySelectedMode(bool enabled) { int[] selectedInstanceIDs = Selection.instanceIDs; foreach (ParticleSystemUI psUI in m_Emitters) { foreach (ParticleSystem selected in psUI.m_ParticleSystems) { if (selected != null) { ParticleSystem root = ParticleSystemEditorUtils.GetRoot(selected); if (root == null) continue; ParticleSystem[] allSystems = GetParticleSystems(root); foreach (ParticleSystem ps in allSystems) { ParticleSystemRenderer psRenderer = ps.GetComponent<ParticleSystemRenderer>(); if (psRenderer != null) { if (enabled) psRenderer.editorEnabled = selectedInstanceIDs.Contains(psRenderer.gameObject.GetInstanceID()); else psRenderer.editorEnabled = true; } } } } } } [Overlay(typeof(SceneView), k_OverlayId, k_DisplayName)] class SceneViewParticleOverlay : TransientSceneViewOverlay { const string k_OverlayId = "Scene View/Particles"; const string k_DisplayName = "Particles"; public override bool visible { get { return s_EffectUi != null; } } public override void OnGUI() { if (s_EffectUi == null) return; s_EffectUi.PlayStopGUI(); } } } }
UnityCsReference/Modules/ParticleSystemEditor/ParticleEffectUI.cs/0
{ "file_path": "UnityCsReference/Modules/ParticleSystemEditor/ParticleEffectUI.cs", "repo_id": "UnityCsReference", "token_count": 27922 }
415
// 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 UnityEditor.EditorTools; namespace UnityEditor { abstract partial class ModuleUI : SerializedModule { public ParticleSystemUI m_ParticleSystemUI; // owner private string m_DisplayName; protected string m_ToolTip = ""; public SerializedProperty m_Enabled; private VisibilityState m_VisibilityState; public List<SerializedProperty> m_ModuleCurves = new List<SerializedProperty>(); private List<SerializedProperty> m_CurvesRemovedWhenFolded = new List<SerializedProperty>(); public enum VisibilityState { NotVisible = 0, VisibleAndFolded = 1, VisibleAndFoldedOut = 2 } public bool visibleUI { get { return m_VisibilityState != VisibilityState.NotVisible; } set { SetVisibilityState(value ? VisibilityState.VisibleAndFolded : VisibilityState.NotVisible); } } public bool foldout { get { return m_VisibilityState == VisibilityState.VisibleAndFoldedOut; } set { SetVisibilityState(value ? VisibilityState.VisibleAndFoldedOut : VisibilityState.VisibleAndFolded); } } public bool enabled { get { return m_Enabled.boolValue; } set { if (m_Enabled.boolValue != value) { m_Enabled.boolValue = value; if (value) OnModuleEnable(); else OnModuleDisable(); } } } public bool enabledHasMultipleDifferentValues { get { return m_Enabled.hasMultipleDifferentValues; } } public string displayName { get { return m_DisplayName; } } public string toolTip { get { return m_ToolTip; } } public bool isWindowView { get { return m_ParticleSystemUI.m_ParticleEffectUI.m_Owner is ParticleSystemWindow; } } public ModuleUI(ParticleSystemUI owner, SerializedObject o, string name, string displayName) : base(o, name) { Setup(owner, o, displayName, VisibilityState.NotVisible); } public ModuleUI(ParticleSystemUI owner, SerializedObject o, string name, string displayName, VisibilityState initialVisibilityState) : base(o, name) { Setup(owner, o, displayName, initialVisibilityState); } private void Setup(ParticleSystemUI owner, SerializedObject o, string displayName, VisibilityState defaultVisibilityState) { m_ParticleSystemUI = owner; m_DisplayName = displayName; if (this is RendererModuleUI) m_Enabled = GetProperty0("m_Enabled"); else m_Enabled = GetProperty("enabled"); m_VisibilityState = VisibilityState.NotVisible; foreach (Object obj in o.targetObjects) { VisibilityState state = (VisibilityState)SessionState.GetInt(GetUniqueModuleName(obj), (int)defaultVisibilityState); m_VisibilityState = (VisibilityState)Mathf.Max((int)state, (int)m_VisibilityState); // use most visible state } CheckVisibilityState(); if (foldout) Init(); } protected abstract void Init(); public virtual void Validate() {} public virtual float GetXAxisScalar() {return 1f; } public abstract void OnInspectorGUI(InitialModuleUI initial); public virtual void OnSceneViewGUI() {} // Like OnSceneGUI but only called once when in multi edit mode where OnSceneGUI is called for each target. public virtual void UpdateCullingSupportedString(ref string text) {} protected virtual void OnModuleEnable() { Undo.undoRedoEvent += UndoRedoPerformed; Init(); // ensure initialized } public virtual void UndoRedoPerformed(in UndoRedoInfo info) { // If the undo operation has changed the module to now be disabled then we should remove any of its curves from the curve editor. (case 861424) if (!enabled) OnModuleDisable(); } protected virtual void OnModuleDisable() { Undo.undoRedoEvent -= UndoRedoPerformed; ParticleSystemCurveEditor psce = m_ParticleSystemUI.m_ParticleEffectUI.GetParticleSystemCurveEditor(); foreach (SerializedProperty curveProp in m_ModuleCurves) { if (psce.IsAdded(curveProp)) psce.RemoveCurve(curveProp); } } internal void CheckVisibilityState() { bool isRendererModule = this is RendererModuleUI; // Ensure disabled modules are only visible if show all modules is true. Except the renderer module, we want that // to be shown always if the module is there which means that we have a ParticleSystemRenderer if (!isRendererModule && !m_Enabled.boolValue && !ParticleEffectUI.GetAllModulesVisible()) SetVisibilityState(VisibilityState.NotVisible); // Ensure enabled modules are visible if (m_Enabled.boolValue && !visibleUI) SetVisibilityState(VisibilityState.VisibleAndFolded); } protected virtual void SetVisibilityState(VisibilityState newState) { if (newState != m_VisibilityState) { if (newState == VisibilityState.VisibleAndFolded) { // Remove curves from the curveeditor when closing modules (and put them back when folding out again) ParticleSystemCurveEditor psce = m_ParticleSystemUI.m_ParticleEffectUI.GetParticleSystemCurveEditor(); foreach (SerializedProperty curveProp in m_ModuleCurves) { if (psce.IsAdded(curveProp)) { m_CurvesRemovedWhenFolded.Add(curveProp); psce.SetVisible(curveProp, false); } } psce.Refresh(); } else if (newState == VisibilityState.VisibleAndFoldedOut) { ParticleSystemCurveEditor psce = m_ParticleSystemUI.m_ParticleEffectUI.GetParticleSystemCurveEditor(); foreach (SerializedProperty curveProp in m_CurvesRemovedWhenFolded) { psce.SetVisible(curveProp, true); } m_CurvesRemovedWhenFolded.Clear(); psce.Refresh(); } m_VisibilityState = newState; foreach (Object obj in serializedObject.targetObjects) { SessionState.SetInt(GetUniqueModuleName(obj), (int)m_VisibilityState); } if (newState == VisibilityState.VisibleAndFoldedOut) Init(); } } protected ParticleSystem GetParticleSystem() { return m_Enabled.serializedObject.targetObject as ParticleSystem; } public ParticleSystemCurveEditor GetParticleSystemCurveEditor() { return m_ParticleSystemUI.m_ParticleEffectUI.GetParticleSystemCurveEditor(); } public virtual bool DrawHeader(Rect rect, GUIContent label) { // When displaying prefab overrides, the whole UI is disabled, but we still need to be able to expand the modules to see the settings - this doesn't modify the asset bool wasEnabled = GUI.enabled; GUI.enabled = true; EditorGUI.BeginChangeCheck(); label = EditorGUI.BeginProperty(rect, label, m_Enabled); var toggleState = GUI.Toggle(rect, foldout, label, ParticleSystemStyles.Get().moduleHeaderStyle); EditorGUI.EndProperty(); if (EditorGUI.EndChangeCheck()) ToolManager.RefreshAvailableTools(); GUI.enabled = wasEnabled; return toggleState; } public void AddToModuleCurves(SerializedProperty curveProp) { m_ModuleCurves.Add(curveProp); if (!foldout) m_CurvesRemovedWhenFolded.Add(curveProp); } // See ParticleSystemGUI.cs for more ModuleUI GUI helper functions... } } // namespace UnityEditor
UnityCsReference/Modules/ParticleSystemEditor/ParticleSystemModules/ModuleUI.cs/0
{ "file_path": "UnityCsReference/Modules/ParticleSystemEditor/ParticleSystemModules/ModuleUI.cs", "repo_id": "UnityCsReference", "token_count": 4111 }
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.Collections.Generic; using System.Linq; using UnityEngine; // The ParticleSystemUI displays and manages the modules of a particle system. namespace UnityEditor { internal class ParticleSystemUI { public ParticleEffectUI m_ParticleEffectUI; // owner public ModuleUI[] m_Modules; public ParticleSystem[] m_ParticleSystems; public SerializedObject m_ParticleSystemSerializedObject; public SerializedObject m_RendererSerializedObject; private static string[] s_ModuleNames; private string m_SupportsCullingText; private string m_SupportsCullingTextLabel; // Cached version including bullet points private int m_CachedMeshInstanceID; private int m_CachedMaterialInstanceID; private int m_CachedMeshDirtyCount; private int m_CachedMaterialDirtyCount; private static PrefColor s_BoundsColor = new PrefColor("Particle System/Bounds", 1.0f, 235.0f / 255.0f, 4.0f / 255.0f, 1.0f); protected class Texts { public GUIContent addModules = EditorGUIUtility.TrTextContent("", "Show/Hide Modules"); public string bulletPoint = "\u2022 "; } private static Texts s_Texts; public bool multiEdit { get { return (m_ParticleSystems != null) && (m_ParticleSystems.Length > 1); } } public void Init(ParticleEffectUI owner, ParticleSystem[] systems) { if (s_ModuleNames == null) s_ModuleNames = GetUIModuleNames(); if (s_Texts == null) s_Texts = new Texts(); m_ParticleEffectUI = owner; m_ParticleSystems = systems; m_ParticleSystemSerializedObject = new SerializedObject(m_ParticleSystems); m_RendererSerializedObject = null; m_SupportsCullingText = null; m_Modules = CreateUIModules(this, m_ParticleSystemSerializedObject); bool anyWithoutRenderers = m_ParticleSystems.FirstOrDefault(o => o.GetComponent<ParticleSystemRenderer>() == null) != null; if (!anyWithoutRenderers) InitRendererUI(); UpdateParticleSystemInfoString(); } internal ModuleUI GetParticleSystemRendererModuleUI() { return m_Modules.Last(); } internal Bounds GetBounds() { var combinedBounds = new Bounds(); bool initialized = false; foreach (ParticleSystem ps in m_ParticleSystems) { ParticleSystemRenderer particleSystemRenderer = ps.GetComponent<ParticleSystemRenderer>(); if (!initialized) combinedBounds = particleSystemRenderer.bounds; combinedBounds.Encapsulate(particleSystemRenderer.bounds); initialized = true; } return combinedBounds; } private void InitRendererUI() { List<ParticleSystemRenderer> renderers = new List<ParticleSystemRenderer>(); foreach (ParticleSystem ps in m_ParticleSystems) { // Ensure we have a renderer ParticleSystemRenderer psRenderer = ps.GetComponent<ParticleSystemRenderer>(); if (psRenderer == null) { ps.gameObject.AddComponent<ParticleSystemRenderer>(); } renderers.Add(ps.GetComponent<ParticleSystemRenderer>()); } // Create RendererModuleUI if (renderers.Count > 0) { System.Diagnostics.Debug.Assert(m_Modules.Last() == null); // If hitting this assert we have either not cleaned up the previous renderer or hitting another module m_RendererSerializedObject = new SerializedObject(renderers.ToArray()); m_Modules[m_Modules.Length - 1] = new RendererModuleUI(this, m_RendererSerializedObject, s_ModuleNames.Last()); } } private void ClearRenderers() { // Remove renderer components m_RendererSerializedObject = null; foreach (ParticleSystem ps in m_ParticleSystems) { ParticleSystemRenderer psRenderer = ps.GetComponent<ParticleSystemRenderer>(); if (psRenderer != null) { Undo.DestroyObjectImmediate(psRenderer); } } m_Modules[m_Modules.Length - 1] = null; } public float GetEmitterDuration() { InitialModuleUI m = m_Modules[0] as InitialModuleUI; if (m != null) return m.m_LengthInSec.floatValue; return -1.0f; } public void OnGUI(float width, bool fixedWidth) { bool isRepaintEvent = Event.current.type == EventType.Repaint; // Name of current emitter string selectedEmitterName = null; if (m_ParticleSystems.Length > 1) { selectedEmitterName = "Multiple Particle Systems"; } else if (m_ParticleSystems.Length > 0) { selectedEmitterName = m_ParticleSystems[0].gameObject.name; } if (fixedWidth) { EditorGUIUtility.labelWidth = width * 0.4f; EditorGUILayout.BeginVertical(GUILayout.Width(width)); } else { // First make sure labelWidth is at default width, then subtract EditorGUIUtility.labelWidth = 0; EditorGUIUtility.labelWidth = EditorGUIUtility.labelWidth - 4; EditorGUILayout.BeginVertical(); } { InitialModuleUI initial = (InitialModuleUI)m_Modules[0]; for (int i = 0; i < m_Modules.Length; ++i) { ModuleUI module = m_Modules[i]; if (module == null) continue; bool initialModule = (module == m_Modules[0]); // Skip if not visible (except initial module which should always be visible) if (!module.visibleUI && !initialModule) continue; // Module header size GUIContent headerLabel = new GUIContent(); Rect moduleHeaderRect; if (initialModule) moduleHeaderRect = GUILayoutUtility.GetRect(width, 25); else moduleHeaderRect = GUILayoutUtility.GetRect(width, 15); // Module content here to render it below the the header if (module.foldout) { using (new EditorGUI.DisabledScope(!module.enabled)) { Rect moduleSize = EditorGUILayout.BeginVertical(ParticleSystemStyles.Get().modulePadding); { moduleSize.y -= 4; // pull background 'up' behind title to fill rounded corners. moduleSize.height += 4; GUI.Label(moduleSize, GUIContent.none, ParticleSystemStyles.Get().moduleBgStyle); module.OnInspectorGUI(initial); } EditorGUILayout.EndVertical(); } } // TODO: Get Texture instead of static preview. Render Icon (below titlebar due to rounded corners) if (initialModule) { // Get preview of material or mesh ParticleSystemRenderer renderer = m_ParticleSystems[0].GetComponent<ParticleSystemRenderer>(); bool isEditable = (m_ParticleSystems[0].gameObject.hideFlags & HideFlags.NotEditable) == 0; float iconSize = 21; Rect iconRect = new Rect(moduleHeaderRect.x + 4, moduleHeaderRect.y + 2, iconSize, iconSize); if (isRepaintEvent && renderer != null) { bool iconRendered = false; int instanceID = 0; if (!multiEdit) { if (renderer.renderMode == ParticleSystemRenderMode.Mesh) { if (renderer.mesh != null) { instanceID = renderer.mesh.GetInstanceID(); // If the asset is dirty we ensure to get a updated one by clearing cache of temporary previews if (m_CachedMeshInstanceID != instanceID) { m_CachedMeshInstanceID = instanceID; m_CachedMeshDirtyCount = -1; } if (EditorUtility.GetDirtyCount(instanceID) != m_CachedMeshDirtyCount) { AssetPreview.ClearTemporaryAssetPreviews(); m_CachedMeshDirtyCount = EditorUtility.GetDirtyCount(instanceID); } } } else if (renderer.sharedMaterial != null) { instanceID = renderer.sharedMaterial.GetInstanceID(); // If the asset is dirty we ensure to get a updated one by clearing cache of temporary previews if (m_CachedMaterialInstanceID != instanceID) { m_CachedMaterialInstanceID = instanceID; m_CachedMaterialDirtyCount = -1; } if (EditorUtility.GetDirtyCount(instanceID) != m_CachedMaterialDirtyCount) { AssetPreview.ClearTemporaryAssetPreviews(); m_CachedMaterialDirtyCount = EditorUtility.GetDirtyCount(instanceID); } } } if (multiEdit || !isEditable) { // Presets should use the default material. instanceID = Material.GetDefaultParticleMaterial().GetInstanceID(); } if (instanceID != 0) { Texture2D icon = AssetPreview.GetAssetPreview(instanceID); if (icon != null) { GUI.DrawTexture(iconRect, icon, ScaleMode.StretchToFill, true); iconRendered = true; } } // Fill so we do not see the background when we have no icon (eg multi-edit) if (!iconRendered) { GUI.Label(iconRect, GUIContent.none, ParticleSystemStyles.Get().moduleBgStyle); } } // Select gameObject when clicking on icon // Don't attempt to select if the system is a preset. It will select the temporary object causing the // preset to deselect and destroy the particle system. (case 1198545) if (!multiEdit && EditorGUI.DropdownButton(iconRect, GUIContent.none, FocusType.Passive, GUIStyle.none) && isEditable) { // Toggle selected particle system from selection if (EditorGUI.actionKey) { List<int> newSelection = new List<int>(); int instanceID = m_ParticleSystems[0].gameObject.GetInstanceID(); newSelection.AddRange(Selection.instanceIDs); if (!newSelection.Contains(instanceID) || newSelection.Count != 1) { if (newSelection.Contains(instanceID)) newSelection.Remove(instanceID); else newSelection.Add(instanceID); } Selection.instanceIDs = newSelection.ToArray(); } else { Selection.activeInstanceID = m_ParticleSystems[0].gameObject.GetInstanceID(); } } } // Button logic for enabledness (see below for UI) Rect checkMarkRect = new Rect(moduleHeaderRect.x + 2, moduleHeaderRect.y + 1, 13, 13); if (!initialModule && GUI.Button(checkMarkRect, GUIContent.none, GUIStyle.none)) module.enabled = !module.enabled; // Button logic for plus/minus (see below for UI) Rect plusRect = new Rect(moduleHeaderRect.x + moduleHeaderRect.width - 10, moduleHeaderRect.y + moduleHeaderRect.height - 10, 10, 10); Rect plusRectInteract = new Rect(plusRect.x - 4, plusRect.y - 4, plusRect.width + 4, plusRect.height + 4); Rect infoRect = new Rect(plusRect.x - 23, plusRect.y - 8, 20, 20); if (initialModule && EditorGUI.DropdownButton(plusRectInteract, s_Texts.addModules, FocusType.Passive, GUIStyle.none)) ShowAddModuleMenu(); // Module header (last to become top most renderered) if (!string.IsNullOrEmpty(selectedEmitterName)) headerLabel.text = initialModule ? selectedEmitterName : module.displayName; else headerLabel.text = module.displayName; headerLabel.tooltip = module.toolTip; bool newToggleState = module.DrawHeader(moduleHeaderRect, headerLabel); if (newToggleState != module.foldout) { switch (Event.current.button) { case 0: bool newFoldoutState = !module.foldout; if (Event.current.control) { foreach (var moduleUi in m_Modules) if (moduleUi != null && moduleUi.visibleUI) moduleUi.foldout = newFoldoutState; } else { module.foldout = newFoldoutState; } break; case 1: if (initialModule) ShowEmitterMenu(); else ShowModuleMenu(i); break; } } // Render checkmark on top (logic: see above) if (!initialModule) { EditorGUI.showMixedValue = module.enabledHasMultipleDifferentValues; GUIStyle style = EditorGUI.showMixedValue ? ParticleSystemStyles.Get().toggleMixed : ParticleSystemStyles.Get().toggle; GUI.Toggle(checkMarkRect, module.enabled, GUIContent.none, style); EditorGUI.showMixedValue = false; } // Render plus/minus on top if (isRepaintEvent && initialModule) GUI.Label(plusRect, GUIContent.none, ParticleSystemStyles.Get().plus); if (initialModule && !string.IsNullOrEmpty(m_SupportsCullingTextLabel)) { var supportsCullingText = new GUIContent("", ParticleSystemStyles.Get().warningIcon, m_SupportsCullingTextLabel); GUI.Label(infoRect, supportsCullingText); } GUILayout.Space(1); // dist to next module } // foreach module GUILayout.Space(-1); } EditorGUILayout.EndVertical(); // end fixed moduleWidth // Apply the property, handle undo ApplyProperties(); } public void OnSceneViewGUI() { if (m_Modules == null) return; // Render bounds if (ParticleEffectUI.m_ShowBounds) { foreach (ParticleSystem ps in m_ParticleSystems) { if (multiEdit) ShowBounds(ParticleSystemEditorUtils.GetRoot(ps)); else ShowBounds(ps); } } UpdateProperties(); foreach (var module in m_Modules) { if (module == null || !module.visibleUI || !module.enabled) continue; if (module.foldout) { module.OnSceneViewGUI(); } } // Apply the property, handle undo ApplyProperties(); } private void ShowBounds(ParticleSystem ps) { if (ps.particleCount > 0) { ParticleSystemRenderer particleSystemRenderer = ps.GetComponent<ParticleSystemRenderer>(); var oldCol = Handles.color; Handles.color = s_BoundsColor; var worldBounds = particleSystemRenderer.bounds; Handles.DrawWireCube(worldBounds.center, worldBounds.size); Handles.color = oldCol; } // In multi-edit, children are not stored, so render their bounds manually if (multiEdit) { ParticleSystem[] children = ps.transform.GetComponentsInChildren<ParticleSystem>(); foreach (ParticleSystem child in children) { if (child != ps) { bool alreadySelected = m_ParticleSystems.FirstOrDefault(o => ParticleSystemEditorUtils.GetRoot(o) == child) != null; if (!alreadySelected) ShowBounds(child); } } } } public void ApplyProperties() { bool hasModifiedProperties = m_ParticleSystemSerializedObject.hasModifiedProperties; // Check the system was not destroyed such as by an Undo operation. if (m_ParticleSystemSerializedObject.targetObject != null) m_ParticleSystemSerializedObject.ApplyModifiedProperties(); if (hasModifiedProperties) { // Resimulate foreach (ParticleSystem ps in m_ParticleSystems) { ParticleSystem root = ParticleSystemEditorUtils.GetRoot(ps); if (!ParticleEffectUI.IsStopped(root) && ParticleSystemEditorUtils.resimulation) ParticleSystemEditorUtils.PerformCompleteResimulation(); } // Refresh procedural supported string UpdateParticleSystemInfoString(); } if (m_RendererSerializedObject != null && m_RendererSerializedObject.targetObject != null) m_RendererSerializedObject.ApplyModifiedProperties(); } void UpdateParticleSystemInfoString() { string supportsCullingText = ""; foreach (var module in m_Modules) { if (module == null || !module.visibleUI || !module.enabled) continue; module.UpdateCullingSupportedString(ref supportsCullingText); } if (supportsCullingText != string.Empty) { if (supportsCullingText != m_SupportsCullingText || m_SupportsCullingTextLabel == null) { m_SupportsCullingText = supportsCullingText; m_SupportsCullingTextLabel = "Procedural simulation is not supported because: " + supportsCullingText.Replace("\n", "\n" + s_Texts.bulletPoint); } } else { m_SupportsCullingText = null; m_SupportsCullingTextLabel = null; } } public void UpdateProperties() { // Check the system was not destroyed such as by an Undo operation. if (m_ParticleSystemSerializedObject.targetObject != null) m_ParticleSystemSerializedObject.UpdateIfRequiredOrScript(); if (m_RendererSerializedObject != null && m_RendererSerializedObject.targetObject != null) m_RendererSerializedObject.UpdateIfRequiredOrScript(); } void ResetModules() { // Reset all foreach (var module in m_Modules) if (module != null) { module.enabled = false; if (!ParticleEffectUI.GetAllModulesVisible()) module.visibleUI = false; } // Default setup has a renderer if (m_Modules.Last() == null) InitRendererUI(); // Default setup has shape, emission and renderer int[] defaultEnabledModulesIndicies = { 1, 2, m_Modules.Length - 1 }; for (int i = 0; i < defaultEnabledModulesIndicies.Length; ++i) { int moduleIndex = defaultEnabledModulesIndicies[i]; if (m_Modules[moduleIndex] != null) { m_Modules[moduleIndex].enabled = true; m_Modules[moduleIndex].visibleUI = true; } } } void ShowAddModuleMenu() { // Now create the menu, add items and show it GenericMenu menu = new GenericMenu(); for (int i = 0; i < s_ModuleNames.Length; ++i) { if (m_Modules[i] == null || !m_Modules[i].visibleUI) menu.AddItem(new GUIContent(s_ModuleNames[i]), false, AddModuleCallback, i); else menu.AddDisabledItem(new GUIContent(s_ModuleNames[i])); } menu.AddSeparator(""); menu.AddItem(EditorGUIUtility.TrTextContent("Show All Modules"), ParticleEffectUI.GetAllModulesVisible(), AddModuleCallback, 10000); menu.ShowAsContext(); Event.current.Use(); } void AddModuleCallback(object obj) { int index = (int)obj; if (index >= 0 && index < m_Modules.Length) { if (index == m_Modules.Length - 1) { InitRendererUI(); } else { m_Modules[index].enabled = true; m_Modules[index].foldout = true; } } else { m_ParticleEffectUI.SetAllModulesVisible(!ParticleEffectUI.GetAllModulesVisible()); } ApplyProperties(); } void ModuleMenuCallback(object obj) { int moduleIndex = (int)obj; bool isRendererModule = (moduleIndex == m_Modules.Length - 1); if (isRendererModule) { ClearRenderers(); } else { if (!ParticleEffectUI.GetAllModulesVisible()) m_Modules[moduleIndex].visibleUI = false; m_Modules[moduleIndex].enabled = false; } } void ShowModuleMenu(int moduleIndex) { // Now create the menu, add items and show it GenericMenu menu = new GenericMenu(); if (!ParticleEffectUI.GetAllModulesVisible()) menu.AddItem(EditorGUIUtility.TrTextContent("Remove"), false, ModuleMenuCallback, moduleIndex); else menu.AddDisabledItem(EditorGUIUtility.TrTextContent("Remove")); // Do not allow remove module when always show modules is enabled var copy = EditorGUIUtility.TrTextContent("Copy Module"); var paste = EditorGUIUtility.TrTextContent("Paste Module"); SerializedProperty prop = m_ParticleSystemSerializedObject.FindProperty(m_Modules[moduleIndex].moduleName); if (prop != null) { ClipboardContextMenu.overrideCopyContent = copy; ClipboardContextMenu.overridePasteContent = paste; EditorGUI.DoPropertyContextMenu(prop, null, menu); ClipboardContextMenu.overrideCopyContent = null; ClipboardContextMenu.overridePasteContent = null; Event.current.Use(); } else if (m_RendererSerializedObject.targetObjectsCount == 1) { menu.AddItem(copy, false, () => UnityEditorInternal.ComponentUtility.CopyComponent(m_RendererSerializedObject.targetObject as Component)); menu.AddItem(paste, false, () => UnityEditorInternal.ComponentUtility.PasteComponentValues(m_RendererSerializedObject.targetObject as Component)); Event.current.Use(); menu.ShowAsContext(); } } void EmitterMenuCallback(object obj) { int userData = (int)obj; switch (userData) { case 0: m_ParticleEffectUI.CreateParticleSystem(m_ParticleSystems[0], SubModuleUI.SubEmitterType.None); break; case 1: ResetModules(); break; case 2: EditorGUIUtility.PingObject(m_ParticleSystems[0]); break; default: System.Diagnostics.Debug.Assert("Enum not handled!".Length == 0); break; } } void ShowEmitterMenu() { // Now create the menu, add items and show it GenericMenu menu = new GenericMenu(); menu.AddItem(EditorGUIUtility.TrTextContent("Show Location"), false, EmitterMenuCallback, 2); menu.AddSeparator(""); if (m_ParticleSystems[0].gameObject.activeInHierarchy) menu.AddItem(EditorGUIUtility.TrTextContent("Create Particle System"), false, EmitterMenuCallback, 0); else menu.AddDisabledItem(EditorGUIUtility.TrTextContent("Create new Particle System")); menu.AddItem(EditorGUIUtility.TrTextContent("Reset"), false, EmitterMenuCallback, 1); menu.ShowAsContext(); Event.current.Use(); } private static ModuleUI[] CreateUIModules(ParticleSystemUI e, SerializedObject so) { int index = 0; // Order should match GetUIModuleNames return new ModuleUI[] { new InitialModuleUI(e, so, s_ModuleNames[index++]), new EmissionModuleUI(e, so, s_ModuleNames[index++]), new ShapeModuleUI(e, so, s_ModuleNames[index++]), new VelocityModuleUI(e, so, s_ModuleNames[index++]), new ClampVelocityModuleUI(e, so, s_ModuleNames[index++]), new InheritVelocityModuleUI(e, so, s_ModuleNames[index++]), new LifetimeByEmitterSpeedModuleUI(e, so, s_ModuleNames[index++]), new ForceModuleUI(e, so, s_ModuleNames[index++]), new ColorModuleUI(e, so, s_ModuleNames[index++]), new ColorByVelocityModuleUI(e, so, s_ModuleNames[index++]), new SizeModuleUI(e, so, s_ModuleNames[index++]), new SizeByVelocityModuleUI(e, so, s_ModuleNames[index++]), new RotationModuleUI(e, so, s_ModuleNames[index++]), new RotationByVelocityModuleUI(e, so, s_ModuleNames[index++]), new ExternalForcesModuleUI(e, so, s_ModuleNames[index++]), new NoiseModuleUI(e, so, s_ModuleNames[index++]), new CollisionModuleUI(e, so, s_ModuleNames[index++]), new TriggerModuleUI(e, so, s_ModuleNames[index++]), new SubModuleUI(e, so, s_ModuleNames[index++]), new UVModuleUI(e, so, s_ModuleNames[index++]), new LightsModuleUI(e, so, s_ModuleNames[index++]), new TrailModuleUI(e, so, s_ModuleNames[index++]), new CustomDataModuleUI(e, so, s_ModuleNames[index++]), null, // RendererModule is created separately in InitRendererUI (it can be added/removed) }; } // Names used when adding modules from a drop list public static string[] GetUIModuleNames() { // Order should match GetUIModules return new string[] { "", L10n.Tr("Emission"), L10n.Tr("Shape"), L10n.Tr("Velocity over Lifetime"), L10n.Tr("Limit Velocity over Lifetime"), L10n.Tr("Inherit Velocity"), L10n.Tr("Lifetime by Emitter Speed"), L10n.Tr("Force over Lifetime"), L10n.Tr("Color over Lifetime"), L10n.Tr("Color by Speed"), L10n.Tr("Size over Lifetime"), L10n.Tr("Size by Speed"), L10n.Tr("Rotation over Lifetime"), L10n.Tr("Rotation by Speed"), L10n.Tr("External Forces"), L10n.Tr("Noise"), L10n.Tr("Collision"), L10n.Tr("Triggers"), L10n.Tr("Sub Emitters"), L10n.Tr("Texture Sheet Animation"), L10n.Tr("Lights"), L10n.Tr("Trails"), L10n.Tr("Custom Data"), L10n.Tr("Renderer") }; } } // class ParticleSystemUI } // namespace UnityEditor
UnityCsReference/Modules/ParticleSystemEditor/ParticleSystemUI.cs/0
{ "file_path": "UnityCsReference/Modules/ParticleSystemEditor/ParticleSystemUI.cs", "repo_id": "UnityCsReference", "token_count": 17154 }
417
// 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.ComponentModel; namespace UnityEngine { public partial class ArticulationBody : Behaviour { [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Please use ArticulationBody.linearVelocity instead. (UnityUpgradable) -> linearVelocity")] public Vector3 velocity { get => linearVelocity; set => linearVelocity = value; } [Obsolete("computeParentAnchor has been renamed to matchAnchors (UnityUpgradable) -> matchAnchors")] public bool computeParentAnchor { get => matchAnchors; set => matchAnchors = value; } [Obsolete("Setting joint accelerations is not supported in forward kinematics. To have inverse dynamics take acceleration into account, use GetJointForcesForAcceleration instead",true)] extern public void SetJointAccelerations(List<float> accelerations); } }
UnityCsReference/Modules/Physics/ScriptBindings/Articulations.deprecated.cs/0
{ "file_path": "UnityCsReference/Modules/Physics/ScriptBindings/Articulations.deprecated.cs", "repo_id": "UnityCsReference", "token_count": 331 }
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; using System.ComponentModel; namespace UnityEngine { public partial class MeshCollider { [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Configuring smooth sphere collisions is no longer needed.", true)] public bool smoothSphereCollisions { get { return true; } set { } } [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("MeshCollider.skinWidth is no longer used.")] public float skinWidth { get { return 0f; } set { } } [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("MeshCollider.inflateMesh is no longer supported. The new cooking algorithm doesn't need inflation to be used.")] public bool inflateMesh { get { return false; } set { } } } }
UnityCsReference/Modules/Physics/ScriptBindings/MeshCollider.deprecated.cs/0
{ "file_path": "UnityCsReference/Modules/Physics/ScriptBindings/MeshCollider.deprecated.cs", "repo_id": "UnityCsReference", "token_count": 351 }
419
// 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/SpringJoint.h")] [NativeClass("Unity::SpringJoint")] public class SpringJoint : Joint { extern public float spring { get; set; } extern public float damper { get; set; } extern public float minDistance { get; set; } extern public float maxDistance { get; set; } extern public float tolerance { get; set; } } }
UnityCsReference/Modules/Physics/ScriptBindings/SpringJoint.bindings.cs/0
{ "file_path": "UnityCsReference/Modules/Physics/ScriptBindings/SpringJoint.bindings.cs", "repo_id": "UnityCsReference", "token_count": 236 }
420
// 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 UnityEditor.EditorTools; using UnityEditor.IMGUI.Controls; namespace UnityEditor { abstract class EditablePath2D { EditableLineHandle2D m_Handle; public EditableLineHandle2D handle => m_Handle; public abstract IList<Vector2> GetPoints(); public abstract void SetPoints(Vector3[] points); public abstract Matrix4x4 localToWorldMatrix { get; } protected EditablePath2D(bool loop, int pointCount, int minPointCount) { m_Handle = new EditableLineHandle2D(new Vector3[pointCount], loop, minPointCount, EditableLineHandle2D.LineIntersectionHighlight.Always); } public void Update() { var cached = GetPoints(); var points = m_Handle.points; if (points.Length != cached.Count) System.Array.Resize(ref points, cached.Count); for (int i = 0; i < points.Length; i++) points[i] = cached[i]; m_Handle.points = points; } } }
UnityCsReference/Modules/Physics2DEditor/Managed/Colliders/EditablePath2D.cs/0
{ "file_path": "UnityCsReference/Modules/Physics2DEditor/Managed/Colliders/EditablePath2D.cs", "repo_id": "UnityCsReference", "token_count": 498 }
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 UnityEngine; using UnityEditor.IMGUI.Controls; namespace UnityEditor { internal class JointAngularLimitHandle2D { public enum JointMotion { Locked = 0, Limited = 1, Free = 2 } private enum ArcType { Solid = 0, Wire = 1 } private static readonly Matrix4x4 s_HandleOffset = Matrix4x4.TRS(Vector3.zero, Quaternion.AngleAxis(90f, Vector3.forward), Vector3.one); private static readonly float s_LockedColorAmount = 0.5f; private static readonly Color s_LockedColor = new Color(0.5f, 0.5f, 0.5f, 0f); private List<KeyValuePair<Action, float>> m_HandleFunctionDistances = new List<KeyValuePair<Action, float>>(6); private ArcHandle m_MinHandle; private ArcHandle m_MaxHandle; private bool m_HandleColorInitialized = false; // When primary axis is limited, secondary and tertiary manipulators are reoriented about its average private Matrix4x4 m_SecondaryAxesMatrix; public float min { get { switch (jointMotion) { case JointMotion.Free: return range.x; case JointMotion.Locked: return 0f; default: return Mathf.Clamp(m_MinHandle.angle, range.x, m_MaxHandle.angle); } } set { m_MinHandle.angle = value; } } public float max { get { switch (jointMotion) { case JointMotion.Free: return range.y; case JointMotion.Locked: return 0f; default: return Mathf.Clamp(m_MaxHandle.angle, m_MinHandle.angle, range.y); } } set { m_MaxHandle.angle = value; } } public Vector2 range { get; set; } public JointMotion jointMotion { get; set; } public Color handleColor { get { if (!m_HandleColorInitialized) handleColor = Handles.xAxisColor; return m_MinHandle.angleHandleColor; } set { m_MinHandle.SetColorWithoutRadiusHandle(value, fillAlpha); m_MaxHandle.SetColorWithoutRadiusHandle(value, fillAlpha); m_HandleColorInitialized = true; } } public float radius { get { return m_MinHandle.radius; } set { m_MinHandle.radius = m_MaxHandle.radius = value; } } public float fillAlpha { get; set; } public float wireframeAlpha { get; set; } public Handles.CapFunction angleHandleDrawFunction { get { return m_MinHandle.angleHandleDrawFunction; } set { m_MinHandle.angleHandleDrawFunction = m_MaxHandle.angleHandleDrawFunction = value; } } public Handles.SizeFunction angleHandleSizeFunction { get { return m_MinHandle.angleHandleSizeFunction; } set { m_MinHandle.angleHandleSizeFunction = m_MaxHandle.angleHandleSizeFunction = value; } } // Handle functions need to be manually sorted private static float GetSortingDistance(ArcHandle handle) { Vector3 worldPosition = Handles.matrix.MultiplyPoint3x4(Quaternion.AngleAxis(handle.angle, Vector3.up) * Vector3.forward * handle.radius); Vector3 toHandle = Camera.current == null ? worldPosition : worldPosition - Camera.current.transform.position; if (Camera.current == null || Camera.current.orthographic) { Vector3 lookVector = Camera.current == null ? Vector3.forward : Camera.current.transform.forward; toHandle = lookVector * Vector3.Dot(lookVector, toHandle); } return toHandle.sqrMagnitude; } private static int CompareHandleFunctionsByDistance(KeyValuePair<Action, float> func1, KeyValuePair<Action, float> func2) { return func2.Value.CompareTo(func1.Value); } public JointAngularLimitHandle2D() { m_MinHandle = new ArcHandle(); m_MaxHandle = new ArcHandle(); jointMotion = JointMotion.Limited; radius = 1f; fillAlpha = 0.1f; wireframeAlpha = 1f; range = new Vector2(-180f, 180f); } public void DrawHandle() { m_SecondaryAxesMatrix = Handles.matrix; // Ensure handle colors are up to date handleColor = handleColor; m_MinHandle.fillColor = m_MinHandle.wireframeColor = Color.clear; m_MaxHandle.fillColor = m_MaxHandle.wireframeColor = Color.clear; // Draw fill shapes as needed Color fillScalar = new Color(1f, 1f, 1f, fillAlpha); bool draw = false; switch (jointMotion) { case JointMotion.Free: using (new Handles.DrawingScope(Handles.color * handleColor)) { Handles.DrawWireDisc(Vector3.zero, Vector3.right, radius); Handles.color *= fillScalar; Handles.DrawSolidDisc(Vector3.zero, Vector3.right, radius); } break; case JointMotion.Limited: draw = true; m_SecondaryAxesMatrix *= Matrix4x4.TRS(Vector3.zero, Quaternion.AngleAxis((min + max) * 0.5f, Vector3.left), Vector3.one); using (new Handles.DrawingScope(Handles.matrix * s_HandleOffset)) { DrawArc(m_MinHandle, m_MaxHandle, handleColor * fillScalar, ArcType.Solid); } break; case JointMotion.Locked: using (new Handles.DrawingScope(Handles.color * Color.Lerp(handleColor, s_LockedColor, s_LockedColorAmount))) { Handles.DrawWireDisc(Vector3.zero, Vector3.right, radius); } break; } // Collect and sort handle drawing functions for all enabled axes m_HandleFunctionDistances.Clear(); m_MinHandle.GetControlIDs(); m_MaxHandle.GetControlIDs(); if (draw) { using (new Handles.DrawingScope(Handles.matrix * s_HandleOffset)) { DrawArc(m_MinHandle, m_MaxHandle, handleColor, ArcType.Wire); m_HandleFunctionDistances.Add(new KeyValuePair<Action, float>(DrawMinHandle, GetSortingDistance(m_MinHandle))); m_HandleFunctionDistances.Add(new KeyValuePair<Action, float>(DrawMaxHandle, GetSortingDistance(m_MaxHandle))); } } m_HandleFunctionDistances.Sort(CompareHandleFunctionsByDistance); // Draw handles foreach (var handleFunction in m_HandleFunctionDistances) handleFunction.Key(); } private void DrawArc(ArcHandle minHandle, ArcHandle maxHandle, Color color, ArcType arcType) { float angle = maxHandle.angle - minHandle.angle; Vector3 forward = Quaternion.AngleAxis(minHandle.angle, Vector3.up) * Vector3.forward; using (new Handles.DrawingScope(Handles.color * color)) { if (arcType == ArcType.Solid) { for (int i = 0, revolutions = (int)Mathf.Abs(angle) / 360; i < revolutions; ++i) { Handles.DrawSolidArc(Vector3.zero, Vector3.up, Vector3.forward, 360f, radius); } Handles.DrawSolidArc(Vector3.zero, Vector3.up, forward, angle % 360f, radius); } else { for (int i = 0, revolutions = (int)Mathf.Abs(angle) / 360; i < revolutions; ++i) { Handles.DrawWireArc(Vector3.zero, Vector3.up, Vector3.forward, 360f, radius); } Handles.DrawWireArc(Vector3.zero, Vector3.up, forward, angle % 360f, radius); } } } private void DrawMinHandle() { using (new Handles.DrawingScope(Handles.matrix * s_HandleOffset)) { m_MinHandle.DrawHandle(); m_MinHandle.angle = Mathf.Clamp(m_MinHandle.angle, range.x, m_MaxHandle.angle); } } private void DrawMaxHandle() { using (new Handles.DrawingScope(Handles.matrix * s_HandleOffset)) { m_MaxHandle.DrawHandle(); m_MaxHandle.angle = Mathf.Clamp(m_MaxHandle.angle, m_MinHandle.angle, range.y); } } } }
UnityCsReference/Modules/Physics2DEditor/Managed/Joints/JointAngularLimitHandle2D.cs/0
{ "file_path": "UnityCsReference/Modules/Physics2DEditor/Managed/Joints/JointAngularLimitHandle2D.cs", "repo_id": "UnityCsReference", "token_count": 4787 }
422
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEditor.EditorTools; using UnityEditor.IMGUI.Controls; using UnityEngine; namespace UnityEditor { [EditorTool("Edit Capsule Collider", typeof(CapsuleCollider))] class CapsuleColliderTool : PrimitiveColliderTool<CapsuleCollider> { readonly CapsuleBoundsHandle m_BoundsHandle = new CapsuleBoundsHandle(); protected override PrimitiveBoundsHandle boundsHandle { get { return m_BoundsHandle; } } protected override void CopyColliderPropertiesToHandle(CapsuleCollider collider) { m_BoundsHandle.center = TransformColliderCenterToHandleSpace(collider.transform, collider.center); float radiusScaleFactor; Vector3 sizeScale = GetCapsuleColliderHandleScale(collider.transform.lossyScale, collider.direction, out radiusScaleFactor); m_BoundsHandle.height = m_BoundsHandle.radius = 0f; m_BoundsHandle.height = collider.height * Mathf.Abs(sizeScale[collider.direction]); m_BoundsHandle.radius = collider.radius * radiusScaleFactor; switch (collider.direction) { case 0: m_BoundsHandle.heightAxis = CapsuleBoundsHandle.HeightAxis.X; break; case 1: m_BoundsHandle.heightAxis = CapsuleBoundsHandle.HeightAxis.Y; break; case 2: m_BoundsHandle.heightAxis = CapsuleBoundsHandle.HeightAxis.Z; break; } } protected override void CopyHandlePropertiesToCollider(CapsuleCollider collider) { collider.center = TransformHandleCenterToColliderSpace(collider.transform, m_BoundsHandle.center); float radiusScaleFactor; Vector3 sizeScale = GetCapsuleColliderHandleScale(collider.transform.lossyScale, collider.direction, out radiusScaleFactor); sizeScale = InvertScaleVector(sizeScale); // only apply changes to collider radius/height if scale factor from transform is non-zero if (radiusScaleFactor != 0f) collider.radius = m_BoundsHandle.radius / radiusScaleFactor; if (sizeScale[collider.direction] != 0f) collider.height = m_BoundsHandle.height * Mathf.Abs(sizeScale[collider.direction]); } public override void OnToolGUI(EditorWindow window) { // prevent possibility that user increases height if radius scale is zero and user drags (non-moving) radius handles to exceed height extents CapsuleCollider collider = (CapsuleCollider)target; float radiusScaleFactor; GetCapsuleColliderHandleScale(collider.transform.lossyScale, collider.direction, out radiusScaleFactor); boundsHandle.axes = PrimitiveBoundsHandle.Axes.All; if (radiusScaleFactor == 0f) { switch (collider.direction) { case 0: boundsHandle.axes = PrimitiveBoundsHandle.Axes.X; break; case 1: boundsHandle.axes = PrimitiveBoundsHandle.Axes.Y; break; case 2: boundsHandle.axes = PrimitiveBoundsHandle.Axes.Z; break; } } base.OnToolGUI(window); } static Vector3 GetCapsuleColliderHandleScale(Vector3 lossyScale, int capsuleDirection, out float radiusScaleFactor) { radiusScaleFactor = 0f; for (int axis = 0; axis < 3; ++axis) { if (axis != capsuleDirection) radiusScaleFactor = Mathf.Max(radiusScaleFactor, Mathf.Abs(lossyScale[axis])); } for (int axis = 0; axis < 3; ++axis) { if (axis != capsuleDirection) lossyScale[axis] = Mathf.Sign(lossyScale[axis]) * radiusScaleFactor; } return lossyScale; } } [CustomEditor(typeof(CapsuleCollider))] [CanEditMultipleObjects] class CapsuleColliderEditor : Collider3DEditorBase { SerializedProperty m_Center; SerializedProperty m_Radius; SerializedProperty m_Height; SerializedProperty m_Direction; private static class Styles { public static readonly GUIContent directionContent = EditorGUIUtility.TrTextContent("Direction", "The axis of the capsule’s lengthwise orientation in the GameObject’s local space."); } public override void OnEnable() { base.OnEnable(); m_Center = serializedObject.FindProperty("m_Center"); m_Radius = serializedObject.FindProperty("m_Radius"); m_Height = serializedObject.FindProperty("m_Height"); m_Direction = serializedObject.FindProperty("m_Direction"); } public override void OnInspectorGUI() { serializedObject.Update(); EditorGUILayout.EditorToolbarForTarget(EditorGUIUtility.TrTempContent("Edit Collider"), this); GUILayout.Space(5); EditorGUILayout.PropertyField(m_IsTrigger, BaseStyles.triggerContent); EditorGUILayout.PropertyField(m_ProvidesContacts, BaseStyles.providesContacts); EditorGUILayout.PropertyField(m_Material, BaseStyles.materialContent); EditorGUILayout.PropertyField(m_Center, BaseStyles.centerContent); EditorGUILayout.PropertyField(m_Radius); EditorGUILayout.PropertyField(m_Height); EditorGUILayout.PropertyField(m_Direction, Styles.directionContent); ShowLayerOverridesProperties(); serializedObject.ApplyModifiedProperties(); } } }
UnityCsReference/Modules/PhysicsEditor/CapsuleColliderEditor.cs/0
{ "file_path": "UnityCsReference/Modules/PhysicsEditor/CapsuleColliderEditor.cs", "repo_id": "UnityCsReference", "token_count": 2702 }
423
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEditor; using UnityEngine.UIElements; using System; using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("Unity.Physics.Editor.ProjectSettingsBridge")] namespace UnityEditorInternal { internal interface IPhysicsProjectSettingsECSInspectorExtension { public void SetupMainPageItems(DropdownField dropDown, HelpBox infoBox, HelpBox warningBox, SerializedObject physicsManager); public void SetupSettingsTab(Tab ecsTab, SerializedObject physicsManager); } internal class PhysicsManagerInspectorBridge { public static void RegisterECSInspectorExtension(IPhysicsProjectSettingsECSInspectorExtension ext) { if (PhysicsManagerInspector.EcsExtension != null) { var cExt = PhysicsManagerInspector.EcsExtension; throw new ArgumentException($"An ECS inspector extension instance has already been registered, current: {cExt.GetType()}"); } PhysicsManagerInspector.EcsExtension = ext; } } }
UnityCsReference/Modules/PhysicsEditor/PhysicsManagerInspectorBridge.cs/0
{ "file_path": "UnityCsReference/Modules/PhysicsEditor/PhysicsManagerInspectorBridge.cs", "repo_id": "UnityCsReference", "token_count": 424 }
424
// 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 Object = UnityEngine.Object; namespace UnityEditor.Presets { [NativeType(Header = "Modules/PresetsEditor/Public/PresetType.h")] [StructLayout(LayoutKind.Sequential)] public struct PresetType : IEquatable<PresetType> { int m_NativeTypeID; MonoScript m_ManagedTypePPtr; string m_ManagedTypeFallback; public PresetType(Object o) { m_NativeTypeID = 0; m_ManagedTypePPtr = null; m_ManagedTypeFallback = string.Empty; Init_Internal(o); } internal PresetType(SerializedProperty property) { m_NativeTypeID = property.FindPropertyRelative("m_NativeTypeID").intValue; m_ManagedTypePPtr = property.FindPropertyRelative("m_ManagedTypePPtr").objectReferenceValue as MonoScript; m_ManagedTypeFallback = property.FindPropertyRelative("m_ManagedTypeFallback").stringValue; } internal PresetType(int nativeTypeID) { m_NativeTypeID = nativeTypeID; m_ManagedTypePPtr = null; m_ManagedTypeFallback = string.Empty; } internal PresetType(Type type) { m_NativeTypeID = 0; m_ManagedTypePPtr = null; m_ManagedTypeFallback = string.Empty; InitFromType_Internal(type); } internal Texture2D GetIcon() { Texture2D icon = null; if (m_ManagedTypePPtr != null) icon = AssetPreview.GetMiniThumbnail(m_ManagedTypePPtr); if (icon == null) icon = AssetPreview.GetMiniTypeThumbnailFromClassID(m_NativeTypeID); return icon; } public override bool Equals(object obj) { return obj is PresetType && Equals((PresetType)obj); } [NativeName("GetHashCode")] private extern int GetHash(); public override int GetHashCode() { return GetHash(); } public static bool operator==(PresetType a, PresetType b) { return a.Equals(b); } public static bool operator!=(PresetType a, PresetType b) { return !a.Equals(b); } public extern bool IsValid(); public extern bool IsValidDefault(); public extern string GetManagedTypeName(); private extern void Init_Internal([NotNull] Object target); private extern void InitFromType_Internal([NotNull] Type type); public bool Equals(PresetType other) { return m_NativeTypeID == other.m_NativeTypeID && m_ManagedTypePPtr == other.m_ManagedTypePPtr && m_ManagedTypeFallback == other.m_ManagedTypeFallback; } } }
UnityCsReference/Modules/PresetsEditor/Public/PresetType.bindings.cs/0
{ "file_path": "UnityCsReference/Modules/PresetsEditor/Public/PresetType.bindings.cs", "repo_id": "UnityCsReference", "token_count": 1377 }
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 System.Runtime.InteropServices; using System.Text.RegularExpressions; using UnityEditor.Connect; using UnityEditor.Profiling; using UnityEditorInternal; using UnityEngine; using UnityEngine.Analytics; using UnityEngine.Profiling; using UnityEngine.Scripting; using static UnityEditor.PlayModeAnalytics; using static UnityEditor.Profiling.Analytics.ProfilerWindowAnalytics; namespace UnityEditor.Profiling.Analytics { [RequiredByNativeCode(GenerateProxy = true)] [StructLayout(LayoutKind.Sequential)] internal struct ProfilerAnalyticsSaveLoadData : IAnalytic.IData { public string extension; public long duration; public long size; public uint frameCount; public bool customFrameRange; public string details; public bool success; public bool isLoad; public bool isSave; } [RequiredByNativeCode(GenerateProxy = true)] [StructLayout(LayoutKind.Sequential)] internal struct ProfilerAnalyticsConnectionData : IAnalytic.IData { public bool success; public string connectionDetail; public string details; } [Serializable] internal struct ProfilerAnalyticsViewUsability : IAnalytic.IData { public string element; public uint mouseEvents; public uint keyboardEvents; public double time; } [Serializable] internal struct ProfilerAnalyticsViewUsabilitySession : IAnalytic.IData { public ProfilerAnalyticsViewUsability[] session; public uint mouseEvents; public uint keyboardEvents; public double time; } [Serializable] internal struct ProfilerAnalyticsCapture : IAnalytic.IData { public bool deepProfileEnabled; public bool callStacksEnabled; public string platformName; // Editor is platform public string connectionName; } [Serializable] internal struct BottleneckLink : IAnalytic.IData { public string linkDescription; } internal static class ProfilerWindowAnalytics { const int k_MaxEventsPerHour = 1000; // Max Events send per hour. const int k_MaxNumberOfElements = 1000; //Max number of elements sent. const string k_VendorKey = "unity.profiler"; const string k_ProfilerSaveLoad = "profilerSaveLoad"; const string k_ProfilerConnection = "profilerConnection"; const string k_ProfilerElementUsability = "profilerSessionElementUsability"; const string k_ProfilerCapture = "profilerCapture"; const string k_BottlenecksModuleLinkSelected = "bottlenecksModuleLinkSelected"; static ProfilerAnalyticsViewUsabilitySession s_ProfilerSession; static List<ProfilerAnalyticsViewUsability> s_Views; static int s_CurrentViewIndex; static IAnalyticsService s_AnalyticsService; static ProfilerWindowAnalytics() { // Instantiate default editor analytics, but only for user sessions when analytics is enabled. if (!InternalEditorUtility.inBatchMode && EditorAnalytics.enabled) SetAnalyticsService(new EditorAnalyticsService()); } public static IAnalyticsService SetAnalyticsService(IAnalyticsService service) { var oldService = s_AnalyticsService; s_AnalyticsService = service; return oldService; } [AnalyticInfo(eventName: k_ProfilerElementUsability, vendorKey: k_VendorKey)] internal class ProfilerWindowDestroy : IAnalytic { public bool TryGatherData(out IAnalytic.IData data, out Exception error) { error = null; data = s_ProfilerSession; return data != null; } } [AnalyticInfo(eventName: k_ProfilerSaveLoad, vendorKey: k_VendorKey)] internal class SaveLoadEvent : IAnalytic { public SaveLoadEvent(ProfilerAnalyticsSaveLoadData data) { m_data = data; } public bool TryGatherData(out IAnalytic.IData data, out Exception error) { error = null; data = m_data; return data != null; } private ProfilerAnalyticsSaveLoadData m_data; } [AnalyticInfo(eventName: k_ProfilerConnection, vendorKey: k_VendorKey)] internal class ConnectionEvent : IAnalytic { public ConnectionEvent(ProfilerAnalyticsConnectionData data) { m_data = data; } public bool TryGatherData(out IAnalytic.IData data, out Exception error) { error = null; data = m_data; return data != null; } private ProfilerAnalyticsConnectionData m_data; } [AnalyticInfo(eventName: k_ProfilerCapture, vendorKey: k_VendorKey)] internal class CaptureEvent : IAnalytic { public CaptureEvent(ProfilerAnalyticsCapture data) { m_data = data; } public bool TryGatherData(out IAnalytic.IData data, out Exception error) { error = null; data = m_data; return data != null; } private ProfilerAnalyticsCapture m_data; } [AnalyticInfo(eventName: k_BottlenecksModuleLinkSelected, vendorKey: k_VendorKey)] internal class BottleneckLinkEvent : IAnalytic { public BottleneckLinkEvent(BottleneckLink data) { m_data = data; } public bool TryGatherData(out IAnalytic.IData data, out Exception error) { error = null; data = m_data; return data != null; } private BottleneckLink m_data; } /// <summary> /// Reset analytics tracking on profiler window open and record the session start time. /// </summary> public static void OnProfilerWindowAwake() { ClearElementUsabilityQueue(EditorApplication.timeSinceStartup); } /// <summary> /// Sent out all accumulated view change events and reset analytics tracking. /// </summary> public static void OnProfilerWindowDestroy() { SendElementUsabilityEventsAndClearQueue(); } /// <summary> /// Increment mouse event count for the current session and view. /// </summary> public static void RecordMouseDownUsabilityEvent() { if (s_Views == null || s_CurrentViewIndex == -1) return; s_ProfilerSession.mouseEvents++; var view = s_Views[s_CurrentViewIndex]; view.mouseEvents++; s_Views[s_CurrentViewIndex] = view; } /// <summary> /// Increment key event count for the current session and view. /// </summary> public static void RecordKeyDownUsabilityEvent() { if (s_Views == null || s_CurrentViewIndex == -1) return; s_ProfilerSession.keyboardEvents++; var view = s_Views[s_CurrentViewIndex]; view.keyboardEvents++; s_Views[s_CurrentViewIndex] = view; } /// <summary> /// The function will accumulate a sequence of view changes and will send out an event once we get into the view switch cycles. /// E.g. when user goes through CPU Hierarchy view, CPU Timeline view and then Memory module we will send an array of ["CPU;Hierarchy", "CPU;Timeline", "Memory"]. /// But for the sequence CPU View, Memory View, CPU View we will send 2 events - ["CPU;Hierarchy", "Memory"] and ["CPU;Hierarchy"]. /// This way we can track individual views usage as well as detect view flows. /// </summary> /// <param name="element">View name</param> public static void SwitchActiveView(string element) { if (string.IsNullOrEmpty(element)) throw new ArgumentNullException(nameof(element)); // Selecting the same element if (s_Views != null && s_CurrentViewIndex >= 0 && s_CurrentViewIndex < s_Views.Count && s_Views[s_CurrentViewIndex].element == element) return; // Check if we start a new sequence or continuing the old one s_Views ??= new List<ProfilerAnalyticsViewUsability>(); var idx = s_Views.FindIndex(x => x.element == element); if (idx != -1) { // Views looped, send data out and start a new sequence. // This way we are able to track sequences and bundle events together to avoid frequent sends. SendElementUsabilityEventsAndClearQueue(); } // New element has been selected. // Update time of the current view var currentTime = EditorApplication.timeSinceStartup; if (s_CurrentViewIndex != -1 && s_CurrentViewIndex < s_Views.Count) { var view = s_Views[s_CurrentViewIndex]; view.time = currentTime - view.time; s_Views[s_CurrentViewIndex] = view; } // Add new view to the array and record the activation time. s_Views.Add(new ProfilerAnalyticsViewUsability() { element = element, mouseEvents = 0, keyboardEvents = 0, time = currentTime, }); s_CurrentViewIndex = s_Views.Count - 1; } static void SendElementUsabilityEventsAndClearQueue() { // Check if there is anything to send if (s_Views == null || s_Views.Count == 0) return; if (s_AnalyticsService == null) return; // Update duration for the current view and send all accumulated events. var view = s_Views[s_CurrentViewIndex]; view.time = EditorApplication.timeSinceStartup - view.time; s_Views[s_CurrentViewIndex] = view; var currentTime = EditorApplication.timeSinceStartup; s_ProfilerSession.session = s_Views.ToArray(); s_ProfilerSession.time = currentTime - s_ProfilerSession.time; ProfilerWindowDestroy analytic = new ProfilerWindowDestroy(); s_AnalyticsService.SendAnalytic(analytic); ClearElementUsabilityQueue(currentTime); } static void ClearElementUsabilityQueue(double startTime) { s_ProfilerSession = new ProfilerAnalyticsViewUsabilitySession() { session = null, mouseEvents = 0, keyboardEvents = 0, time = EditorApplication.timeSinceStartup, }; s_Views?.Clear(); s_CurrentViewIndex = -1; } /// <summary> /// Send event when we start getting data from the stream /// </summary> public static void StartCapture() { if (s_AnalyticsService == null) return; var captureEvt = new ProfilerAnalyticsCapture { callStacksEnabled = ProfilerDriver.memoryRecordMode != 0, deepProfileEnabled = ProfilerDriver.deepProfiling, // Includes platform name or Editor is profiling Editor connectionName = ProfilerDriver.GetConnectionIdentifier(ProfilerDriver.connectedProfiler), // Editor platform name platformName = Application.platform.ToString() }; CaptureEvent analytic = new CaptureEvent(captureEvt); s_AnalyticsService.SendAnalytic(analytic); } public static void SendSaveLoadEvent(ProfilerAnalyticsSaveLoadData data) { if (s_AnalyticsService == null) return; SaveLoadEvent analytic = new SaveLoadEvent(data); s_AnalyticsService.SendAnalytic(analytic); } public static void SendConnectionEvent(ProfilerAnalyticsConnectionData data) { if (s_AnalyticsService == null) return; ConnectionEvent analytic = new ConnectionEvent(data); s_AnalyticsService.SendAnalytic(analytic); } public static void SendBottleneckLinkSelectedEvent(string linkDescription) { if (s_AnalyticsService == null) return; var data = new BottleneckLink { linkDescription = linkDescription }; BottleneckLinkEvent analytic = new BottleneckLinkEvent(data); s_AnalyticsService.SendAnalytic(analytic); } } }
UnityCsReference/Modules/ProfilerEditor/ProfilerWindow/Analytics/ProfilerWindowAnalytics.cs/0
{ "file_path": "UnityCsReference/Modules/ProfilerEditor/ProfilerWindow/Analytics/ProfilerWindowAnalytics.cs", "repo_id": "UnityCsReference", "token_count": 5575 }
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 System.Text.RegularExpressions; using Unity.Profiling.Editor; using UnityEngine; using UnityEditor; using UnityEditor.Profiling; namespace UnityEditorInternal { internal class Chart { public delegate void ChangedEventHandler(Chart sender); public Rect lastChartRect = Rect.zero; private static int s_ChartHash = "Charts".GetHashCode(); public const float kSideWidth = 180.0f; protected const int k_DistanceFromTopToFirstLegendLabel = 38; protected const int k_LegendSeriesLabelHeight = 14; protected const int k_LegendSeriesLabelOffset = 5; protected const int k_MinimumHeight = 130; private const float k_LineWidth = 2f; private const int k_LabelLayoutMaxIterations = 5; private Vector3[] m_LineDrawingPoints; private float[] m_StackedSampleSums; private static readonly Color s_OverlayBackgroundDimFactor = new Color(0.9f, 0.9f, 0.9f, 0.4f); protected Action<bool> onDoSeriesToggle; string m_ChartSettingsName; int m_chartControlID; public void LoadAndBindSettings(string chartSettingsName, ChartViewData cdata) { m_ChartSettingsName = chartSettingsName; LoadChartsSettings(cdata); } public void DeleteSettings() { DeleteChartsSettings(); } static class Styles { public static readonly GUIStyle background = "OL Box"; public static readonly GUIStyle legendHeaderLabel = "ProfilerHeaderLabel"; public static readonly GUIStyle legendBackground = "ProfilerLeftPane"; public static readonly GUIStyle rightPane = "ProfilerRightPane"; public static readonly GUIStyle seriesLabel = "ProfilerPaneSubLabel"; public static readonly GUIStyle seriesDragHandle = "RL DragHandle"; public static readonly GUIStyle whiteLabel = "ProfilerBadge"; public static readonly GUIStyle noDataOverlayBox = "ProfilerNoDataAvailable"; public static readonly GUIContent notSupportedWarningIcon = new GUIContent("", EditorGUIUtility.LoadIcon("console.warnicon.sml")); public static readonly float labelDropShadowOpacity = 0.3f; public static readonly float labelLerpToWhiteAmount = 0.5f; public static readonly Color selectedFrameColor = new Color(1, 1, 1, 0.7f); public static readonly Color noDataSeparatorColor = new Color(.8f, .8f, .8f, 0.5f); static Styles() { seriesLabel.wordWrap = false; seriesLabel.clipping = TextClipping.Clip; } } public event ChangedEventHandler closed; public event ChangedEventHandler selected; public GUIContent legendHeaderLabel { get; set; } public Vector2 labelRange { get; set; } public Vector2 graphRange { get; set; } string orderPreferenceKey => m_ChartSettingsName + "Order"; string visiblePreferenceKey => m_ChartSettingsName + "Visible"; int m_DragItemIndex = -1; Vector2 m_DragDownPos; int[] m_OldChartOrder; public Func<int, string> statisticsAvailabilityMessage = null; public Chart() { labelRange = new Vector2(-Mathf.Infinity, Mathf.Infinity); graphRange = new Vector2(-Mathf.Infinity, Mathf.Infinity); } public virtual void Close() { closed(this); } private int MoveSelectedFrame(int selectedFrame, ChartViewData cdata, int direction) { int length = cdata.GetDataDomainLength(); int newSelectedFrame = selectedFrame + direction; if (newSelectedFrame < cdata.firstSelectableFrame || newSelectedFrame > cdata.chartDomainOffset + length - 1) return selectedFrame; return newSelectedFrame; } private int DoFrameSelectionDrag(float x, Rect r, ChartViewData cdata, int len) { int frame = Mathf.RoundToInt((x - r.x) / r.width * len - 0.5f); GUI.changed = true; return Mathf.Clamp(frame + cdata.chartDomainOffset, cdata.firstSelectableFrame, cdata.chartDomainOffset + len - 1); } private int HandleFrameSelectionEvents(int selectedFrame, int chartControlID, Rect chartFrame, ChartViewData cdata) { Event evt = Event.current; switch (evt.type) { case EventType.MouseDown: if (chartFrame.Contains(evt.mousePosition)) { GUIUtility.keyboardControl = chartControlID; GUIUtility.hotControl = chartControlID; int len = cdata.GetDataDomainLength(); selectedFrame = DoFrameSelectionDrag(evt.mousePosition.x, chartFrame, cdata, len); evt.Use(); } break; case EventType.MouseDrag: if (GUIUtility.hotControl == chartControlID) { int len = cdata.GetDataDomainLength(); selectedFrame = DoFrameSelectionDrag(evt.mousePosition.x, chartFrame, cdata, len); evt.Use(); } break; case EventType.MouseUp: if (GUIUtility.hotControl == chartControlID) { GUIUtility.hotControl = 0; evt.Use(); } break; case EventType.KeyDown: if (GUIUtility.keyboardControl != chartControlID || selectedFrame < 0) break; if (evt.keyCode == KeyCode.LeftArrow) { selectedFrame = MoveSelectedFrame(selectedFrame, cdata, -1); evt.Use(); } else if (evt.keyCode == KeyCode.RightArrow) { selectedFrame = MoveSelectedFrame(selectedFrame, cdata, 1); evt.Use(); } break; } return selectedFrame; } public void OnLostFocus() { if (GUIUtility.hotControl == m_chartControlID) { GUIUtility.hotControl = 0; } m_chartControlID = 0; } protected virtual void DoLegendGUI(Rect position, ProfilerModuleChartType type, ChartViewData cdata, EventType evtType, bool active) { Styles.legendHeaderLabel.clipping = TextClipping.Ellipsis; if (Event.current.type == EventType.Repaint) Styles.legendBackground.Draw(position, GUIContent.none, false, false, active, false); Rect headerRect = position; GUIContent headerLabel = legendHeaderLabel ?? GUIContent.none; var headerSize = Styles.legendHeaderLabel.CalcSize(headerLabel); headerRect.height = headerSize.y; // Leave space for the GPU Profiler's Warning Icon, 16 pixels wide, 2 pixels margin = 20 pixels. // Without this spacer, the tooltip of the header would be displayed instead of the one for the Warning Icon. headerRect.xMax -= 20; GUI.Label(headerRect, headerLabel, Styles.legendHeaderLabel); position.yMin += headerRect.height + Styles.legendHeaderLabel.margin.bottom; position.xMin += k_LegendSeriesLabelOffset; position.xMax -= k_LegendSeriesLabelOffset; DoSeriesList(position, m_chartControlID, type, cdata); } public int DoGUI(Rect chartRect, ProfilerModuleChartType type, int selectedFrame, ChartViewData cdata, bool active) { if (cdata == null) return selectedFrame; m_chartControlID = GUIUtility.GetControlID(s_ChartHash, FocusType.Keyboard); Rect r = chartRect; r.x += kSideWidth; r.width -= kSideWidth; Event evt = Event.current; EventType evtType = evt.GetTypeForControl(m_chartControlID); // Handle chart selection. if (!active && evtType == EventType.MouseDown && chartRect.Contains(evt.mousePosition) && selected != null) { ChartSelected(); // Selecting a chart blocks further interaction, such as selecting a frame. Only the selected chart can be interacted with. GUIUtility.ExitGUI(); } if (evtType == EventType.Repaint) lastChartRect = r; // if we are not dragging labels, handle graph frame selection if (m_DragItemIndex == -1) selectedFrame = HandleFrameSelectionEvents(selectedFrame, m_chartControlID, r, cdata); Rect sideRect = r; sideRect.x -= kSideWidth; sideRect.width = kSideWidth; DoLegendGUI(sideRect, type, cdata, evtType, active); if (evt.type == EventType.Repaint) { Styles.rightPane.Draw(r, false, false, active, false); r.height -= 1.0f; // do not draw the bottom pixel if (type.IsStackedChartType()) DrawChartStacked(selectedFrame, cdata, r, active, type); else DrawChartLine(selectedFrame, cdata, r, active); } return selectedFrame; } public void ChartSelected() { selected(this); } private void DrawSelectedFrame(int selectedFrame, ChartViewData cdata, Rect r) { if (cdata.firstSelectableFrame != -1 && selectedFrame - cdata.firstSelectableFrame >= 0) DrawVerticalLine(selectedFrame, cdata, r, Styles.selectedFrameColor, 1.0f); } internal static void DrawVerticalLine(int frame, ChartViewData cdata, Rect r, Color color, float minWidth, float maxWidth = 0) { if (Event.current.type != EventType.Repaint) return; frame -= cdata.chartDomainOffset; if (frame < 0) return; float domainSize = cdata.GetDataDomainLength(); float lineWidth = Mathf.Max(minWidth, r.width / domainSize); if (maxWidth > 0) lineWidth = Mathf.Min(maxWidth, lineWidth); HandleUtility.ApplyWireMaterial(); GL.Begin(GL.QUADS); GL.Color(color); GL.Vertex3(r.x + r.width / domainSize * frame, r.y + 1, 0); GL.Vertex3(r.x + r.width / domainSize * frame + lineWidth, r.y + 1, 0); GL.Vertex3(r.x + r.width / domainSize * frame + lineWidth, r.yMax, 0); GL.Vertex3(r.x + r.width / domainSize * frame, r.yMax, 0); GL.End(); } private void DrawMaxValueScale(ChartViewData cdata, Rect r) { Handles.Label(new Vector3(r.x + r.width / 2 - 20, r.yMin + 2, 0), "Scale: " + cdata.maxValue); } private void DrawChartLine(int selectedFrame, ChartViewData cdata, Rect r, bool chartActive) { for (int i = 0; i < cdata.numSeries; i++) { DrawChartItemLine(r, cdata, i); } if (cdata.maxValue > 0) { DrawMaxValueScale(cdata, r); } DrawOverlayBoxes(cdata, r, chartActive); DrawSelectedFrame(selectedFrame, cdata, r); DrawLabels(r, cdata, selectedFrame, ProfilerModuleChartType.Line); } List<int> m_cachedFramesWithSeparatorLines = new List<int>(); void DrawOverlayBoxes(ChartViewData cdata, Rect r, bool chartActive) { m_cachedFramesWithSeparatorLines.Clear(); if (Event.current.type == EventType.Repaint && cdata.dataAvailable != null) { r.height += 1; int lastFrameBeforeStatisticsAvailabilityChanged = 0; int lastStatisticsState = 1; int frameDataLength = cdata.dataAvailable.Length; for (int frame = 0; frame < frameDataLength; frame++) { bool hasDataForFrame = (cdata.dataAvailable[frame] & ChartViewData.dataAvailableBit) == ChartViewData.dataAvailableBit; if (hasDataForFrame) { if (lastFrameBeforeStatisticsAvailabilityChanged < frame - 1) { DrawOverlayBox(r, lastFrameBeforeStatisticsAvailabilityChanged, frame, frameDataLength, chartActive, Styles.noDataOverlayBox, lastStatisticsState); } lastStatisticsState = ChartViewData.dataAvailableBit; lastFrameBeforeStatisticsAvailabilityChanged = frame; } else if (lastStatisticsState != cdata.dataAvailable[frame]) { // Not bitwise comparison because this here just checks that the previous frame didn't just contain normal available data if (lastStatisticsState != ChartViewData.dataAvailableBit) { // a new reason for missing data has started here, flush out the old one DrawOverlayBox(r, lastFrameBeforeStatisticsAvailabilityChanged, frame, frameDataLength, chartActive, Styles.noDataOverlayBox, lastStatisticsState); m_cachedFramesWithSeparatorLines.Add(frame + cdata.chartDomainOffset); } lastFrameBeforeStatisticsAvailabilityChanged = frame; lastStatisticsState = cdata.dataAvailable[frame]; } } if (lastFrameBeforeStatisticsAvailabilityChanged < frameDataLength - 1) { DrawOverlayBox(r, lastFrameBeforeStatisticsAvailabilityChanged, frameDataLength - 1, frameDataLength, chartActive, Styles.noDataOverlayBox, lastStatisticsState); } } foreach (var frame in m_cachedFramesWithSeparatorLines) { DrawVerticalLine(frame, cdata, r, Styles.noDataSeparatorColor, 1f, 1f); } } void DrawOverlayBox(Rect r, int startFrame, int endFrame, int frameDataLength, bool chartActive, GUIStyle style, int statisticsAvailabilityState) { float gracePixels = -1; float domainSize = frameDataLength - 1; float startXOffest = Mathf.RoundToInt(r.width * startFrame / domainSize) + gracePixels; float endXOffest = Mathf.RoundToInt(r.width * endFrame / domainSize) - gracePixels; Rect noDataRect = r; noDataRect.x += Mathf.Max(startXOffest, 0); noDataRect.width = Mathf.Min(endXOffest - startXOffest, r.width - (noDataRect.x - r.x)); string message = ""; GUIContent content = GUIContent.none; if (statisticsAvailabilityMessage != null) { message = statisticsAvailabilityMessage(statisticsAvailabilityState); if (message != null) { // Remove hyperlinks for the player settings from tooltip, since they can't be clicked. message = Regex.Replace(message, @"\(<a playersettingslink=.*<\/a>\)", ""); } content = new GUIContent("", message); } // draw tooltip int style.Draw(noDataRect, content, false, false, chartActive, false); if (!string.IsNullOrEmpty(message)) { var size = EditorStyles.label.CalcSize(Styles.notSupportedWarningIcon); var position = new Vector2(noDataRect.width / 2 - size.x / 2, noDataRect.height / 2 - size.y / 2); if (size.x <= noDataRect.width && message != null) { Styles.notSupportedWarningIcon.tooltip = message; var labelRect = new Rect(noDataRect.position + position, size); GUI.Label(labelRect, Styles.notSupportedWarningIcon); } } } private void DrawChartStacked(int selectedFrame, ChartViewData cdata, Rect r, bool chartActive, ProfilerModuleChartType type) { HandleUtility.ApplyWireMaterial(); int numSamples = cdata.GetDataDomainLength(); if (numSamples <= 0) return; if (m_StackedSampleSums == null || m_StackedSampleSums.Length < numSamples) m_StackedSampleSums = new float[numSamples]; for (int i = 0; i < numSamples; ++i) m_StackedSampleSums[i] = 0f; for (int i = 0; i < cdata.numSeries; i++) { if (cdata.hasOverlay) DrawChartItemStackedOverlay(r, i, cdata, m_StackedSampleSums); DrawChartItemStacked(r, i, cdata, m_StackedSampleSums); } DrawOverlayBoxes(cdata, r, chartActive); DrawSelectedFrame(selectedFrame, cdata, r); DrawGridStacked(r, cdata); DrawLabels(r, cdata, selectedFrame, type); } internal static void DoLabel(float x, float y, string text, float alignment) { if (string.IsNullOrEmpty(text)) return; GUIContent content = EditorGUIUtility.TempContent(text); Vector2 size = Styles.whiteLabel.CalcSize(content); Rect r = new Rect(x + size.x * alignment, y, size.x, size.y); EditorGUI.DoDropShadowLabel(r, content, Styles.whiteLabel, Styles.labelDropShadowOpacity); } private void DrawGridStacked(Rect r, ChartViewData cdata) { if (Event.current.type != EventType.Repaint || cdata.grid == null || cdata.gridLabels == null) return; GL.Begin(GL.LINES); GL.Color(new Color(1, 1, 1, 0.2f)); float rangeScale = cdata.series[0].rangeAxis.sqrMagnitude == 0f ? 0f : 1f / (cdata.series[0].rangeAxis.y - cdata.series[0].rangeAxis.x) * r.height; float rectBottom = r.y + r.height; for (int i = 0; i < cdata.grid.Length; ++i) { float y = rectBottom - (cdata.grid[i] - cdata.series[0].rangeAxis.x) * rangeScale; if (y > r.y) { GL.Vertex3(r.x + 80, y, 0.0f); GL.Vertex3(r.x + r.width, y, 0.0f); } } GL.End(); for (int i = 0; i < cdata.grid.Length; ++i) { float y = rectBottom - (cdata.grid[i] - cdata.series[0].rangeAxis.x) * rangeScale; if (y > r.y) { DoLabel(r.x + 5, y - 12, cdata.gridLabels[i], 0.0f); } } } private struct LabelLayoutData { public Rect position; public float desiredYPosition; } private readonly List<LabelLayoutData> m_LabelData = new List<LabelLayoutData>(16); private readonly List<int> m_LabelOrder = new List<int>(16); private readonly List<int> m_MostOverlappingLabels = new List<int>(16); private readonly List<int> m_OverlappingLabels = new List<int>(16); private readonly List<float> m_SelectedFrameValues = new List<float>(16); private void DrawLabels(Rect chartPosition, ChartViewData data, int selectedFrame, ProfilerModuleChartType chartType) { if (data.selectedLabels == null || Event.current.type != EventType.Repaint) return; if (selectedFrame == -1 && ProfilerUserSettings.showStatsLabelsOnCurrentFrame) selectedFrame = ProfilerDriver.lastFrameIndex; // exit early if the selected frame is outside the domain of the chart var domain = data.GetDataDomain(); if ( selectedFrame < data.firstSelectableFrame || selectedFrame > data.chartDomainOffset + (int)(domain.y - domain.x) || domain.y - domain.x == 0f ) return; var selectedIndex = selectedFrame - data.chartDomainOffset; m_LabelOrder.Clear(); m_LabelOrder.AddRange(data.order); // get values of all series and cumulative value of all enabled stacks m_SelectedFrameValues.Clear(); var stacked = chartType.IsStackedChartType(); var numLabels = 0; for (int s = 0; s < data.numSeries; ++s) { var chartData = data.hasOverlay ? data.overlays[s] : data.series[s]; var value = chartData.yValues[selectedIndex] * chartData.yScale; m_SelectedFrameValues.Add(value); if (data.series[s].enabled) { ++numLabels; } } if (numLabels == 0) return; // populate layout data array with default data m_LabelData.Clear(); // leave some space for "Selected" overlay in CPU view... if (data.hasOverlay) chartPosition.yMin += EditorGUIUtility.singleLineHeight; var selectedFrameMidline = chartPosition.x + chartPosition.width * ((selectedIndex + 0.5f) / (domain.y - domain.x)); var maxLabelWidth = 0f; numLabels = 0; for (int s = 0; s < data.numSeries; ++s) { var labelData = new LabelLayoutData(); var chartData = data.series[s]; var value = m_SelectedFrameValues[s]; if (chartData.enabled && value >= labelRange.x && value <= labelRange.y) { var rangeAxis = chartData.rangeAxis; var rangeSize = rangeAxis.sqrMagnitude == 0f ? 1f : rangeAxis.y * chartData.yScale - rangeAxis.x; // convert stacked series to cumulative value of enabled series if (stacked) { var accumulatedValues = 0f; int currentChartIndex = m_LabelOrder.FindIndex(x => x == s); for (int i = currentChartIndex - 1; i >= 0; --i) { var otherSeriesIdx = data.order[i]; var otherChartData = data.hasOverlay ? data.overlays[otherSeriesIdx] : data.series[otherSeriesIdx]; bool enabled = data.series[otherSeriesIdx].enabled; if (enabled) { accumulatedValues += otherChartData.yValues[selectedIndex] * otherChartData.yScale; } } // labels for stacked series will be in the middle of their stacks value = accumulatedValues + (0.5f * value); } // default position is left aligned to midline var position = new Vector2( // offset by half a point so there is a 1-point gap down the midline if labels are on both sides selectedFrameMidline + 0.5f, chartPosition.y + chartPosition.height * (1.0f - ((value * chartData.yScale - rangeAxis.x) / rangeSize)) ); var size = Styles.whiteLabel.CalcSize(EditorGUIUtility.TempContent(data.selectedLabels[s])); position.y -= 0.5f * size.y; position.y = Mathf.Clamp(position.y, chartPosition.yMin, chartPosition.yMax - size.y); labelData.position = new Rect(position, size); labelData.desiredYPosition = labelData.position.center.y; ++numLabels; } m_LabelData.Add(labelData); maxLabelWidth = Mathf.Max(maxLabelWidth, labelData.position.width); } if (numLabels == 0) return; // line charts order labels based on series values if (!stacked) m_LabelOrder.Sort(SortLineLabelIndices); // right align labels to the selected frame midline if approaching right border if (selectedFrameMidline > chartPosition.x + chartPosition.width - maxLabelWidth) { for (int s = 0; s < data.numSeries; ++s) { var label = m_LabelData[s]; label.position.x -= label.position.width; m_LabelData[s] = label; } } // alternate right/left alignment if in the middle else if (selectedFrameMidline > chartPosition.x + maxLabelWidth) { var processed = 0; for (int s = 0; s < data.numSeries; ++s) { var labelIndex = m_LabelOrder[s]; if (m_LabelData[labelIndex].position.size.sqrMagnitude == 0f) continue; if ((processed & 1) == 0) { var label = m_LabelData[labelIndex]; // ensure there is a 1-point gap down the midline label.position.x -= label.position.width + 1f; m_LabelData[labelIndex] = label; } ++processed; } } // separate overlapping labels for (int it = 0; it < k_LabelLayoutMaxIterations; ++it) { m_MostOverlappingLabels.Clear(); // work on the biggest cluster of overlapping rects for (int s1 = 0; s1 < data.numSeries; ++s1) { m_OverlappingLabels.Clear(); m_OverlappingLabels.Add(s1); if (m_LabelData[s1].position.size.sqrMagnitude == 0f) continue; for (int s2 = 0; s2 < data.numSeries; ++s2) { if (m_LabelData[s2].position.size.sqrMagnitude == 0f) continue; if (s1 != s2 && m_LabelData[s1].position.Overlaps(m_LabelData[s2].position)) m_OverlappingLabels.Add(s2); } if (m_OverlappingLabels.Count > m_MostOverlappingLabels.Count) { m_MostOverlappingLabels.Clear(); m_MostOverlappingLabels.AddRange(m_OverlappingLabels); } } // finish if there are no more overlapping rects if (m_MostOverlappingLabels.Count == 1) break; float totalHeight; var geometricCenter = GetGeometricCenter(m_MostOverlappingLabels, m_LabelData, out totalHeight); // account for other rects that will overlap after expanding var foundOverlaps = true; while (foundOverlaps) { foundOverlaps = false; var minY = geometricCenter - 0.5f * totalHeight; var maxY = geometricCenter + 0.5f * totalHeight; for (int s = 0; s < data.numSeries; ++s) { if (m_MostOverlappingLabels.Contains(s)) continue; var testRect = m_LabelData[s].position; if (testRect.size.sqrMagnitude == 0f) continue; var x = testRect.xMax < selectedFrameMidline ? testRect.xMax : testRect.xMin; if ( testRect.Contains(new Vector2(x, minY)) || testRect.Contains(new Vector2(x, maxY)) ) { m_MostOverlappingLabels.Add(s); foundOverlaps = true; } } GetGeometricCenter(m_MostOverlappingLabels, m_LabelData, out totalHeight); // keep labels inside chart rect if (geometricCenter - 0.5f * totalHeight < chartPosition.yMin) geometricCenter = chartPosition.yMin + 0.5f * totalHeight; else if (geometricCenter + 0.5f * totalHeight > chartPosition.yMax) geometricCenter = chartPosition.yMax - 0.5f * totalHeight; } // separate overlapping rects and distribute them away from their geometric center m_MostOverlappingLabels.Sort(SortOverlappingRectIndices); var heightAllotted = 0f; for (int i = 0; i < m_MostOverlappingLabels.Count; ++i) { var labelIndex = m_MostOverlappingLabels[i]; var label = m_LabelData[labelIndex]; label.position.y = geometricCenter - totalHeight * 0.5f + heightAllotted; m_LabelData[labelIndex] = label; heightAllotted += label.position.height; } } // draw the labels var oldContentColor = GUI.contentColor; for (int s = 0; s < data.numSeries; ++s) { var labelIndex = m_LabelOrder[s]; if (m_LabelData[labelIndex].position.size.sqrMagnitude == 0f) continue; GUI.contentColor = Color.Lerp(data.series[labelIndex].color, Color.white, Styles.labelLerpToWhiteAmount); var layoutData = m_LabelData[labelIndex]; EditorGUI.DoDropShadowLabel( layoutData.position, EditorGUIUtility.TempContent(data.selectedLabels[labelIndex]), Styles.whiteLabel, Styles.labelDropShadowOpacity ); } GUI.contentColor = oldContentColor; } private int SortLineLabelIndices(int index1, int index2) { return -m_LabelData[index1].desiredYPosition.CompareTo(m_LabelData[index2].desiredYPosition); } private int SortOverlappingRectIndices(int index1, int index2) { return -m_LabelOrder.IndexOf(index1).CompareTo(m_LabelOrder.IndexOf(index2)); } private float GetGeometricCenter(List<int> overlappingRects, List<LabelLayoutData> labelData, out float totalHeight) { var geometricCenter = 0f; totalHeight = 0f; for (int i = 0, count = overlappingRects.Count; i < count; ++i) { var labelIndex = overlappingRects[i]; geometricCenter += labelData[labelIndex].desiredYPosition; totalHeight += labelData[labelIndex].position.height; } return geometricCenter / overlappingRects.Count; } private void DrawChartItemLine(Rect r, ChartViewData cdata, int index) { ChartSeriesViewData series = cdata.series[index]; if (!series.enabled) return; if (m_LineDrawingPoints == null || series.numDataPoints > m_LineDrawingPoints.Length) m_LineDrawingPoints = new Vector3[series.numDataPoints]; Vector2 domain = cdata.GetDataDomain(); float domainSize = cdata.GetDataDomainLength(); if (domainSize <= 0f) return; float domainScale = 1f / (domainSize) * r.width; float rangeScale = cdata.series[index].rangeAxis.sqrMagnitude == 0f ? 0f : 1f / (cdata.series[index].rangeAxis.y - cdata.series[index].rangeAxis.x) * r.height; float rectBottom = r.y + r.height; bool passedFirstValidValue = false; for (int i = 0; i < series.numDataPoints; ++i) { float yValue = series.yValues[i]; if (yValue == -1f) { if (!passedFirstValidValue) { continue; } // once we started drawing the points in the line, we have to keep going, otherwise the line will interpolate over frames with missing data, leading to misleading visuals. // alternatively we'd have to split the line here, which might be better. // consider splitting in a future version yValue = 0; } yValue *= series.yScale; if (!passedFirstValidValue) { passedFirstValidValue = true; // first valid point found. Set all skipped points in the line point array to the current one, the line starts here for (int k = 0; k < i; k++) { m_LineDrawingPoints[k].Set( (series.firstXValue + i - domain.x + 0.5f) * domainScale + r.x, rectBottom - (Mathf.Clamp(yValue, graphRange.x, graphRange.y) - series.rangeAxis.x) * rangeScale, 0f ); } } m_LineDrawingPoints[i].Set( (series.firstXValue + i - domain.x + 0.5f) * domainScale + r.x, rectBottom - (Mathf.Clamp(yValue, graphRange.x, graphRange.y) - series.rangeAxis.x) * rangeScale, 0f ); } if (passedFirstValidValue) { using (new Handles.DrawingScope(cdata.series[index].color)) Handles.DrawAAPolyLine(k_LineWidth, series.numDataPoints, m_LineDrawingPoints); } } private void DrawChartItemStacked(Rect r, int index, ChartViewData cdata, float[] stackedSampleSums) { int numSamples = cdata.GetDataDomainLength(); float step = r.width / numSamples; index = cdata.order[index]; if (!cdata.series[index].enabled) return; Color color = cdata.series[index].color; if (cdata.hasOverlay) color *= s_OverlayBackgroundDimFactor; GL.Begin(GL.TRIANGLE_STRIP); GL.Color(color); float x = r.x + step * 0.5f; float rangeScale = cdata.series[0].rangeAxis.sqrMagnitude == 0f ? 0f : 1f / (cdata.series[0].rangeAxis.y - cdata.series[0].rangeAxis.x) * r.height; float rectBottom = r.y + r.height; float rangeStart = cdata.series[0].rangeAxis.x; bool passedFirstValidValue = false; const int vertexBufferSize = 512; Span<Vector3> vertexBuffer = stackalloc Vector3[vertexBufferSize]; int vertexBufferOffset = 0; for (int i = 0; i < numSamples; i++, x += step) { float y = rectBottom - stackedSampleSums[i]; var serie = cdata.series[index]; float value = serie.yValues[i]; if (value == -1f) { if (!passedFirstValidValue) { continue; } // once we started drawing the vertices, we have to keep going, otherwise the mesh will interpolate over frames with missing data, leading to misleading visuals. value = 0; } passedFirstValidValue = true; value *= serie.yScale; float val = (value - rangeStart) * rangeScale; if (y - val < r.yMin) val = y - r.yMin; // Clamp the values to be inside drawrect vertexBuffer[vertexBufferOffset++] = new Vector3(x, y - val, 0); // clip chart top vertexBuffer[vertexBufferOffset++] = new Vector3(x, y, 0); if (vertexBufferOffset >= vertexBufferSize) { unsafe { fixed (Vector3* p = vertexBuffer) GL.Vertices(p, null, null, vertexBufferOffset); } vertexBufferOffset -= vertexBufferSize; } stackedSampleSums[i] += val; } if (vertexBufferOffset > 0) { unsafe { fixed (Vector3* p = vertexBuffer) GL.Vertices(p, null, null, vertexBufferOffset); } } GL.End(); } private void DrawChartItemStackedOverlay(Rect r, int index, ChartViewData cdata, float[] stackedSampleSums) { int numSamples = cdata.GetDataDomainLength(); float step = r.width / numSamples; int orderIdx = cdata.order[index]; if (!cdata.series[orderIdx].enabled) return; Color color = cdata.series[orderIdx].color; GL.Begin(GL.TRIANGLE_STRIP); GL.Color(color); float x = r.x + step * 0.5f; float rangeScale = cdata.series[0].rangeAxis.sqrMagnitude == 0f ? 0f : 1f / (cdata.series[0].rangeAxis.y - cdata.series[0].rangeAxis.x) * r.height; float rangeStart = cdata.series[0].rangeAxis.x; float rectBottom = r.y + r.height; bool passedFirstValidValue = false; const int vertexBufferSize = 512; Span<Vector3> vertexBuffer = stackalloc Vector3[vertexBufferSize]; int vertexBufferOffset = 0; for (int i = 0; i < numSamples; i++, x += step) { float y = rectBottom - stackedSampleSums[i]; var overlay = cdata.overlays[orderIdx]; float value = overlay.yValues[i]; if (value == -1f) { if (!passedFirstValidValue) { continue; } // once we started drawing the vertices, we have to keep going, otherwise the mesh will interpolate over frames with missing data, leading to misleading visuals. value = 0; } passedFirstValidValue = true; value *= overlay.yScale; float val = (value - rangeStart) * rangeScale; vertexBuffer[vertexBufferOffset++] = new Vector3(x, y - val, 0); vertexBuffer[vertexBufferOffset++] = new Vector3(x, y, 0); if (vertexBufferOffset >= vertexBufferSize) { unsafe { fixed (Vector3* p = vertexBuffer) GL.Vertices(p, null, null, vertexBufferOffset); } vertexBufferOffset -= vertexBufferSize; } } if (vertexBufferOffset > 0) { unsafe { fixed (Vector3* p = vertexBuffer) GL.Vertices(p, null, null, vertexBufferOffset); } } GL.End(); } protected virtual Rect DoSeriesList(Rect position, int chartControlID, ProfilerModuleChartType chartType, ChartViewData cdata) { Rect elementPosition = position; Event evt = Event.current; EventType eventType = evt.GetTypeForControl(chartControlID); Vector2 mousePosition = evt.mousePosition; if (m_DragItemIndex != -1) { switch (eventType) { case EventType.MouseUp: if (GUIUtility.hotControl == chartControlID) { GUIUtility.hotControl = 0; m_DragItemIndex = -1; evt.Use(); } break; case EventType.KeyDown: if (evt.keyCode == KeyCode.Escape) { GUIUtility.hotControl = 0; System.Array.Copy(m_OldChartOrder, cdata.order, m_OldChartOrder.Length); m_DragItemIndex = -1; evt.Use(); } break; } } for (int i = cdata.numSeries - 1; i >= 0; --i) { int orderIdx = cdata.order[i]; var name = cdata.series[orderIdx].name; GUIContent elementLabel = EditorGUIUtility.TempContent(name); elementLabel.tooltip = name; elementPosition.height = Styles.seriesLabel.CalcHeight(elementLabel, elementPosition.width); Rect controlPosition = elementPosition; if (i == m_DragItemIndex) controlPosition.y = mousePosition.y - m_DragDownPos.y; if (chartType.IsStackedChartType()) { Rect dragHandlePosition = controlPosition; dragHandlePosition.xMin = dragHandlePosition.xMax - elementPosition.height; switch (eventType) { case EventType.Repaint: // Properly center the drag handle vertically Rect dragHandleRenderedPosition = dragHandlePosition; dragHandleRenderedPosition.height = Styles.seriesDragHandle.fixedHeight; dragHandleRenderedPosition.y += (dragHandlePosition.height - dragHandleRenderedPosition.height) / 2; Styles.seriesDragHandle.Draw(dragHandleRenderedPosition, false, false, false, false); break; case EventType.MouseDown: if (dragHandlePosition.Contains(mousePosition)) { m_DragItemIndex = i; m_DragDownPos = mousePosition; m_DragDownPos.x -= elementPosition.x; m_DragDownPos.y -= elementPosition.y; m_OldChartOrder = new int[cdata.numSeries]; System.Array.Copy(cdata.order, m_OldChartOrder, m_OldChartOrder.Length); GUIUtility.hotControl = chartControlID; evt.Use(); } break; case EventType.MouseDrag: if (i == m_DragItemIndex) { bool moveDn = mousePosition.y > elementPosition.yMax; bool moveUp = mousePosition.y < elementPosition.yMin; if (moveDn || moveUp) { int draggedItemOrder = cdata.order[i]; int targetIdx = moveUp ? Mathf.Min(cdata.numSeries - 1, i + 1) : Mathf.Max(0, i - 1); cdata.order[i] = cdata.order[targetIdx]; cdata.order[targetIdx] = draggedItemOrder; m_DragItemIndex = targetIdx; SaveChartsSettingsOrder(cdata); } evt.Use(); } break; case EventType.MouseUp: if (m_DragItemIndex == i) evt.Use(); m_DragItemIndex = -1; break; } } DoSeriesToggle(controlPosition, elementLabel, ref cdata.series[orderIdx].enabled, cdata.series[orderIdx].color, cdata); elementPosition.y += elementPosition.height + EditorGUIUtility.standardVerticalSpacing; } return elementPosition; } protected void DoSeriesToggle(Rect position, GUIContent label, ref bool enabled, Color color, ChartViewData cdata) { Color oldColor = GUI.backgroundColor; bool oldEnableState = enabled; GUI.backgroundColor = enabled ? color : Color.black; EditorGUI.BeginChangeCheck(); enabled = GUI.Toggle(position, enabled, label, Styles.seriesLabel); if (EditorGUI.EndChangeCheck()) SaveChartsSettingsEnabled(cdata); GUI.backgroundColor = oldColor; if (onDoSeriesToggle != null) { onDoSeriesToggle(oldEnableState != enabled); } } private void LoadChartsSettings(ChartViewData cdata) { if (string.IsNullOrEmpty(m_ChartSettingsName)) return; var str = EditorPrefs.GetString(orderPreferenceKey); if (!string.IsNullOrEmpty(str)) { try { var values = str.Split(','); if (values.Length == cdata.numSeries) { for (var i = 0; i < cdata.numSeries; i++) cdata.order[i] = int.Parse(values[i]); } } catch (FormatException) {} } str = EditorPrefs.GetString(visiblePreferenceKey); for (var i = 0; i < cdata.numSeries; i++) { if (i < str.Length && str[i] == '0') cdata.series[i].enabled = false; } } protected void SetChartSettingsNameAndUpdateAllPreferences(string name) { var orderPreference = EditorPrefs.GetString(orderPreferenceKey); var visiblePreference = EditorPrefs.GetString(visiblePreferenceKey); EditorPrefs.DeleteKey(orderPreferenceKey); EditorPrefs.DeleteKey(visiblePreferenceKey); m_ChartSettingsName = name; EditorPrefs.SetString(orderPreferenceKey, orderPreference); EditorPrefs.SetString(visiblePreferenceKey, visiblePreference); } void DeleteChartsSettings() { EditorPrefs.DeleteKey(orderPreferenceKey); EditorPrefs.DeleteKey(visiblePreferenceKey); } private void SaveChartsSettingsOrder(ChartViewData cdata) { if (string.IsNullOrEmpty(m_ChartSettingsName)) return; var str = string.Empty; for (var i = 0; i < cdata.numSeries; i++) { if (str.Length != 0) str += ","; str += cdata.order[i]; } EditorPrefs.SetString(orderPreferenceKey, str); } protected void SaveChartsSettingsEnabled(ChartViewData cdata) { var str = string.Empty; for (var i = 0; i < cdata.numSeries; i++) str += cdata.series[i].enabled ? '1' : '0'; EditorPrefs.SetString(visiblePreferenceKey, str); } } internal class ChartSeriesViewData { public string name { get; private set; } public string category { get; private set; } public Color color { get; private set; } public bool enabled; public float yScale { get; internal set; } public float[] yValues { get; private set; } public Vector2 rangeAxis { get; set; } public int numDataPoints { get; private set; } public readonly int firstXValue = 0; public readonly int lastXValue = 0; public ChartSeriesViewData(string name, string category, int numDataPoints, Color color) { this.name = name; this.category = category; this.color = color; this.numDataPoints = numDataPoints; yValues = new float[numDataPoints]; lastXValue = numDataPoints - 1; yScale = 1.0f; enabled = true; } // Used by legacy areas that don't use counters and therefore don't have a category. public ChartSeriesViewData(string name, int numDataPoints, Color color) : this(name, string.Empty, numDataPoints, color) {} } internal class ChartViewData { static readonly float[] k_ChartGridValues1ms = { 1000, 250, 100 }; static readonly string[] k_ChartGridLabels1ms = { "1ms (1000FPS)", "0.25ms (4000FPS)", "0.1ms (10000FPS)" }; static readonly float[] k_ChartGridValues8ms = { 8333, 4000, 1000 }; static readonly string[] k_ChartGridLabels8ms = { "8ms (120FPS)", "4ms (250FPS)", "1ms (1000FPS)" }; static readonly float[] k_ChartGridValues16ms = { 16667, 10000, 5000 }; static readonly string[] k_ChartGridLabels16ms = { "16ms (60FPS)", "10ms (100FPS)", "5ms (200FPS)" }; static readonly float[] k_ChartGridValues66ms = { 66667, 33333, 16667 }; static readonly string[] k_ChartGridLabels66ms = { "66ms (15FPS)", "33ms (30FPS)", "16ms (60FPS)" }; public ChartSeriesViewData[] series { get; private set; } public ChartSeriesViewData[] overlays { get; private set; } public int[] order { get; private set; } public float[] grid { get; private set; } public string[] gridLabels { get; private set; } public string[] selectedLabels { get; private set; } /// <summary> /// if dataAvailable has this bit set, there is data /// </summary> public const int dataAvailableBit = 1; /// <summary> /// 0 = No Data /// bit 1 set = Data available /// >1 = There's a additional info that may provide a reason for missing data /// </summary> public int[] dataAvailable { get; set; } public int firstSelectableFrame { get; private set; } public bool hasOverlay { get; set; } public float maxValue { get; set; } public int numSeries { get; private set; } public int chartDomainOffset { get; private set; } public void Assign(ChartSeriesViewData[] series, int firstFrame, int firstSelectableFrame) { this.series = series; this.chartDomainOffset = firstFrame; this.firstSelectableFrame = firstSelectableFrame; numSeries = series.Length; if (order == null || order.Length != numSeries) { order = new int[numSeries]; for (int i = 0, count = order.Length; i < count; ++i) order[i] = order.Length - 1 - i; } if (overlays == null || overlays.Length != numSeries) overlays = new ChartSeriesViewData[numSeries]; } public void ClearDataAvailableBuffer() { for (int i = 0; i < dataAvailable.Length; ++i) dataAvailable[i] = 0; } public void AssignSelectedLabels(string[] selectedLabels) { this.selectedLabels = selectedLabels; } public void SetGrid(float[] grid, string[] labels) { this.grid = grid; this.gridLabels = labels; } public Vector2 GetDataDomain() { // TODO: this currently assumes data points are in order and first series has at least one data point if (series == null || numSeries == 0 || series[0].numDataPoints == 0) return Vector2.zero; Vector2 result = Vector2.one * series[0].firstXValue; for (int i = 0; i < numSeries; ++i) { if (series[i].numDataPoints == 0) continue; result.x = Mathf.Min(result.x, series[i].firstXValue); result.y = Mathf.Max(result.y, series[i].lastXValue); } return result; } public int GetDataDomainLength() { var domain = GetDataDomain(); // the domain is a range of indices, logically starting at 0. The Length is therefore the (lastIndex - firstIndex + 1) return (int)(domain.y - domain.x) + 1; } public void UpdateChartGrid(float timeMax, bool showGrid) { if (!showGrid) { SetGrid(null, null); return; } if (timeMax < 1500) { SetGrid(k_ChartGridValues1ms, k_ChartGridLabels1ms); } else if (timeMax < 10000) { SetGrid(k_ChartGridValues8ms, k_ChartGridLabels8ms); } else if (timeMax < 30000) { SetGrid(k_ChartGridValues16ms, k_ChartGridLabels16ms); } else { SetGrid(k_ChartGridValues66ms, k_ChartGridLabels66ms); } } } }
UnityCsReference/Modules/ProfilerEditor/ProfilerWindow/Chart.cs/0
{ "file_path": "UnityCsReference/Modules/ProfilerEditor/ProfilerWindow/Chart.cs", "repo_id": "UnityCsReference", "token_count": 27824 }
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 System.Linq; using System.Text; using UnityEditor; using UnityEditor.IMGUI.Controls; using UnityEditor.Profiling; using UnityEngine.Profiling; using UnityEngine; namespace UnityEditorInternal.Profiling { [Serializable] internal class ProfilerDetailedObjectsView : ProfilerDetailedView { static readonly string kInstancesCountFormatText = L10n.Tr("{0} instances of {1} sample:"); static readonly string kInstancesCountTooltipText = L10n.Tr("Total count of samples which represent the selected item in the Hierarchy View."); static readonly string kMetadataText = LocalizationDatabase.GetLocalizedString("Metadata:"); static readonly string kCallstackText = LocalizationDatabase.GetLocalizedString("Call Stack:"); static readonly string kNoMetadataOrCallstackText = LocalizationDatabase.GetLocalizedString("No metadata or call stack is available for the selected sample."); [NonSerialized] bool m_Initialized; [NonSerialized] List<ulong> m_CachedCallstack = new List<ulong>(); [NonSerialized] GUIContent m_InstancesLabel; [SerializeField] TreeViewState m_TreeViewState; [SerializeField] MultiColumnHeaderState m_MultiColumnHeaderState; [SerializeField] SplitterState m_VertSplit; [SerializeField] ProfilerFrameDataMultiColumnHeader m_MultiColumnHeader; ObjectsTreeView m_TreeView; Vector2 m_CallstackScrollViewPos; public bool gpuView { get; set; } public delegate void FrameItemCallback(int id); public event FrameItemCallback frameItemEvent; class ObjectInformation { public int id; // FrameDataView item id public int sampleIndex; // Merged sample index public int instanceId; // 0 if from a different Editor/Player session than the current one public float[] columnValues; public string[] columnStrings; } class ObjectsTreeView : TreeView { ProfilerFrameDataMultiColumnHeader m_MultiColumnHeader; List<ObjectInformation> m_ObjectsData; static readonly IList<int> k_DefaultSelection = new int[] { 0 }; public event FrameItemCallback frameItemEvent; public ObjectsTreeView(TreeViewState treeViewState, ProfilerFrameDataMultiColumnHeader multicolumnHeader) : base(treeViewState, multicolumnHeader) { m_MultiColumnHeader = multicolumnHeader; showBorder = true; showAlternatingRowBackgrounds = true; multicolumnHeader.sortingChanged += OnSortingChanged; Reload(); } public int GetSelectedFrameDataViewId() { if (m_ObjectsData == null || state.selectedIDs.Count == 0) return -1; var selectedId = state.selectedIDs[0]; if (selectedId == -1 || selectedId >= m_ObjectsData.Count) return -1; return m_ObjectsData[selectedId].id; } public int GetSelectedFrameDataViewMergedSampleIndex() { if (m_ObjectsData == null || state.selectedIDs.Count == 0) return 0; var selectedId = state.selectedIDs[0]; if (selectedId == -1 || selectedId >= m_ObjectsData.Count) return 0; return m_ObjectsData[selectedId].sampleIndex; } public void SetData(List<ObjectInformation> objectsData) { // Reload by forcing soring of the new data m_ObjectsData = objectsData; OnSortingChanged(multiColumnHeader); // Ensure that we select the first item when we if (m_ObjectsData != null && !HasSelection()) SetSelection(k_DefaultSelection); } protected override TreeViewItem BuildRoot() { var root = new TreeViewItem { id = -1, depth = -1 }; var allItems = new List<TreeViewItem>(); if (m_ObjectsData != null && m_ObjectsData.Count != 0) { allItems.Capacity = m_ObjectsData.Count; for (var i = 0; i < m_ObjectsData.Count; i++) allItems.Add(new TreeViewItem { id = i, depth = 0 }); } else { allItems.Add(new TreeViewItem { id = 0, depth = 0, displayName = kNoneText }); } SetupParentsAndChildrenFromDepths(root, allItems); return root; } protected override void RowGUI(RowGUIArgs args) { if (Event.current.rawType != EventType.Repaint) return; if (m_ObjectsData == null || m_ObjectsData.Count == 0) { base.RowGUI(args); return; } var item = args.item; for (var i = 0; i < args.GetNumVisibleColumns(); ++i) CellGUI(args.GetCellRect(i), item, args.GetColumn(i), ref args); } void CellGUI(Rect cellRect, TreeViewItem item, int column, ref RowGUIArgs args) { var objData = m_ObjectsData[args.item.id]; CenterRectUsingSingleLineHeight(ref cellRect); DefaultGUI.Label(cellRect, objData.columnStrings[column], args.selected, args.focused); } void OnSortingChanged(MultiColumnHeader header) { if (header.sortedColumnIndex == -1) return; // No column to sort for (just use the order the data are in) if (m_ObjectsData != null) { var columns = m_MultiColumnHeader.columns; if (header.sortedColumnIndex >= columns.Length) return; var orderMultiplier = header.IsSortedAscending(header.sortedColumnIndex) ? 1 : -1; Comparison<ObjectInformation> comparison; switch (columns[header.sortedColumnIndex].profilerColumn) { case HierarchyFrameDataView.columnTotalTime: case HierarchyFrameDataView.columnTotalPercent: case HierarchyFrameDataView.columnTotalGpuTime: case HierarchyFrameDataView.columnTotalGpuPercent: case HierarchyFrameDataView.columnGcMemory: case HierarchyFrameDataView.columnDrawCalls: comparison = (objData1, objData2) => objData1.columnValues[header.sortedColumnIndex].CompareTo(objData2.columnValues[header.sortedColumnIndex]) * orderMultiplier; break; default: comparison = (objData1, objData2) => objData1.columnStrings[header.sortedColumnIndex].CompareTo(objData2.columnStrings[header.sortedColumnIndex]) * orderMultiplier; break; } m_ObjectsData.Sort(comparison); } Reload(); } protected override void SingleClickedItem(int id) { if (m_ObjectsData == null) return; var selectedInstanceId = m_ObjectsData[id].instanceId; // 0 is an invalid instance ID if (selectedInstanceId == 0) return; var obj = EditorUtility.InstanceIDToObject(selectedInstanceId); if (obj is Component) obj = ((Component)obj).gameObject; if (obj != null) EditorGUIUtility.PingObject(obj.GetInstanceID()); } protected override void DoubleClickedItem(int id) { if (m_ObjectsData == null) return; if (frameItemEvent != null) frameItemEvent.Invoke(m_ObjectsData[id].id); } protected override bool CanMultiSelect(TreeViewItem item) { return false; } } readonly string k_PrefKeyPrefix; string multiColumnHeaderStatePrefKey => k_PrefKeyPrefix + "MultiColumnHeaderState"; string splitter0StatePrefKey => k_PrefKeyPrefix + "Splitter.Relative[0]"; string splitter1StatePrefKey => k_PrefKeyPrefix + "Splitter.Relative[1]"; public ProfilerDetailedObjectsView(string prefKeyPrefix) { k_PrefKeyPrefix = prefKeyPrefix; } void InitIfNeeded() { if (m_Initialized) return; if (m_CachedCallstack == null) m_CachedCallstack = new List<ulong>(); if (m_InstancesLabel == null) m_InstancesLabel = new GUIContent(); var cpuDetailColumns = new[] { HierarchyFrameDataView.columnObjectName, HierarchyFrameDataView.columnTotalPercent, HierarchyFrameDataView.columnGcMemory, HierarchyFrameDataView.columnTotalTime }; var gpuDetailColumns = new[] { HierarchyFrameDataView.columnObjectName, HierarchyFrameDataView.columnTotalGpuPercent, HierarchyFrameDataView.columnDrawCalls, HierarchyFrameDataView.columnTotalGpuTime }; var profilerColumns = gpuView ? gpuDetailColumns : cpuDetailColumns; var defaultSortColumn = gpuView ? HierarchyFrameDataView.columnTotalGpuTime : HierarchyFrameDataView.columnTotalTime; var columns = ProfilerFrameDataHierarchyView.CreateColumns(profilerColumns); var headerState = ProfilerFrameDataHierarchyView.CreateDefaultMultiColumnHeaderState(columns, defaultSortColumn); headerState.columns[0].minWidth = 60; headerState.columns[0].autoResize = true; headerState.columns[0].allowToggleVisibility = false; var multiColumnHeaderStateData = SessionState.GetString(multiColumnHeaderStatePrefKey, ""); if (!string.IsNullOrEmpty(multiColumnHeaderStateData)) { try { var restoredHeaderState = JsonUtility.FromJson<MultiColumnHeaderState>(multiColumnHeaderStateData); if (restoredHeaderState != null) m_MultiColumnHeaderState = restoredHeaderState; } catch{} // Nevermind, we'll just fall back to the default } if (MultiColumnHeaderState.CanOverwriteSerializedFields(m_MultiColumnHeaderState, headerState)) MultiColumnHeaderState.OverwriteSerializedFields(m_MultiColumnHeaderState, headerState); var firstInit = m_MultiColumnHeaderState == null; m_MultiColumnHeaderState = headerState; m_MultiColumnHeader = new ProfilerFrameDataMultiColumnHeader(m_MultiColumnHeaderState, columns) { height = 25 }; if (firstInit) m_MultiColumnHeader.ResizeToFit(); m_MultiColumnHeader.visibleColumnsChanged += OnMultiColumnHeaderChanged; m_MultiColumnHeader.sortingChanged += OnMultiColumnHeaderChanged; if (m_TreeViewState == null) m_TreeViewState = new TreeViewState(); m_TreeView = new ObjectsTreeView(m_TreeViewState, m_MultiColumnHeader); m_TreeView.frameItemEvent += frameItemEvent; if (m_VertSplit == null || !m_VertSplit.IsValid()) m_VertSplit = SplitterState.FromRelative(new[] { SessionState.GetFloat(splitter0StatePrefKey, 60f), SessionState.GetFloat(splitter1StatePrefKey, 40f) }, new[] { 50f, 50f }, null); m_Initialized = true; } void OnMultiColumnHeaderChanged(MultiColumnHeader header) { SessionState.SetString(multiColumnHeaderStatePrefKey, JsonUtility.ToJson(header.state)); } public void DoGUI(GUIStyle headerStyle, HierarchyFrameDataView frameDataView, IList<int> selection) { if (frameDataView == null || !frameDataView.valid || selection.Count == 0) { DrawEmptyPane(headerStyle); return; } InitIfNeeded(); UpdateIfNeeded(frameDataView, selection[0]); var selectedSampleId = m_TreeView.GetSelectedFrameDataViewId(); var selectedMergedSampleIndex = m_TreeView.GetSelectedFrameDataViewMergedSampleIndex(); var selectedSampleMetadataCount = 0; if (selectedSampleId != -1) { frameDataView.GetItemMergedSampleCallstack(selectedSampleId, selectedMergedSampleIndex, m_CachedCallstack); selectedSampleMetadataCount = frameDataView.GetItemMergedSamplesMetadataCount(selectedSampleId, selectedMergedSampleIndex); } GUILayout.Label(m_InstancesLabel, EditorStyles.label); var showCallstack = m_CachedCallstack.Count > 0; var showMetadata = selectedSampleMetadataCount != 0; SplitterGUILayout.BeginVerticalSplit(m_VertSplit, Styles.expandedArea); // Detailed list var rect = EditorGUILayout.BeginVertical(Styles.expandedArea); m_TreeView.OnGUI(rect); EditorGUILayout.EndVertical(); // Metadata area EditorGUILayout.BeginVertical(Styles.expandedArea); if (showCallstack) { EditorGUILayout.BeginHorizontal(EditorStyles.toolbar); ProfilerFrameDataViewBase.showFullDetailsForCallStacks = GUILayout.Toggle(ProfilerFrameDataViewBase.showFullDetailsForCallStacks, ProfilerFrameDataViewBase.showFullDetailsForCallStacksContent, EditorStyles.toolbarButton); EditorGUILayout.EndHorizontal(); } // Display active text (We want word wrapped text with a vertical scrollbar) m_CallstackScrollViewPos = EditorGUILayout.BeginScrollView(m_CallstackScrollViewPos, Styles.callstackScroll); var sb = new StringBuilder(); if (showMetadata || showCallstack) { if (showMetadata) { var metadataInfo = frameDataView.GetMarkerMetadataInfo(frameDataView.GetItemMarkerID(selectedSampleId)); sb.Append(kMetadataText); sb.Append('\n'); for (var i = 0; i < selectedSampleMetadataCount; ++i) { if (metadataInfo != null && i < metadataInfo.Length) sb.Append(metadataInfo[i].name); else sb.Append(i); sb.Append(": "); sb.Append(frameDataView.GetItemMergedSamplesMetadata(selectedSampleId, selectedMergedSampleIndex, i)); sb.Append('\n'); } sb.Append('\n'); } if (showCallstack) { m_ProfilerFrameDataHierarchyView.CompileCallStack(sb, m_CachedCallstack, frameDataView); } } else { sb.Append(kNoMetadataOrCallstackText); } var metadataText = sb.ToString(); Styles.callstackTextArea.CalcMinMaxWidth(GUIContent.Temp(metadataText), out _, out var maxWidth); float minHeight = Styles.callstackTextArea.CalcHeight(GUIContent.Temp(metadataText), maxWidth); EditorGUILayout.SelectableLabel(metadataText, Styles.callstackTextArea, GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(true), GUILayout.MinWidth(maxWidth + 10), GUILayout.MinHeight(minHeight + 10)); EditorGUILayout.EndScrollView(); EditorGUILayout.EndVertical(); SplitterGUILayout.EndVerticalSplit(); } void UpdateIfNeeded(HierarchyFrameDataView frameDataView, int selectedId) { var needReload = m_SelectedID != selectedId || !Equals(m_FrameDataView, frameDataView); if (!needReload) return; m_FrameDataView = frameDataView; m_SelectedID = selectedId; m_TreeView.SetSelection(new List<int>()); var samplesCount = m_FrameDataView.GetItemMergedSamplesCount(selectedId); // Collect all the data var instanceIDs = new List<int>(samplesCount); m_FrameDataView.GetItemMergedSamplesInstanceID(selectedId, instanceIDs); var columns = m_MultiColumnHeader.columns; var columnsCount = columns.Length; var objectsDatas = new List<string>[columnsCount]; var objectsValueDatas = new List<float>[columnsCount]; for (var i = 0; i < columnsCount; i++) { objectsDatas[i] = new List<string>(samplesCount); m_FrameDataView.GetItemMergedSamplesColumnData(selectedId, columns[i].profilerColumn, objectsDatas[i]); objectsValueDatas[i] = new List<float>(samplesCount); m_FrameDataView.GetItemMergedSamplesColumnDataAsFloats(selectedId, columns[i].profilerColumn, objectsValueDatas[i]); } bool dataIsFromCurrentEditorSession = ProfilerDriver.FrameDataBelongsToCurrentEditorSession(m_FrameDataView); // Store it per sample var objectsData = new List<ObjectInformation>(); for (var i = 0; i < samplesCount; i++) { var objData = new ObjectInformation() { columnStrings = new string[columnsCount], columnValues = new float[columnsCount] }; objData.id = selectedId; objData.sampleIndex = i; // Do not set the instance ID if this data is not coming from this session. // This field is only used for pinging the related object and instanceId does not carry over between editor sessions. objData.instanceId = (dataIsFromCurrentEditorSession && i < instanceIDs.Count) ? instanceIDs[i] : 0; for (var j = 0; j < columnsCount; j++) { objData.columnStrings[j] = (i < objectsDatas[j].Count) ? objectsDatas[j][i] : string.Empty; objData.columnValues[j] = (i < objectsValueDatas[j].Count) ? objectsValueDatas[j][i] : 0.0f; } objectsData.Add(objData); } m_TreeView.SetData(objectsData); // Update instances label var sampleName = m_FrameDataView.GetItemName(selectedId); m_InstancesLabel.text = UnityString.Format(kInstancesCountFormatText, samplesCount, sampleName); m_InstancesLabel.tooltip = kInstancesCountTooltipText; } public void Clear() { if (m_TreeView != null) { if (m_TreeView.multiColumnHeader != null) { m_TreeView.multiColumnHeader.visibleColumnsChanged -= OnMultiColumnHeaderChanged; m_TreeView.multiColumnHeader.sortingChanged -= OnMultiColumnHeaderChanged; } m_TreeView.SetData(null); } } override public void SaveViewSettings() { if (m_VertSplit != null && m_VertSplit.relativeSizes != null && m_VertSplit.relativeSizes.Length >= 2) { SessionState.SetFloat(splitter0StatePrefKey, m_VertSplit.relativeSizes[0]); SessionState.SetFloat(splitter1StatePrefKey, m_VertSplit.relativeSizes[1]); } } public override void OnEnable(CPUOrGPUProfilerModule cpuOrGpuProfilerModule, ProfilerFrameDataHierarchyView profilerFrameDataHierarchyView) { base.OnEnable(cpuOrGpuProfilerModule, profilerFrameDataHierarchyView); } override public void OnDisable() { SaveViewSettings(); } } }
UnityCsReference/Modules/ProfilerEditor/ProfilerWindow/ProfilerDetailedObjectsView.cs/0
{ "file_path": "UnityCsReference/Modules/ProfilerEditor/ProfilerWindow/ProfilerDetailedObjectsView.cs", "repo_id": "UnityCsReference", "token_count": 9763 }
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 Unity.Profiling.Editor; using UnityEditorInternal.Profiling; using UnityEngine; namespace UnityEditor.Profiling { [Serializable] internal class DynamicProfilerModule : ProfilerModuleBase { public const string iconPath = "Profiler.Custom"; Action m_LegacyInitialization; public void Initialize(InitializationArgs args, List<ProfilerCounterData> chartCounters, List<ProfilerCounterData> detailCounters) { m_LegacyInitialization = () => { SetCounters(chartCounters, detailCounters); }; Initialize(args); } internal override void LegacyModuleInitialize() { base.LegacyModuleInitialize(); m_LegacyInitialization.Invoke(); m_LegacyInitialization = null; } public override void DrawToolbar(Rect position) { DrawEmptyToolbar(); } public override void DrawDetailsView(Rect position) { DrawDetailsViewText(position); } public SerializedData ToSerializedData() { return new SerializedData() { m_Name = DisplayName, m_ChartCounters = m_LegacyChartCounters, m_DetailCounters = m_LegacyDetailCounters, }; } [Serializable] public struct SerializedData { public string m_Name; public List<ProfilerCounterData> m_ChartCounters; public List<ProfilerCounterData> m_DetailCounters; } [Serializable] public class SerializedDataCollection { public List<SerializedData> m_Modules = new List<SerializedData>(); public int Length => m_Modules.Count; public SerializedData this[int index] { get => m_Modules[index]; } public void Add(SerializedData module) { m_Modules.Add(module); } public static SerializedDataCollection FromDynamicProfilerModulesInCollection(List<ProfilerModule> modules) { var serializableCollection = new SerializedDataCollection(); foreach (var module in modules) { if (module is DynamicProfilerModule dynamicModule) { serializableCollection.Add(dynamicModule.ToSerializedData()); } } return serializableCollection; } } } }
UnityCsReference/Modules/ProfilerEditor/ProfilerWindow/ProfilerModules/DynamicProfilerModule.cs/0
{ "file_path": "UnityCsReference/Modules/ProfilerEditor/ProfilerWindow/ProfilerModules/DynamicProfilerModule.cs", "repo_id": "UnityCsReference", "token_count": 1318 }
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.Collections.Generic; using UnityEngine; using UnityEditorInternal; namespace UnityEditor { internal class MemoryTreeList { internal class Styles { public GUIStyle background = "OL Box"; public GUIStyle header = "OL title"; public GUIStyle entryEven = "OL EntryBackEven"; public GUIStyle entryOdd = "OL EntryBackOdd"; public GUIStyle numberLabel = "OL Label"; public GUIStyle foldout = "IN foldout"; } private static Styles m_Styles; protected static Styles styles { get { return m_Styles ?? (m_Styles = new Styles()); } } private bool m_RequiresRefresh; public bool RequiresRefresh { get { return m_RequiresRefresh; } set { m_RequiresRefresh = value; } } const float kIndentPx = 16; const float kBaseIndent = 4; protected const float kSmallMargin = 4; protected const float kRowHeight = 16; protected const float kNameColumnSize = 300; protected const float kColumnSize = 70; protected const float kFoldoutSize = 14; public MemoryElementSelection m_MemorySelection; protected MemoryElement m_Root = null; protected IProfilerWindowController m_ProfilerWindow; protected SplitterState m_Splitter; protected MemoryTreeList m_DetailView; protected int m_ControlID; protected Vector2 m_ScrollPosition; protected float m_SelectionOffset; protected float m_VisibleHeight; public MemoryTreeList(IProfilerWindowController profilerWindow, MemoryTreeList detailview) { m_MemorySelection = new MemoryElementSelection(); m_ProfilerWindow = profilerWindow; m_DetailView = detailview; m_ControlID = GUIUtility.GetPermanentControlID(); SetupSplitter(); } protected virtual void SetupSplitter() { float[] splitterRelativeSizes = new float[1]; float[] splitterMinWidths = new float[1]; splitterRelativeSizes[0] = kNameColumnSize; splitterMinWidths[0] = 100; m_Splitter = SplitterState.FromRelative(splitterRelativeSizes, splitterMinWidths, null); } public void OnGUI() { GUILayout.BeginVertical(); SplitterGUILayout.BeginHorizontalSplit(m_Splitter, EditorStyles.toolbar); DrawHeader(); SplitterGUILayout.EndHorizontalSplit(); if (m_Root == null) { GUILayout.EndVertical(); return; } HandleKeyboard(); m_ScrollPosition = GUILayout.BeginScrollView(m_ScrollPosition, styles.background); int row = 0; foreach (MemoryElement memoryElement in m_Root.children) { DrawItem(memoryElement, ref row, 1); row++; } GUILayoutUtility.GetRect(0f, row * kRowHeight, GUILayout.ExpandWidth(true)); if (Event.current.type == EventType.Repaint) m_VisibleHeight = GUIClip.visibleRect.height; GUILayout.EndScrollView(); GUILayout.EndVertical(); } private static float Clamp(float value, float min, float max) { return (value < min) ? min : (value > max) ? max : value; } private bool FindNamedChild(string name, List<MemoryElement> list, out MemoryElement outChild) { foreach (var child in list) { if (child.name == name) { outChild = child; return true; } } outChild = null; return false; } private void RestoreViewState(MemoryElement oldRoot, MemoryElement newRoot) { foreach (MemoryElement memoryElement in newRoot.children) { memoryElement.ExpandChildren(); if (memoryElement.ChildCount() == 0) continue; MemoryElement child = null; if (FindNamedChild(memoryElement.name, oldRoot.children, out child)) { memoryElement.expanded = child.expanded; if (memoryElement.expanded) { RestoreViewState(child, memoryElement); } } } } public void SetRoot(MemoryElement root) { MemoryElement oldRoot = m_Root; m_Root = root; if (m_Root != null) m_Root.ExpandChildren(); if (m_DetailView != null) m_DetailView.SetRoot(null); // Attempt to restore the old state of things by walking the old tree if (oldRoot != null && m_Root != null) RestoreViewState(oldRoot, m_Root); } public MemoryElement GetRoot() { return m_Root; } protected static void DrawBackground(int row, bool selected) { var currentRect = GenerateRect(row); var background = (row % 2 == 0 ? styles.entryEven : styles.entryOdd); if (Event.current.type == EventType.Repaint) background.Draw(currentRect, GUIContent.none, false, false, selected, false); } protected virtual void DrawHeader() { GUILayout.Label("Referenced By:", styles.header); } protected static Rect GenerateRect(int row) { var rect = new Rect(1, kRowHeight * row, GUIClip.visibleRect.width, kRowHeight); return rect; } protected virtual void DrawData(Rect rect, MemoryElement memoryElement, int indent, int row, bool selected) { if (Event.current.type != EventType.Repaint) return; string displayName = memoryElement.name + "(" + memoryElement.memoryInfo.className + ")"; styles.numberLabel.Draw(rect, displayName, false, false, false, selected); } protected void DrawRecursiveData(MemoryElement element, ref int row, int indent) { if (element.ChildCount() == 0) return; element.ExpandChildren(); foreach (MemoryElement elem in element.children) { row++; DrawItem(elem, ref row, indent); } } protected virtual void DrawItem(MemoryElement memoryElement, ref int row, int indent) { bool isSelected = m_MemorySelection.isSelected(memoryElement); DrawBackground(row, isSelected); Rect rect = GenerateRect(row); rect.x = kBaseIndent + indent * kIndentPx - kFoldoutSize; Rect toggleRect = rect; toggleRect.width = kFoldoutSize; if (memoryElement.ChildCount() > 0) memoryElement.expanded = GUI.Toggle(toggleRect, memoryElement.expanded, GUIContent.none, styles.foldout); rect.x += kFoldoutSize; if (isSelected) m_SelectionOffset = row * kRowHeight; if (Event.current.type == EventType.MouseDown && rect.Contains(Event.current.mousePosition)) { RowClicked(Event.current, memoryElement); } DrawData(rect, memoryElement, indent, row, isSelected); if (memoryElement.expanded) DrawRecursiveData(memoryElement, ref row, indent + 1); } protected void RowClicked(Event evt, MemoryElement memoryElement) { m_MemorySelection.SetSelection(memoryElement); GUIUtility.keyboardControl = m_ControlID; if (evt.clickCount == 2 && memoryElement.memoryInfo != null && memoryElement.memoryInfo.instanceId != 0) { Selection.activeInstanceID = memoryElement.memoryInfo.instanceId; } evt.Use(); if (memoryElement.memoryInfo != null) { EditorGUIUtility.PingObject(memoryElement.memoryInfo.instanceId); } if (m_DetailView != null) m_DetailView.SetRoot(memoryElement.memoryInfo == null ? null : new MemoryElement(memoryElement.memoryInfo, false)); m_ProfilerWindow.Repaint(); } protected void HandleKeyboard() { Event evt = Event.current; if (evt.GetTypeForControl(m_ControlID) != EventType.KeyDown || m_ControlID != GUIUtility.keyboardControl) return; if (m_MemorySelection.Selected == null) return; int count; switch (evt.keyCode) { case KeyCode.UpArrow: m_MemorySelection.MoveUp(); break; case KeyCode.DownArrow: m_MemorySelection.MoveDown(); break; case KeyCode.Home: m_MemorySelection.MoveFirst(); break; case KeyCode.End: m_MemorySelection.MoveLast(); break; case KeyCode.LeftArrow: if (m_MemorySelection.Selected.expanded) m_MemorySelection.Selected.expanded = false; else m_MemorySelection.MoveParent(); break; case KeyCode.RightArrow: if (m_MemorySelection.Selected.ChildCount() > 0) m_MemorySelection.Selected.expanded = true; break; case KeyCode.PageUp: count = Mathf.RoundToInt(m_VisibleHeight / kRowHeight); for (int i = 0; i < count; i++) m_MemorySelection.MoveUp(); break; case KeyCode.PageDown: count = Mathf.RoundToInt(m_VisibleHeight / kRowHeight); for (int i = 0; i < count; i++) m_MemorySelection.MoveDown(); break; case KeyCode.Return: if (m_MemorySelection.Selected.memoryInfo != null) { Selection.activeInstanceID = m_MemorySelection.Selected.memoryInfo.instanceId; } break; default: return; } RowClicked(evt, m_MemorySelection.Selected); EnsureVisible(); m_ProfilerWindow.Repaint(); } private void RecursiveFindSelected(MemoryElement element, ref int row) { if (m_MemorySelection.isSelected(element)) m_SelectionOffset = row * kRowHeight; row++; if (!element.expanded || element.ChildCount() == 0) return; element.ExpandChildren(); foreach (MemoryElement elem in element.children) RecursiveFindSelected(elem, ref row); } protected void EnsureVisible() { int row = 0; RecursiveFindSelected(m_Root, ref row); m_ScrollPosition.y = Clamp(m_ScrollPosition.y, m_SelectionOffset - m_VisibleHeight, m_SelectionOffset - kRowHeight); } } class MemoryTreeListClickable : MemoryTreeList { public MemoryTreeListClickable(IProfilerWindowController profilerWindow, MemoryTreeList detailview) : base(profilerWindow, detailview) { } protected override void SetupSplitter() { float[] splitterRelativeSizes = new float[3]; float[] splitterMinWidths = new float[3]; splitterRelativeSizes[0] = kNameColumnSize; splitterMinWidths[0] = 100; splitterRelativeSizes[1] = kColumnSize; splitterMinWidths[1] = 50; splitterRelativeSizes[2] = kColumnSize; splitterMinWidths[2] = 50; m_Splitter = SplitterState.FromRelative(splitterRelativeSizes, splitterMinWidths, null); } protected override void DrawHeader() { GUILayout.Label("Name", styles.header); GUILayout.Label("Memory", styles.header); GUILayout.Label("Ref count", styles.header); } protected override void DrawData(Rect rect, MemoryElement memoryElement, int indent, int row, bool selected) { if (Event.current.type != EventType.Repaint) return; string displayName = memoryElement.name; if (memoryElement.ChildCount() > 0 && indent < 3) displayName += " (" + memoryElement.AccumulatedChildCount() + ")"; int currentColumn = 0; rect.xMax = m_Splitter.realSizes[currentColumn]; styles.numberLabel.Draw(rect, displayName, false, false, false, selected); rect.x = rect.xMax; rect.width = m_Splitter.realSizes[++currentColumn] - kSmallMargin; styles.numberLabel.Draw(rect, EditorUtility.FormatBytes(memoryElement.totalMemory), false, false, false, selected); rect.x += m_Splitter.realSizes[currentColumn++]; rect.width = m_Splitter.realSizes[currentColumn] - kSmallMargin; if (memoryElement.ReferenceCount() > 0) styles.numberLabel.Draw(rect, memoryElement.ReferenceCount().ToString(), false, false, false, selected); else if (selected) styles.numberLabel.Draw(rect, "", false, false, false, selected); } } }
UnityCsReference/Modules/ProfilerEditor/ProfilerWindow/ProfilerModules/Memory/MemoryTreeList.cs/0
{ "file_path": "UnityCsReference/Modules/ProfilerEditor/ProfilerWindow/ProfilerModules/Memory/MemoryTreeList.cs", "repo_id": "UnityCsReference", "token_count": 6860 }
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; using Unity.Profiling.Editor; using UnityEditor; using UnityEngine; using UnityEngine.Profiling; namespace UnityEditorInternal.Profiling { [Serializable] [ProfilerModuleMetadata("UI", typeof(LocalizationResource), IconPath = "Profiler.UI")] internal class UIProfilerModule : ProfilerModuleBase { const int k_DefaultOrderIndex = 10; static readonly string k_UIProfilerAvailableOnlyInEditorMode = LocalizationDatabase.GetLocalizedString("Data is only available when profiling Play Mode in the Editor."); protected static WeakReference instance; [SerializeField] UISystemProfiler m_UISystemProfiler; public UIProfilerModule() : base(ProfilerModuleChartType.StackedTimeArea) {} // Used by UIDetailsProfilerModule protected UIProfilerModule(ProfilerModuleChartType defaultChartType) : base(defaultChartType) {} static UISystemProfiler sharedUISystemProfiler { get { return instance.IsAlive ? (instance.Target as UIProfilerModule)?.m_UISystemProfiler : null; } } internal override ProfilerArea area => ProfilerArea.UI; public override bool usesCounters => false; private protected override int defaultOrderIndex => k_DefaultOrderIndex; private protected override string legacyPreferenceKey => "ProfilerChartUI"; internal override void OnEnable() { if (this.GetType() == typeof(UIProfilerModule)) { instance = new WeakReference(this); } base.OnEnable(); if (m_UISystemProfiler == null) m_UISystemProfiler = new UISystemProfiler(); } internal override void OnDisable() { base.OnDisable(); if (m_UISystemProfiler != null) { m_UISystemProfiler.CurrentAreaChanged(null); m_UISystemProfiler.Dispose(); } } public override void DrawToolbar(Rect position) { // This module still needs to be broken apart into Toolbar and View. // case-1251139: We draw an empty toolbar when the profiler is not connected to an editor. // This is primary to match the other profiler's UI message display. if (!ProfilerWindow.ConnectedToEditor) DrawEmptyToolbar(); } public override void DrawDetailsView(Rect position) { if (ProfilerWindow.ConnectedToEditor) sharedUISystemProfiler?.DrawUIPane(ProfilerWindow); else GUILayout.Label(k_UIProfilerAvailableOnlyInEditorMode); } } }
UnityCsReference/Modules/ProfilerEditor/ProfilerWindow/ProfilerModules/uGui/UIProfilerModule.cs/0
{ "file_path": "UnityCsReference/Modules/ProfilerEditor/ProfilerWindow/ProfilerModules/uGui/UIProfilerModule.cs", "repo_id": "UnityCsReference", "token_count": 1205 }
431
// 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 System.Text; using Unity.Profiling.LowLevel; using UnityEngine.Bindings; namespace UnityEditor.Profiling { [NativeHeader("Modules/ProfilerEditor/ProfilerHistory/HierarchyFrameDataView.h")] [StructLayout(LayoutKind.Sequential)] public class HierarchyFrameDataView : FrameDataView { public const int invalidSampleId = -1; [Flags] public enum ViewModes { Default = 0, MergeSamplesWithTheSameName = 1 << 0, HideEditorOnlySamples = 1 << 1, InvertHierarchy = 1 << 2 } public const int columnDontSort = -1; public const int columnName = 0; public const int columnTotalPercent = 1; public const int columnSelfPercent = 2; public const int columnCalls = 3; public const int columnGcMemory = 4; public const int columnTotalTime = 5; public const int columnSelfTime = 6; internal const int columnDrawCalls = 7; internal const int columnTotalGpuTime = 8; internal const int columnSelfGpuTime = 9; internal const int columnTotalGpuPercent = 10; internal const int columnSelfGpuPercent = 11; public const int columnWarningCount = 12; public const int columnObjectName = 13; public const int columnStartTime = 14; internal HierarchyFrameDataView(int frameIndex, int threadIndex, ViewModes viewMode, int sortColumn, bool sortAscending) { m_Ptr = Internal_Create(frameIndex, threadIndex, viewMode, sortColumn, sortAscending); } [ThreadSafe] static extern IntPtr Internal_Create(int frameIndex, int threadIndex, ViewModes viewMode, int sortColumn, bool sortAscending); public extern ViewModes viewMode { [ThreadSafe] get; } public extern int sortColumn { [ThreadSafe] get; } public extern bool sortColumnAscending { [ThreadSafe] get; } [ThreadSafe] public extern int GetRootItemID(); [ThreadSafe] public extern int GetItemMarkerID(int id); [ThreadSafe] public extern MarkerFlags GetItemMarkerFlags(int id); [ThreadSafe] public extern ushort GetItemCategoryIndex(int id); [ThreadSafe] public extern int GetItemDepth(int id); public extern bool HasItemChildren(int id); internal extern int GetItemChildrenCount(int id); public extern void GetItemChildren(int id, [NotNull] List<int> outChildren); public extern void GetItemAncestors(int id, [NotNull] List<int> outAncestors); public extern void GetItemDescendantsThatHaveChildren(int id, [NotNull] List<int> outChildren); [ThreadSafe] public extern string GetItemName(int id); [ThreadSafe] public extern int GetItemInstanceID(int id); [ThreadSafe] public extern string GetItemColumnData(int id, int column); public float GetItemColumnDataAsSingle(int id, int column) { return GetItemColumnDataAsFloat(id, column); } [ThreadSafe] public extern float GetItemColumnDataAsFloat(int id, int column); [ThreadSafe] public extern double GetItemColumnDataAsDouble(int id, int column); public int GetItemMetadataCount(int id) { return GetItemMergedSamplesMetadataCount(id, 0); } public string GetItemMetadata(int id, int index) { return GetItemMergedSamplesMetadata(id, 0, index); } public float GetItemMetadataAsFloat(int id, int index) { return GetItemMergedSamplesMetadataAsFloat(id, 0, index); } public long GetItemMetadataAsLong(int id, int index) { return GetItemMergedSamplesMetadataAsLong(id, 0, index); } [NativeMethod(IsThreadSafe = true, ThrowsException = true)] public extern int GetItemMergedSamplesMetadataCount(int id, int sampleIndex); [NativeMethod(IsThreadSafe = true, ThrowsException = true)] public extern string GetItemMergedSamplesMetadata(int id, int sampleIndex, int metadataIndex); [NativeMethod(IsThreadSafe = true, ThrowsException = true)] public extern float GetItemMergedSamplesMetadataAsFloat(int id, int sampleIndex, int metadataIndex); [NativeMethod(IsThreadSafe = true, ThrowsException = true)] public extern long GetItemMergedSamplesMetadataAsLong(int id, int sampleIndex, int metadataIndex); [ThreadSafe] internal extern string GetItemTooltip(int id, int column); public string ResolveItemCallstack(int id) { return ResolveItemMergedSampleCallstack(id, 0); } public void GetItemCallstack(int id, List<ulong> outCallstack) { GetItemMergedSampleCallstack(id, 0, outCallstack); } [ThreadSafe] public extern int GetItemMergedSamplesCount(int id); [NativeMethod(IsThreadSafe = true, ThrowsException = true)] public extern void GetItemRawFrameDataViewIndices(int id, [NotNull] List<int> outSampleIndices); [NativeMethod(IsThreadSafe = true, ThrowsException = true)] public extern bool ItemContainsRawFrameDataViewIndex(int id, int sampleIndex); public void GetItemMergedSamplesColumnData(int id, int column, List<string> outStrings) { if (outStrings == null) throw new ArgumentNullException(nameof(outStrings)); GetItemMergedSamplesColumnDataInternal(id, column, outStrings); } [NativeMethod("GetItemMergedSamplesColumnData")] [ThreadSafe] extern void GetItemMergedSamplesColumnDataInternal(int id, int column, List<string> outStrings); public void GetItemMergedSamplesColumnDataAsFloats(int id, int column, List<float> outValues) { if (outValues == null) throw new ArgumentNullException(nameof(outValues)); GetItemMergedSamplesColumnDataAsFloatsInternal(id, column, outValues); } [NativeMethod("GetItemMergedSamplesColumnDataAsFloats")] [ThreadSafe] extern void GetItemMergedSamplesColumnDataAsFloatsInternal(int id, int column, List<float> outValues); public void GetItemMergedSamplesColumnDataAsDoubles(int id, int column, List<double> outValues) { if (outValues == null) throw new ArgumentNullException(nameof(outValues)); GetItemMergedSamplesColumnDataAsDoublesInternal(id, column, outValues); } [NativeMethod("GetItemMergedSamplesColumnDataAsDoubles")] [ThreadSafe] extern void GetItemMergedSamplesColumnDataAsDoublesInternal(int id, int column, List<double> outValues); public void GetItemMergedSamplesInstanceID(int id, List<int> outInstanceIds) { if (outInstanceIds == null) throw new ArgumentNullException(nameof(outInstanceIds)); GetItemMergedSamplesInstanceIDInternal(id, outInstanceIds); } [NativeMethod("GetItemMergedSamplesInstanceID")] [ThreadSafe] extern void GetItemMergedSamplesInstanceIDInternal(int id, List<int> outInstanceIds); public void GetItemMergedSampleCallstack(int id, int sampleIndex, List<ulong> outCallstack) { if (outCallstack == null) throw new ArgumentNullException(nameof(outCallstack)); GetItemMergedSampleCallstackInternal(id, sampleIndex, outCallstack); } [NativeMethod("GetItemMergedSampleCallstack")] [ThreadSafe] extern void GetItemMergedSampleCallstackInternal(int id, int sampleIndex, List<ulong> outCallstack); public extern string ResolveItemMergedSampleCallstack(int id, int sampleIndex); public void GetItemMarkerIDPath(int id, List<int> outFullIdPath) { if (outFullIdPath == null) throw new ArgumentNullException("outFullIdPath"); if (viewMode.HasFlag(ViewModes.InvertHierarchy)) { // Inverted hierarchy should also report Marker ID path from the top-down perspective. // Since callers are represented by children items we do depth first scan to get the first valid markerid path. outFullIdPath.Clear(); List<int> children = null; var childId = id; while (HasItemChildren(childId)) { if (children == null) children = new List<int>(); GetItemChildren(childId, children); childId = children[0]; outFullIdPath.Add(childId); } } else { GetItemAncestors(id, outFullIdPath); } outFullIdPath.Reverse(); for (int i = 0; i < outFullIdPath.Count; ++i) outFullIdPath[i] = GetItemMarkerID(outFullIdPath[i]); outFullIdPath.Add(GetItemMarkerID(id)); } public string GetItemPath(int id) { var ancestors = new List<int>(); if (viewMode.HasFlag(ViewModes.InvertHierarchy)) { // Inverted hierarchy should also report Marker ID path from the top-down perspective. // Since callers are represented by children items we do depth first scan to get the first valid markerid path. List<int> children = null; var childId = id; while (HasItemChildren(childId)) { if (children == null) children = new List<int>(); GetItemChildren(childId, children); childId = children[0]; ancestors.Add(childId); } } else { GetItemAncestors(id, ancestors); } var propertyPathBuilder = new StringBuilder(); for (int i = ancestors.Count - 1; i >= 0; i--) { propertyPathBuilder.Append(GetItemName(ancestors[i])); propertyPathBuilder.Append('/'); } propertyPathBuilder.Append(GetItemName(id)); return propertyPathBuilder.ToString(); } public extern void Sort(int sortColumn, bool sortAscending); public override bool Equals(object obj) { var dataViewObj = obj as HierarchyFrameDataView; if (dataViewObj == null) return false; if (m_Ptr == dataViewObj.m_Ptr) return true; if (m_Ptr == IntPtr.Zero || dataViewObj.m_Ptr == IntPtr.Zero) return false; return frameIndex.Equals(dataViewObj.frameIndex) && threadIndex.Equals(dataViewObj.threadIndex) && viewMode.Equals(dataViewObj.viewMode) && sortColumn.Equals(dataViewObj.sortColumn) && sortColumnAscending.Equals(dataViewObj.sortColumnAscending); } public override int GetHashCode() { return frameIndex.GetHashCode() ^ (threadIndex.GetHashCode() << 8) ^ (viewMode.GetHashCode() << 24); } new internal static class BindingsMarshaller { public static IntPtr ConvertToNative(HierarchyFrameDataView frameDataView) => frameDataView.m_Ptr; } } }
UnityCsReference/Modules/ProfilerEditor/Public/HierarchyFrameDataView.bindings.cs/0
{ "file_path": "UnityCsReference/Modules/ProfilerEditor/Public/HierarchyFrameDataView.bindings.cs", "repo_id": "UnityCsReference", "token_count": 5008 }
432
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License namespace Unity.Properties { /// <summary> /// The <see cref="PropertyContainer"/> class is used as the entry point to operate on data containers using properties. /// </summary> public static partial class PropertyContainer { } }
UnityCsReference/Modules/Properties/Runtime/Algorithms/PropertyContainer.cs/0
{ "file_path": "UnityCsReference/Modules/Properties/Runtime/Algorithms/PropertyContainer.cs", "repo_id": "UnityCsReference", "token_count": 121 }
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.Generic; namespace Unity.Properties { /// <summary> /// This interface provides access to an <see cref="IProperty{TContainer}"/> of a <see cref="IPropertyBag{TContainer}"/> by index. /// </summary> /// <typeparam name="TContainer">The container type to access.</typeparam> public interface IIndexedProperties<TContainer> { /// <summary> /// Gets the property associated with the specified index. /// </summary> /// <param name="container">The container hosting the data.</param> /// <param name="index">The index of the property to get.</param> /// <param name="property">When this method returns, contains the property associated with the specified index, if the name is found; otherwise, null.</param> /// <returns><see langword="true"/> if the <see cref="IIndexedProperties{TContainer}"/> contains a property for the specified index; otherwise, <see langword="false"/>.</returns> bool TryGetProperty(ref TContainer container, int index, out IProperty<TContainer> property); } /// <summary> /// This interface provides access to an <see cref="IProperty{TContainer}"/> of a <see cref="IPropertyBag{TContainer}"/> by name. /// </summary> /// <typeparam name="TContainer">The container type to access.</typeparam> public interface INamedProperties<TContainer> { /// <summary> /// Gets the property associated with the specified name. /// </summary> /// <param name="container">The container hosting the data.</param> /// <param name="name">The name of the property to get.</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> bool TryGetProperty(ref TContainer container, string name, out IProperty<TContainer> property); } /// <summary> /// This interface provides access to an <see cref="IProperty{TContainer}"/> of a <see cref="IPropertyBag{TContainer}"/> by a key. /// </summary> /// <typeparam name="TContainer">The container type to access.</typeparam> /// <typeparam name="TKey">The key type to access the property with.</typeparam> public interface IKeyedProperties<TContainer, TKey> { /// <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> bool TryGetProperty(ref TContainer container, TKey key, out IProperty<TContainer> property); } /// <summary> /// Base untyped interface for implementing property bags. /// </summary> public interface IPropertyBag { /// <summary> /// Call this method to invoke <see cref="ITypeVisitor.Visit{TContainer}"/> with the strongly typed container type. /// </summary> /// <param name="visitor">The visitor being run.</param> void Accept(ITypeVisitor visitor); /// <summary> /// Call this method to invoke <see cref="IPropertyBagVisitor.Visit{TContainer}"/> with the strongly typed container for the given <see cref="container"/> object. /// </summary> /// <param name="visitor">The visitor to invoke the visit callback on.</param> /// <param name="container">The container being visited.</param> void Accept(IPropertyBagVisitor visitor, ref object container); } /// <summary> /// Base typed interface for implementing property bags. /// </summary> public interface IPropertyBag<TContainer> : IPropertyBag { /// <summary> /// Returns an enumerator that iterates through all static properties for the type. /// </summary> /// <remarks> /// This should return a subset properties returned by <see cref="GetProperties(ref TContainer)"/>. /// </remarks> /// <returns>A <see cref="IEnumerator{IProperty}"/> structure for all properties.</returns> PropertyCollection<TContainer> GetProperties(); /// <summary> /// Returns an enumerator that iterates through all static and dynamic properties for the given container. /// </summary> /// <remarks> /// This should return all static properties returned by <see cref="GetProperties()"/> in addition to any dynamic properties. /// If the container is a collection type all elements will be iterated. /// </remarks> /// <param name="container">The container hosting the data.</param> /// <returns>A <see cref="IEnumerator{IProperty}"/> structure for all properties.</returns> PropertyCollection<TContainer> GetProperties(ref TContainer container); /// <summary> /// Creates and returns a new instance of <see cref="TContainer"/>. /// </summary> /// <returns>A new instance of <see cref="TContainer"/>.</returns> TContainer CreateInstance(); /// <summary> /// Tries to create a new instance of <see cref="TContainer"/>. /// </summary> /// <param name="instance">When this method returns, contains the created instance, if type construction succeeded; otherwise, the default value for <typeparamref name="TContainer"/>.</param> /// <returns><see langword="true"/> if a new instance of type <see cref="TContainer"/> was created; otherwise, <see langword="false"/>.</returns> bool TryCreateInstance(out TContainer instance); /// <summary> /// Call this method to invoke <see cref="IPropertyBagVisitor.Visit{TContainer}"/> with the strongly typed container. /// </summary> /// <param name="visitor">The visitor being run.</param> /// <param name="container">The container being visited.</param> void Accept(IPropertyBagVisitor visitor, ref TContainer container); } /// <summary> /// Base untyped interface for implementing collection based property bags. /// </summary> public interface ICollectionPropertyBag<TCollection, TElement> : IPropertyBag<TCollection>, ICollectionPropertyBagAccept<TCollection> where TCollection : ICollection<TElement> { } /// <summary> /// Base typed interface for implementing list based property bags. /// </summary> public interface IListPropertyBag<TList, TElement> : ICollectionPropertyBag<TList, TElement>, IListPropertyBagAccept<TList>, IListPropertyAccept<TList>, IIndexedProperties<TList> where TList : IList<TElement> { } /// <summary> /// Base typed interface for implementing set based property bags. /// </summary> public interface ISetPropertyBag<TSet, TElement> : ICollectionPropertyBag<TSet, TElement>, ISetPropertyBagAccept<TSet>, ISetPropertyAccept<TSet>, IKeyedProperties<TSet, object> where TSet : ISet<TElement> { } /// <summary> /// Base typed interface for implementing dictionary based property bags. /// </summary> public interface IDictionaryPropertyBag<TDictionary, TKey, TValue> : ICollectionPropertyBag<TDictionary, KeyValuePair<TKey, TValue>>, IDictionaryPropertyBagAccept<TDictionary>, IDictionaryPropertyAccept<TDictionary>, IKeyedProperties<TDictionary, object> where TDictionary : IDictionary<TKey, TValue> { } }
UnityCsReference/Modules/Properties/Runtime/PropertyBags/IPropertyBag.cs/0
{ "file_path": "UnityCsReference/Modules/Properties/Runtime/PropertyBags/IPropertyBag.cs", "repo_id": "UnityCsReference", "token_count": 2655 }
434
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License namespace Unity.Properties { /// <summary> /// Base class to implement a visitor responsible for getting an object's concrete type as a generic. /// </summary> /// <remarks> /// It is required that the visited object is a container type with a property bag. /// </remarks> public abstract class ConcreteTypeVisitor : IPropertyBagVisitor { /// <summary> /// Implement this method to receive the strongly typed callback for a given container. /// </summary> /// <param name="container">The reference to the container.</param> /// <typeparam name="TContainer">The container type.</typeparam> protected abstract void VisitContainer<TContainer>(ref TContainer container); void IPropertyBagVisitor.Visit<TContainer>(IPropertyBag<TContainer> properties, ref TContainer container) => VisitContainer(ref container); } }
UnityCsReference/Modules/Properties/Runtime/PropertyVisitors/ConcreteTypeVisitor.cs/0
{ "file_path": "UnityCsReference/Modules/Properties/Runtime/PropertyVisitors/ConcreteTypeVisitor.cs", "repo_id": "UnityCsReference", "token_count": 334 }
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 System.Collections.Generic; using UnityEngine; using UnityEngine.Internal; using UnityEngine.UIElements; namespace UnityEditor.Search { /// <summary> /// DisplayMode for a <see cref="ISearchView"/> /// </summary> public enum DisplayMode { /// <summary>Unspecified ISearchView display mode</summary> None = 0, /// <summary>Display as a list view in compact mode</summary> Compact = 1, /// <summary>Display as a list view</summary> List = 32, /// <summary>Display as a Grid of icons of various size.</summary> Grid = 96, [ExcludeFromDocs] /// <summary>Maximum grid size</summary> Limit = 128, /// <summary>Table view used to bulk edit search results.</summary> Table = 129, } /// <summary> /// Where to place the cursor in the text are of a <see cref="ISearchView"/> (see <see cref="ISearchView.SetSearchText"/>). /// </summary> public enum TextCursorPlacement { /// <summary>Do not move the cursor.</summary> None, /// <summary>Move the cursor at the end of the line of text.</summary> MoveLineEnd, /// <summary>Move the cursor at the beginning of the line of text.</summary> MoveLineStart, /// <summary>Move the cursor the the end of the previous word.</summary> MoveToEndOfPreviousWord, /// <summary>Move the cursor the the start of the previous word.</summary> MoveToStartOfNextWord, /// <summary>Move the cursor one word to the left.</summary> MoveWordLeft, /// <summary>Move the cursor one word to the right.</summary> MoveWordRight, /// <summary>Move the cursor one word to the right for auto complete mode.</summary> MoveAutoComplete, /// <summary>Default cursor position (end of the line of text).</summary> Default = MoveLineEnd } [Flags] public enum RefreshFlags { None = 0, // Normal refresh Default = 1 << 0, // The structure of the current selection data has changed StructureChanged = 1 << 1, // The display mode or item size has changed DisplayModeChanged = 1 << 2, // The search item list has been updated ItemsChanged = 1 << 3, // The current item group has changed. GroupChanged = 1 << 4, // A search query was initiated QueryStarted = 1 << 5, // A search query has completed QueryCompleted = 1 << 6, } /// <summary> /// Search view interface used by the search context to execute a few UI operations. /// </summary> public interface ISearchView : IDisposable { /// <summary> /// Returns the selected item in the view /// </summary> SearchSelection selection { get; } /// <summary> /// Return the list of all search results. /// </summary> ISearchList results { get; } /// <summary> /// Returns the current view search context /// </summary> SearchContext context { get; } /// <summary> /// Returns the view state /// </summary> SearchViewState state { get; } /// <summary> /// Current group of items being displayed if any. /// </summary> string currentGroup { get; set; } /// <summary> /// Defines the size of items in the search view. /// </summary> float itemIconSize { get; set; } /// <summary> /// Indicates how the data is displayed in the UI. /// </summary> DisplayMode displayMode { get; } /// <summary> /// Allow multi-selection or not. /// </summary> bool multiselect { get; set; } /// <summary> /// Absolute coordinate of the search view /// </summary> Rect position { get; } /// <summary> /// Indicates if a search is still running /// </summary> bool searchInProgress { get; } /// <summary> /// Callback used to override the select behavior. /// </summary> Action<SearchItem, bool> selectCallback { get; } /// <summary> /// Callback used to filter items shown in the list. /// </summary> Func<SearchItem, bool> filterCallback { get; } /// <summary> /// Callback used to override the tracking behavior. /// </summary> Action<SearchItem> trackingCallback { get; } /// <summary> /// Update the search view with a new selection. /// </summary> /// <param name="selection">Array of item indices to select</param> void SetSelection(params int[] selection); /// <summary> /// Add new items to the current selection /// </summary> /// <param name="selection">Array of item indices to add to selection</param> void AddSelection(params int[] selection); /// <summary> /// Sets the search query text. /// </summary> /// <param name="searchText">Text to be displayed in the search view.</param> /// <param name="moveCursor">Where to place the cursor after having set the search text</param> void SetSearchText(string searchText, TextCursorPlacement moveCursor = TextCursorPlacement.Default); void SetSearchText(string searchText, TextCursorPlacement moveCursor, int cursorInsertPosition); /// <summary> /// Make sure the search is now focused. /// </summary> void Focus(); /// <summary> /// Triggers a refresh of the search view, re-fetching all the search items from enabled search providers. /// </summary> void Refresh(RefreshFlags reason = RefreshFlags.Default); /// <summary> /// Request the search view to repaint itself /// </summary> void Repaint(); /// <summary> /// Execute a Search Action on a given list of items. /// </summary> /// <param name="action">Action to execute.</param> /// <param name="items">Items to apply the action on.</param> /// <param name="endSearch">If true, executing this action will close the Quicksearch window.</param> void ExecuteAction(SearchAction action, SearchItem[] items, bool endSearch = true); /// <summary> /// Execute the default action of the active selection. /// </summary> void ExecuteSelection(); /// <summary> /// Close the search view /// </summary> void Close(); /// <summary> /// Show a contextual menu for the specified item. /// </summary> /// <param name="item">Item affected by the contextual menu.</param> /// <param name="contextualActionPosition">Where the menu should be drawn on screen (generally item position)</param> void ShowItemContextualMenu(SearchItem item, Rect contextualActionPosition); /// <summary> /// Request to focus and select the search field. /// </summary> void SelectSearch(); /// <summary> /// Focus the search text field control. /// </summary> void FocusSearch(); /// <summary> /// Set table view columns. /// </summary> void SetColumns(IEnumerable<SearchColumn> columns); /// <summary> /// Indicates if the current view is in picking mode or not. /// </summary> /// <returns></returns> bool IsPicker(); internal int GetViewId(); internal int totalCount { get; } internal bool syncSearch { get; set; } internal SearchPreviewManager previewManager { get; } internal IEnumerable<IGroup> EnumerateGroups(); internal void SetupColumns(IList<SearchField> fields); internal IEnumerable<SearchQueryError> GetAllVisibleErrors(); } interface ISearchQueryView { bool CanSaveQuery(); void SaveUserSearchQuery(); void SaveProjectSearchQuery(); void SaveActiveSearchQuery(); void ExecuteSearchQuery(ISearchQuery query); } interface ISearchField { int controlID { get; } int cursorIndex { get; } string text { get; } void Focus(); VisualElement GetTextElement(); } }
UnityCsReference/Modules/QuickSearch/Editor/ISearchView.cs/0
{ "file_path": "UnityCsReference/Modules/QuickSearch/Editor/ISearchView.cs", "repo_id": "UnityCsReference", "token_count": 3287 }
436
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License // #define USE_PERFORMANCE_TRACKER using System; using System.Collections.Generic; using System.Collections.Concurrent; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using UnityEditorInternal; using UnityEngine; namespace UnityEditor.Search { public interface IPropertyDatabaseView : IDisposable { public bool Store(string documentId, string propertyPath, object value); public bool Store(ulong documentKey, Hash128 propertyHash, object value); public bool Store(Hash128 propertyHash, object value); public bool Store(in PropertyDatabaseRecordKey recordKey, object value); bool TryLoad(in PropertyDatabaseRecordKey recordKey, out object data); bool TryLoad(in PropertyDatabaseRecordKey recordKey, out IPropertyDatabaseRecordValue data); bool TryLoad(ulong documentKey, out IEnumerable<object> data); bool TryLoad(ulong documentKey, out IEnumerable<IPropertyDatabaseRecord> records); void Invalidate(string documentId); void Invalidate(ulong documentKey); void Invalidate(in PropertyDatabaseRecordKey recordKey); void InvalidateMask(ulong documentKeyMask); IEnumerable<IPropertyDatabaseRecord> EnumerateAll(); void Sync(); void Clear(); public PropertyDatabaseRecordKey CreateRecordKey(string documentId, string propertyPath); public PropertyDatabaseRecordKey CreateRecordKey(ulong documentKey, Hash128 propertyPathHash); public PropertyDatabaseRecordKey CreateRecordKey(string propertyPath); public PropertyDatabaseRecordKey CreateRecordKey(string documentId, Hash128 propertyHash); public PropertyDatabaseRecordKey CreateRecordKey(Hash128 propertyHash); public ulong CreateDocumentKey(string documentId); public Hash128 CreatePropertyHash(string propertyPath); TValue GetValueFromRecord<TValue>(IPropertyDatabaseRecordValue recordValue); public bool IsPersistableType(Type type); } class PropertyDatabaseLock : IDisposable { static Dictionary<string, SharedCounter> s_DatabaseFiles = new Dictionary<string, SharedCounter>(); class SharedCounter { public int value; public SharedCounter(int value) { this.value = value; } } string m_Path; bool m_Disposed; PropertyDatabaseLock(string propertyDatabasePath, SharedCounter counter) { m_Path = propertyDatabasePath; } PropertyDatabaseLock(PropertyDatabaseLock other) { this.m_Path = other.m_Path; this.m_Disposed = other.m_Disposed; } public static bool TryOpen(string propertyDatabasePath, out PropertyDatabaseLock pdbl) { pdbl = null; try { lock (s_DatabaseFiles) { if (s_DatabaseFiles.TryGetValue(propertyDatabasePath, out var _)) { return false; } var counter = new SharedCounter(1); s_DatabaseFiles.Add(propertyDatabasePath, counter); pdbl = new PropertyDatabaseLock(propertyDatabasePath, counter); return true; } } catch (Exception) { pdbl = null; return false; } } public PropertyDatabaseLock Share() { lock(s_DatabaseFiles) { if (m_Disposed) throw new ObjectDisposedException(m_Path, "Trying to share a lock that has already been disposed."); if (!s_DatabaseFiles.TryGetValue(m_Path, out var counter)) throw new System.Exception($"Data base {m_Path} is not opened."); ++counter.value; return new PropertyDatabaseLock(this); } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } ~PropertyDatabaseLock() { Dispose(false); } void Dispose(bool disposed) { lock (s_DatabaseFiles) { if (m_Disposed) return; m_Disposed = true; if (s_DatabaseFiles.TryGetValue(m_Path, out var counter)) { --counter.value; if (counter.value == 0) { s_DatabaseFiles.Remove(m_Path); } } } } } public class PropertyDatabase : IDisposable { PropertyDatabaseVolatileMemoryStore m_LocalVolatileStore; PropertyDatabaseMemoryStore m_LocalStore; PropertyDatabaseFileStore m_FileStore; PropertyStringTable m_StringTable; PropertyDatabaseLock m_PropertyDatabaseLock; internal static readonly int version = ((0x50 << 24) | (0x44 << 16) | 0x0007) ^ PropertyStringTable.version ^ ((InternalEditorUtility.GetUnityVersion().Major & 0xffff) << 16 | InternalEditorUtility.GetUnityVersion().Minor); public string filePath { get; } internal string stringTableFilePath { get; } public bool autoFlush { get; } public bool valid => m_Valid && !disposed; const double k_DefaultBackgroundUpdateDebounceInSeconds = 5.0; Delayer m_Debounce; bool m_Valid; internal bool disposed { get; private set; } internal PropertyDatabaseErrorView disposedView { get; private set; } public PropertyDatabase(string filePath) : this(filePath, false) {} public PropertyDatabase(string filePath, bool autoFlush, double backgroundUpdateDebounceInSeconds = k_DefaultBackgroundUpdateDebounceInSeconds) { if (string.IsNullOrEmpty(filePath)) throw new System.ArgumentNullException(nameof(filePath)); this.filePath = filePath; stringTableFilePath = GetStringTablePath(filePath); disposedView = new PropertyDatabaseErrorView($"The property database has already been disposed."); if (PropertyDatabaseLock.TryOpen(filePath, out m_PropertyDatabaseLock)) { m_LocalVolatileStore = new PropertyDatabaseVolatileMemoryStore(); m_LocalStore = new PropertyDatabaseMemoryStore(); m_FileStore = new PropertyDatabaseFileStore(filePath); m_StringTable = new PropertyStringTable(stringTableFilePath, 30); // Do not allow automatic background updates while running tests. The writing of the file // causes an assembly leak during the test Unity.IntegrationTests.Scripting.AssemblyReloadTest.AssemblyReloadDoesntLeakAssemblies // on MacOs. I haven't found out why exactly does the writing of a file causes an assembly to be held, so instead I deactivate // the automatic update during tests. this.autoFlush = autoFlush && !Utils.IsRunningTests(); m_Debounce = Delayer.Debounce(_ => TriggerBackgroundUpdate(), backgroundUpdateDebounceInSeconds); m_Valid = true; } else { this.autoFlush = false; m_Valid = false; } } public bool Store(string documentId, string propertyPath, object value) { using (var view = GetView()) return view.Store(documentId, propertyPath, value); } public bool Store(ulong documentKey, Hash128 propertyHash, object value) { using (var view = GetView()) return view.Store(documentKey, propertyHash, value); } public bool Store(Hash128 propertyHash, object value) { using (var view = GetView()) return view.Store(propertyHash, value); } public bool Store(in PropertyDatabaseRecordKey recordKey, object value) { using (var view = GetView()) return view.Store(recordKey, value); } internal bool Store(in PropertyDatabaseRecordKey recordKey, in PropertyDatabaseRecordValue value) { using (var view = (PropertyDatabaseView)GetView()) return view.Store(recordKey, value); } internal bool Store(in PropertyDatabaseRecord record) { using (var view = (PropertyDatabaseView)GetView()) return view.Store(record); } public bool TryLoad(in PropertyDatabaseRecordKey recordKey, out object value) { using (var view = GetView()) return view.TryLoad(recordKey, out value); } public bool TryLoad(in PropertyDatabaseRecordKey recordKey, out IPropertyDatabaseRecordValue value) { using (var view = GetView()) return view.TryLoad(recordKey, out value); } internal bool TryLoad(in PropertyDatabaseRecordKey recordKey, out PropertyDatabaseRecordValue value) { using (var view = (PropertyDatabaseView)GetView()) return view.TryLoad(recordKey, out value); } public bool TryLoad(ulong documentKey, out IEnumerable<object> data) { using (var view = GetView()) return view.TryLoad(documentKey, out data); } public bool TryLoad(ulong documentKey, out IEnumerable<IPropertyDatabaseRecord> records) { using (var view = GetView()) return view.TryLoad(documentKey, out records); } public void Invalidate(string documentId) { using (var view = GetView()) view.Invalidate(documentId); } public void Invalidate(ulong documentKey) { using (var view = GetView()) view.Invalidate(documentKey); } public void Invalidate(in PropertyDatabaseRecordKey recordKey) { using (var view = GetView()) view.Invalidate(recordKey); } internal void Invalidate(uint documentKeyHiWord) { using (var view = GetView()) view.Invalidate(documentKeyHiWord); } public void InvalidateMask(ulong documentKeyMask) { using (var view = GetView()) view.InvalidateMask(documentKeyMask); } internal void InvalidateMask(uint documentKeyHiWordMask) { using (var view = GetView()) view.InvalidateMask(documentKeyHiWordMask); } public void Clear() { using (var view = GetView()) view.Clear(); } internal PropertyDatabaseRecord CreateRecord(string documentId, string propertyPath, object value) { return CreateRecord(CreateDocumentKey(documentId), CreatePropertyHash(propertyPath), value); } internal PropertyDatabaseRecord CreateRecord(string documentId, string propertyPath, object value, PropertyStringTableView view) { return CreateRecord(CreateDocumentKey(documentId), CreatePropertyHash(propertyPath), value, view); } internal PropertyDatabaseRecord CreateRecord(ulong documentKey, Hash128 propertyPathHash, object value) { var key = CreateRecordKey(documentKey, propertyPathHash); return CreateRecord(key, value); } internal PropertyDatabaseRecord CreateRecord(ulong documentKey, Hash128 propertyPathHash, object value, PropertyStringTableView view) { var key = CreateRecordKey(documentKey, propertyPathHash); return CreateRecord(key, value, view); } internal PropertyDatabaseRecord CreateRecord(string propertyPath, object value) { return CreateRecord(CreatePropertyHash(propertyPath), value); } internal PropertyDatabaseRecord CreateRecord(string propertyPath, object value, PropertyStringTableView view) { return CreateRecord(CreatePropertyHash(propertyPath), value, view); } internal PropertyDatabaseRecord CreateRecord(Hash128 propertyPathHash, object value) { return CreateRecord(0, propertyPathHash, value); } internal PropertyDatabaseRecord CreateRecord(Hash128 propertyPathHash, object value, PropertyStringTableView view) { return CreateRecord(0, propertyPathHash, value, view); } internal PropertyDatabaseRecord CreateRecord(in PropertyDatabaseRecordKey recordKey, object value) { var recordValue = CreateRecordValue(value); return CreateRecord(recordKey, recordValue); } internal PropertyDatabaseRecord CreateRecord(in PropertyDatabaseRecordKey recordKey, object value, PropertyStringTableView view) { var recordValue = CreateRecordValue(value, view); return CreateRecord(recordKey, recordValue); } internal static PropertyDatabaseRecord CreateRecord(in PropertyDatabaseRecordKey recordKey, PropertyDatabaseRecordValue recordValue) { if (!IsSupportedPropertyType(recordValue.propertyType)) throw new ArgumentException($"Property type of {nameof(recordValue)} is not supported."); return new PropertyDatabaseRecord(recordKey, recordValue); } public static PropertyDatabaseRecordKey CreateRecordKey(string documentId, string propertyPath) { return CreateRecordKey(documentId, CreatePropertyHash(propertyPath)); } public static Hash128 CreatePropertyHash(string propertyPath) { return Hash128.Compute(propertyPath); } public static PropertyDatabaseRecordKey CreateRecordKey(ulong documentKey, Hash128 propertyPathHash) { return new PropertyDatabaseRecordKey(documentKey, propertyPathHash); } public static PropertyDatabaseRecordKey CreateRecordKey(string propertyPath) { return CreateRecordKey(CreatePropertyHash(propertyPath)); } public static PropertyDatabaseRecordKey CreateRecordKey(string documentId, Hash128 propertyHash) { return CreateRecordKey(CreateDocumentKey(documentId), propertyHash); } public static PropertyDatabaseRecordKey CreateRecordKey(Hash128 propertyHash) { return CreateRecordKey(0, propertyHash); } public static ulong CreateDocumentKey(string documentId) { return string.IsNullOrEmpty(documentId) ? 0UL : documentId.GetHashCode64(); } internal PropertyDatabaseRecordValue CreateRecordValue(object value) { if (!valid) return PropertyDatabaseRecordValue.invalid; using (var view = m_StringTable.GetView()) return CreateRecordValue(value, view); } internal PropertyDatabaseRecordValue CreateRecordValue(object value, PropertyStringTableView stringTableView) { if (!IsPersistableType(value.GetType())) throw new ArgumentException($"Type \"{value.GetType()}\" is not supported."); return PropertyDatabaseSerializerManager.Serialize(value, stringTableView); } internal object GetObjectFromRecordValue(in PropertyDatabaseRecordValue recordValue) { if (!valid) return null; using (var view = m_StringTable.GetView()) return GetObjectFromRecordValue(recordValue, view); } public TValue GetValueFromRecord<TValue>(IPropertyDatabaseRecordValue recordValue) { if (!valid) return default; using (var view = m_StringTable.GetView()) return GetValueFromRecord<TValue>(recordValue, view); } internal object GetObjectFromRecordValue(in PropertyDatabaseRecordValue recordValue, PropertyStringTableView stringTableView) { if (!IsSupportedPropertyType(recordValue.propertyType)) throw new ArgumentException($"Property type \"{recordValue.propertyType}\" of {nameof(recordValue)} is not supported."); return PropertyDatabaseSerializerManager.Deserialize(recordValue, stringTableView); } internal object GetObjectFromRecordValue(IPropertyDatabaseRecordValue recordValue) { if (!valid) return null; using (var view = m_StringTable.GetView()) return GetObjectFromRecordValue(recordValue, view); } internal object GetObjectFromRecordValue(IPropertyDatabaseRecordValue recordValue, PropertyStringTableView stringTableView) { if (recordValue == null) return null; if (recordValue.type != PropertyDatabaseType.Volatile) return GetObjectFromRecordValue((PropertyDatabaseRecordValue)recordValue, stringTableView); var volatileRecordValue = (PropertyDatabaseVolatileRecordValue)recordValue; return volatileRecordValue.value; } internal TValue GetValueFromRecord<TValue>(IPropertyDatabaseRecordValue recordValue, PropertyStringTableView stringTableView) { if (recordValue == null) return default; if (recordValue.type != PropertyDatabaseType.Volatile) return (TValue)GetObjectFromRecordValue((PropertyDatabaseRecordValue)recordValue, stringTableView); var volatileRecordValue = (PropertyDatabaseVolatileRecordValue)recordValue; return (TValue)volatileRecordValue.value; } public static bool IsPersistableType(Type type) { return PropertyDatabaseSerializerManager.SerializerExists(type); } internal static bool IsSupportedPropertyType(byte propertyType) { return PropertyDatabaseSerializerManager.DeserializerExists((PropertyDatabaseType)propertyType); } public IPropertyDatabaseView GetView(bool delayedSync = false) { { if (valid) return new PropertyDatabaseView(this, m_LocalVolatileStore, m_LocalStore, m_FileStore, m_StringTable, m_PropertyDatabaseLock.Share(), delayedSync); if (!disposed) return new PropertyDatabaseErrorView($"The property database \"{filePath}\" is already opened."); return disposedView; } } public void Flush() { if (!valid) return; var task = TriggerBackgroundUpdate(); task.Wait(); } internal Task TriggerBackgroundUpdate() { var task = Task.Run(() => { try { MergeStoresToFile(); } catch (ThreadAbortException) { // Rethrow but do not log. throw; } catch (Exception ex) { Debug.LogException(ex); throw; } }); return task; } internal void StoresChanged() { if (!autoFlush) return; lock (this) { m_Debounce?.Execute(); } } public string GetInfo() { if (!valid) return string.Empty; var sb = new StringBuilder(); sb.AppendLine($"Property Database: \"{filePath}\""); GetStoreInfo(m_LocalVolatileStore, "Volatile Store", sb); GetStoreInfo(m_LocalStore, "Non-Serialized Store", sb); GetStoreInfo(m_FileStore, "Serialized Store (on disk)", sb); GetStringTableInfo(m_StringTable, sb); return sb.ToString(); } static void GetStoreInfo(IPropertyDatabaseStore store, string storeTitle, StringBuilder sb) { using (var view = store.GetView()) { sb.AppendLine($"\t{storeTitle}:"); sb.AppendLine($"\t\tCount: {view.length}"); sb.AppendLine($"\t\tSize: {Utils.FormatBytes(view.byteSize)}"); } } static void GetStringTableInfo(PropertyStringTable st, StringBuilder sb) { var longestStringsCount = 5; using (var view = st.GetView()) { sb.AppendLine($"\tString Table: {st.filePath}"); sb.AppendLine($"\t\tVersion: {view.version}"); sb.AppendLine($"\t\tCount: {view.count}"); sb.AppendLine($"\t\tSymbols slots: {view.symbolSlots}"); sb.AppendLine($"\t\tAllocated bytes for strings: {Utils.FormatBytes(view.allocatedStringBytes)}"); sb.AppendLine($"\t\tUsed bytes for strings: {Utils.FormatBytes(view.usedStringBytes)}"); sb.AppendLine($"\t\tAverage byte size for strings: {Utils.FormatBytes(view.GetAverageBytesPerString())}"); sb.AppendLine($"\t\tFile size: {Utils.FormatBytes(view.fileSize)}"); sb.AppendLine($"\t\tTop {longestStringsCount} longest strings:"); var strings = view.GetAllStrings(); foreach (var str in strings.OrderByDescending(s => s.Length).Take(longestStringsCount)) { sb.AppendLine($"\t\t\t{str}"); } } } void MergeStoresToFile() { if (!valid) return; // TODO: When trackers are removed, put back GetView() using (var view = new PropertyDatabaseView(this, m_LocalVolatileStore, m_LocalStore, m_FileStore, m_StringTable, m_PropertyDatabaseLock.Share(), false)) view.MergeStores(); } static string GetStringTablePath(string propertyDatabasePath) { return propertyDatabasePath + ".st"; } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } void Dispose(bool _) { lock (this) { if (disposed) return; m_Debounce?.Dispose(); m_Debounce = null; m_PropertyDatabaseLock?.Dispose(); m_PropertyDatabaseLock = null; disposed = true; } } ~PropertyDatabase() { Dispose(false); } } struct PropertyDatabaseView : IPropertyDatabaseView { bool m_Disposed; bool m_DelayedSync; PropertyDatabase m_PropertyDatabase; PropertyDatabaseMemoryStore m_MemoryStore; PropertyDatabaseFileStore m_FileStore; PropertyDatabaseLock m_Lock; PropertyDatabaseVolatileMemoryStoreView m_VolatileMemoryStoreView; PropertyDatabaseMemoryStoreView m_MemoryStoreView; PropertyDatabaseFileStoreView m_FileStoreView; PropertyStringTableView m_StringTableView; // Internal for debugging internal PropertyDatabaseVolatileMemoryStoreView volatileMemoryStoreView => m_VolatileMemoryStoreView; internal PropertyDatabaseMemoryStoreView memoryStoreView => m_MemoryStoreView; internal PropertyDatabaseFileStoreView fileStoreView => m_FileStoreView; internal PropertyStringTableView stringTableView => m_StringTableView; internal PropertyDatabase database => m_PropertyDatabase; internal PropertyDatabaseView(PropertyDatabase propertyDatabase, PropertyDatabaseVolatileMemoryStore volatileMemoryStore, PropertyDatabaseMemoryStore memoryStore, PropertyDatabaseFileStore fileStore, PropertyStringTable stringTable, PropertyDatabaseLock propertyDatabaseLock, bool delayedSync) { m_PropertyDatabase = propertyDatabase; m_MemoryStore = memoryStore; m_FileStore = fileStore; m_VolatileMemoryStoreView = (PropertyDatabaseVolatileMemoryStoreView)volatileMemoryStore.GetView(); m_MemoryStoreView = (PropertyDatabaseMemoryStoreView)memoryStore.GetView(); m_FileStoreView = (PropertyDatabaseFileStoreView)fileStore.GetView(); m_StringTableView = stringTable.GetView(delayedSync); m_Disposed = false; m_DelayedSync = delayedSync; m_Lock = propertyDatabaseLock; } public void Dispose() { if (m_Disposed) return; if (m_DelayedSync) Sync(); m_PropertyDatabase = null; m_MemoryStore = null; m_FileStore = null; m_VolatileMemoryStoreView.Dispose(); m_MemoryStoreView.Dispose(); m_FileStoreView.Dispose(); m_StringTableView.Dispose(); m_Lock.Dispose(); m_Lock = null; m_DelayedSync = false; m_Disposed = true; } public bool Store(string documentId, string propertyPath, object value) { if (m_PropertyDatabase.disposed) return m_PropertyDatabase.disposedView.Store(documentId, propertyPath, value); var recordKey = CreateRecordKey(documentId, propertyPath); return Store(recordKey, value); } public bool Store(ulong documentKey, Hash128 propertyHash, object value) { if (m_PropertyDatabase.disposed) return m_PropertyDatabase.disposedView.Store(documentKey, propertyHash, value); var recordKey = CreateRecordKey(documentKey, propertyHash); return Store(recordKey, value); } public bool Store(Hash128 propertyHash, object value) { if (m_PropertyDatabase.disposed) return m_PropertyDatabase.disposedView.Store(propertyHash, value); var recordKey = CreateRecordKey(propertyHash); return Store(recordKey, value); } public bool Store(in PropertyDatabaseRecordKey recordKey, object value) { { if (m_PropertyDatabase.disposed) return m_PropertyDatabase.disposedView.Store(recordKey, value); if (!IsPersistableType(value.GetType())) return m_VolatileMemoryStoreView.Store(recordKey, value, !m_DelayedSync); var record = m_PropertyDatabase.CreateRecord(recordKey, value, m_StringTableView); return Store(record); } } public bool Store(in PropertyDatabaseRecordKey recordKey, in PropertyDatabaseRecordValue value) { if (m_PropertyDatabase.disposed) return m_PropertyDatabase.disposedView.Store(recordKey, value); var record = CreateRecord(recordKey, value); return Store(record); } public bool Store(in PropertyDatabaseRecord record) { { if (m_PropertyDatabase.disposed) return m_PropertyDatabase.disposedView.Store(record); if (!record.recordValue.valid) return false; var success = m_MemoryStoreView.Store(record, !m_DelayedSync); if (success) { m_PropertyDatabase.StoresChanged(); } return success; } } public bool TryLoad(in PropertyDatabaseRecordKey recordKey, out object data) { { data = null; if (m_PropertyDatabase.disposed) return m_PropertyDatabase.disposedView.TryLoad(recordKey, out data); if (!TryLoad(recordKey, out PropertyDatabaseRecordValue recordValue)) return m_VolatileMemoryStoreView.TryLoad(recordKey, out data); data = GetObjectFromRecordValue(recordValue); return true; } } public bool TryLoad(in PropertyDatabaseRecordKey recordKey, out PropertyDatabaseRecordValue data) { { if (m_PropertyDatabase.disposed) return m_PropertyDatabase.disposedView.TryLoad(recordKey, out data); data = PropertyDatabaseRecordValue.invalid; if (m_MemoryStoreView.TryLoad(recordKey, out PropertyDatabaseRecord memoryRecord, true)) { // If data is invalid, it was deliberately made invalid, so it should be invalid in the // filestore too. data = memoryRecord.recordValue; return memoryRecord.IsValid(); } if (!m_FileStoreView.TryLoad(recordKey, out PropertyDatabaseRecord fileRecord)) return false; // Cache loaded value into memory store. data = fileRecord.recordValue; m_MemoryStoreView.Store(fileRecord, !m_DelayedSync); return true; } } public bool TryLoad(in PropertyDatabaseRecordKey recordKey, out IPropertyDatabaseRecordValue data) { { if (m_PropertyDatabase.disposed) return m_PropertyDatabase.disposedView.TryLoad(recordKey, out data); if (m_VolatileMemoryStoreView.TryLoad(recordKey, out IPropertyDatabaseRecord volatileRecord)) { data = volatileRecord.value; return true; } var success = TryLoad(recordKey, out PropertyDatabaseRecordValue recordValue); data = recordValue; return success; } } public bool TryLoad(ulong documentKey, out IEnumerable<object> data) { { data = null; if (m_PropertyDatabase.disposed) return m_PropertyDatabase.disposedView.TryLoad(documentKey, out data); if (!TryLoad(documentKey, out IEnumerable<IPropertyDatabaseRecord> records)) return false; var results = new List<object>(); foreach (var propertyDatabaseRecord in records) { results.Add(GetObjectFromRecordValue(propertyDatabaseRecord.value)); } data = results; return true; } } public bool TryLoad(ulong documentKey, out IEnumerable<IPropertyDatabaseRecord> records) { { records = null; if (m_PropertyDatabase.disposed) return m_PropertyDatabase.disposedView.TryLoad(documentKey, out records); SortedSet<IPropertyDatabaseRecord> allRecords = new SortedSet<IPropertyDatabaseRecord>(new IPropertyDatabaseRecordComparer()); if (m_VolatileMemoryStoreView.TryLoad(documentKey, out var volatileRecords)) allRecords.UnionWith(volatileRecords); if (m_MemoryStoreView.TryLoad(documentKey, out var memoryRecords)) allRecords.UnionWith(memoryRecords); if (m_FileStoreView.TryLoad(documentKey, out var fileRecords)) allRecords.UnionWith(fileRecords); if (allRecords.Count == 0) return false; records = allRecords; return true; } } public void Invalidate(string documentId) { if (m_PropertyDatabase.disposed) { m_PropertyDatabase.disposedView.Invalidate(documentId); return; } var documentKey = PropertyDatabase.CreateDocumentKey(documentId); Invalidate(documentKey); } public void Invalidate(ulong documentKey) { { if (m_PropertyDatabase.disposed) { m_PropertyDatabase.disposedView.Invalidate(documentKey); return; } m_VolatileMemoryStoreView.Invalidate(documentKey, !m_DelayedSync); m_MemoryStoreView.Invalidate(documentKey, !m_DelayedSync); m_FileStoreView.InvalidateInMemory(documentKey, !m_DelayedSync); m_PropertyDatabase.StoresChanged(); } } public void Invalidate(in PropertyDatabaseRecordKey recordKey) { { if (m_PropertyDatabase.disposed) { m_PropertyDatabase.disposedView.Invalidate(recordKey); return; } m_VolatileMemoryStoreView.Invalidate(recordKey, !m_DelayedSync); m_MemoryStoreView.Invalidate(recordKey, !m_DelayedSync); m_FileStoreView.InvalidateInMemory(m_MemoryStoreView, recordKey, !m_DelayedSync); m_PropertyDatabase.StoresChanged(); } } internal void Invalidate(uint documentKeyHiWord) { { if (m_PropertyDatabase.disposed) { m_PropertyDatabase.disposedView.Invalidate(documentKeyHiWord); return; } m_VolatileMemoryStoreView.Invalidate(documentKeyHiWord, !m_DelayedSync); m_MemoryStoreView.Invalidate(documentKeyHiWord, !m_DelayedSync); m_FileStoreView.InvalidateInMemory(documentKeyHiWord, !m_DelayedSync); m_PropertyDatabase.StoresChanged(); } } public void InvalidateMask(ulong documentKeyMask) { { if (m_PropertyDatabase.disposed) { m_PropertyDatabase.disposedView.InvalidateMask(documentKeyMask); return; } m_VolatileMemoryStoreView.InvalidateMask(documentKeyMask, !m_DelayedSync); m_MemoryStoreView.InvalidateMask(documentKeyMask, !m_DelayedSync); m_FileStoreView.InvalidateMaskInMemory(documentKeyMask, !m_DelayedSync); m_PropertyDatabase.StoresChanged(); } } internal void InvalidateMask(uint documentKeyHiWordMask) { { if (m_PropertyDatabase.disposed) { m_PropertyDatabase.disposedView.InvalidateMask(documentKeyHiWordMask); return; } m_VolatileMemoryStoreView.InvalidateMask(documentKeyHiWordMask, !m_DelayedSync); m_MemoryStoreView.InvalidateMask(documentKeyHiWordMask, !m_DelayedSync); m_FileStoreView.InvalidateMaskInMemory(documentKeyHiWordMask, !m_DelayedSync); m_PropertyDatabase.StoresChanged(); } } public IEnumerable<IPropertyDatabaseRecord> EnumerateAll() { { if (m_PropertyDatabase.disposed) return m_PropertyDatabase.disposedView.EnumerateAll(); SortedSet<IPropertyDatabaseRecord> allRecords = new SortedSet<IPropertyDatabaseRecord>(new IPropertyDatabaseRecordComparer()); allRecords.UnionWith(m_VolatileMemoryStoreView.EnumerateAll()); allRecords.UnionWith(m_MemoryStoreView.EnumerateAll()); allRecords.UnionWith(m_FileStoreView.EnumerateAll()); return allRecords; } } public void Sync() { if (m_PropertyDatabase.disposed) { m_PropertyDatabase.disposedView.Sync(); return; } m_VolatileMemoryStoreView.Sync(); m_MemoryStoreView.Sync(); m_FileStoreView.Sync(); m_StringTableView.Sync(); } public void Clear() { if (m_PropertyDatabase.disposed) { m_PropertyDatabase.disposedView.Clear(); return; } m_VolatileMemoryStoreView.Clear(); m_MemoryStoreView.Clear(); m_FileStoreView.Clear(); m_StringTableView.Clear(); } public PropertyDatabaseRecord CreateRecord(string documentId, string propertyPath, object value) { if (m_PropertyDatabase.disposed) return m_PropertyDatabase.disposedView.CreateRecord(documentId, propertyPath, value); return m_PropertyDatabase.CreateRecord(documentId, propertyPath, value, m_StringTableView); } public PropertyDatabaseRecord CreateRecord(ulong documentKey, Hash128 propertyPathHash, object value) { if (m_PropertyDatabase.disposed) return m_PropertyDatabase.disposedView.CreateRecord(documentKey, propertyPathHash, value); return m_PropertyDatabase.CreateRecord(documentKey, propertyPathHash, value, m_StringTableView); } public PropertyDatabaseRecord CreateRecord(string propertyPath, object value) { if (m_PropertyDatabase.disposed) return m_PropertyDatabase.disposedView.CreateRecord(propertyPath, value); return m_PropertyDatabase.CreateRecord(propertyPath, value, m_StringTableView); } public PropertyDatabaseRecord CreateRecord(Hash128 propertyPathHash, object value) { if (m_PropertyDatabase.disposed) return m_PropertyDatabase.disposedView.CreateRecord(propertyPathHash, value); return m_PropertyDatabase.CreateRecord(propertyPathHash, value, m_StringTableView); } public PropertyDatabaseRecord CreateRecord(in PropertyDatabaseRecordKey recordKey, object value) { if (m_PropertyDatabase.disposed) return m_PropertyDatabase.disposedView.CreateRecord(recordKey, value); return m_PropertyDatabase.CreateRecord(recordKey, value, m_StringTableView); } public PropertyDatabaseRecord CreateRecord(in PropertyDatabaseRecordKey recordKey, in PropertyDatabaseRecordValue recordValue) { if (m_PropertyDatabase.disposed) return m_PropertyDatabase.disposedView.CreateRecord(recordKey, recordValue); return PropertyDatabase.CreateRecord(recordKey, recordValue); } public PropertyDatabaseRecordKey CreateRecordKey(string documentId, string propertyPath) { if (m_PropertyDatabase.disposed) return m_PropertyDatabase.disposedView.CreateRecordKey(documentId, propertyPath); return PropertyDatabase.CreateRecordKey(documentId, propertyPath); } public PropertyDatabaseRecordKey CreateRecordKey(ulong documentKey, Hash128 propertyPathHash) { if (m_PropertyDatabase.disposed) return m_PropertyDatabase.disposedView.CreateRecordKey(documentKey, propertyPathHash); return PropertyDatabase.CreateRecordKey(documentKey, propertyPathHash); } public PropertyDatabaseRecordKey CreateRecordKey(string propertyPath) { if (m_PropertyDatabase.disposed) return m_PropertyDatabase.disposedView.CreateRecordKey(propertyPath); return PropertyDatabase.CreateRecordKey(propertyPath); } public PropertyDatabaseRecordKey CreateRecordKey(string documentId, Hash128 propertyHash) { if (m_PropertyDatabase.disposed) return m_PropertyDatabase.disposedView.CreateRecordKey(documentId, propertyHash); return PropertyDatabase.CreateRecordKey(documentId, propertyHash); } public PropertyDatabaseRecordKey CreateRecordKey(Hash128 propertyHash) { if (m_PropertyDatabase.disposed) return m_PropertyDatabase.disposedView.CreateRecordKey(propertyHash); return PropertyDatabase.CreateRecordKey(propertyHash); } public ulong CreateDocumentKey(string documentId) { if (m_PropertyDatabase.disposed) return m_PropertyDatabase.disposedView.CreateDocumentKey(documentId); return PropertyDatabase.CreateDocumentKey(documentId); } public Hash128 CreatePropertyHash(string propertyPath) { if (m_PropertyDatabase.disposed) return m_PropertyDatabase.disposedView.CreatePropertyHash(propertyPath); return PropertyDatabase.CreatePropertyHash(propertyPath); } public PropertyDatabaseRecordValue CreateRecordValue(object value) { if (m_PropertyDatabase.disposed) return m_PropertyDatabase.disposedView.CreateRecordValue(value); return m_PropertyDatabase.CreateRecordValue(value, m_StringTableView); } public object GetObjectFromRecordValue(in PropertyDatabaseRecordValue recordValue) { if (m_PropertyDatabase.disposed) return m_PropertyDatabase.disposedView.GetObjectFromRecordValue(recordValue); return m_PropertyDatabase.GetObjectFromRecordValue(recordValue, m_StringTableView); } public object GetObjectFromRecordValue(IPropertyDatabaseRecordValue recordValue) { if (m_PropertyDatabase.disposed) return m_PropertyDatabase.disposedView.GetObjectFromRecordValue(recordValue); return m_PropertyDatabase.GetObjectFromRecordValue(recordValue, m_StringTableView); } public TValue GetValueFromRecord<TValue>(IPropertyDatabaseRecordValue recordValue) { if (m_PropertyDatabase.disposed) return m_PropertyDatabase.disposedView.GetValueFromRecord<TValue>(recordValue); return m_PropertyDatabase.GetValueFromRecord<TValue>(recordValue, m_StringTableView); } public bool IsPersistableType(Type type) { if (m_PropertyDatabase.disposed) return m_PropertyDatabase.disposedView.IsPersistableType(type); return PropertyDatabase.IsPersistableType(type); } public bool IsSupportedPropertyType(byte propertyType) { if (m_PropertyDatabase.disposed) return m_PropertyDatabase.disposedView.IsSupportedPropertyType(propertyType); return PropertyDatabase.IsSupportedPropertyType(propertyType); } internal void MergeStores() { if (m_PropertyDatabase.disposed) { m_PropertyDatabase.disposedView.MergeStores(); return; } var newMemoryStore = new PropertyDatabaseMemoryStore(); using (m_MemoryStore.LockUpgradeableRead()) using (m_FileStore.LockUpgradeableRead()) using (var newMemoryStoreView = (PropertyDatabaseMemoryStoreView)newMemoryStore.GetView()) using (new RaceConditionDetector(m_PropertyDatabase)) { // Merge both stores newMemoryStoreView.MergeWith(m_FileStoreView, false); newMemoryStoreView.MergeWith(m_MemoryStoreView, false); // Write new memory store to file. var tempFilePath = GetTempFilePath(m_FileStore.filePath); newMemoryStoreView.SaveToFile(tempFilePath); // Swap file store with new one, and clear the invalidated documents (since the invalid records were not saved) m_FileStore.SwapFile(tempFilePath); m_FileStore.ClearInvalidatedDocuments(); // Clear the memory store after file was swapped. If you do it before, you risk // entering a state where another thread could try to read between the moment the clear is done // and the new file is written and opened. m_MemoryStoreView.Clear(); } } static string GetTempFilePath(string baseFilePath) { return $"{baseFilePath}_{Guid.NewGuid().ToString("N")}_temp"; } } struct PropertyDatabaseErrorView : IPropertyDatabaseView { string m_Message; LogType m_LogType; public PropertyDatabaseErrorView(string message, LogType type = LogType.Error) { m_Message = message; m_LogType = type; } void LogMessage() { Debug.LogFormat(m_LogType, LogOption.None, null, m_Message); } public void Dispose() {} public bool Store(string documentId, string propertyPath, object value) { LogMessage(); return false; } public bool Store(ulong documentKey, Hash128 propertyHash, object value) { LogMessage(); return false; } public bool Store(Hash128 propertyHash, object value) { LogMessage(); return false; } public bool Store(in PropertyDatabaseRecordKey recordKey, object value) { LogMessage(); return false; } public bool Store(in PropertyDatabaseRecord record) { LogMessage(); return false; } public bool TryLoad(in PropertyDatabaseRecordKey recordKey, out object data) { data = null; LogMessage(); return false; } public bool TryLoad(in PropertyDatabaseRecordKey recordKey, out PropertyDatabaseRecordValue data) { data = PropertyDatabaseRecordValue.invalid; LogMessage(); return false; } public bool TryLoad(in PropertyDatabaseRecordKey recordKey, out IPropertyDatabaseRecordValue data) { data = null; LogMessage(); return false; } public bool TryLoad(ulong documentKey, out IEnumerable<object> data) { data = null; LogMessage(); return false; } public bool TryLoad(ulong documentKey, out IEnumerable<IPropertyDatabaseRecord> records) { records = null; LogMessage(); return false; } public void Invalidate(string documentId) { LogMessage(); } public void Invalidate(ulong documentKey) { LogMessage(); } public void Invalidate(in PropertyDatabaseRecordKey recordKey) { LogMessage(); } public void InvalidateMask(ulong documentKeyMask) { LogMessage(); } public IEnumerable<IPropertyDatabaseRecord> EnumerateAll() { LogMessage(); return null; } public void Sync() { LogMessage(); } public void Clear() { LogMessage(); } public PropertyDatabaseRecord CreateRecord(string documentId, string propertyPath, object value) { LogMessage(); return PropertyDatabaseRecord.invalid; } public PropertyDatabaseRecord CreateRecord(ulong documentKey, Hash128 propertyPathHash, object value) { LogMessage(); return PropertyDatabaseRecord.invalid; } public PropertyDatabaseRecord CreateRecord(string propertyPath, object value) { LogMessage(); return PropertyDatabaseRecord.invalid; } public PropertyDatabaseRecord CreateRecord(Hash128 propertyPathHash, object value) { LogMessage(); return PropertyDatabaseRecord.invalid; } public PropertyDatabaseRecord CreateRecord(in PropertyDatabaseRecordKey recordKey, object value) { LogMessage(); return PropertyDatabaseRecord.invalid; } public PropertyDatabaseRecord CreateRecord(in PropertyDatabaseRecordKey recordKey, in PropertyDatabaseRecordValue recordValue) { return PropertyDatabase.CreateRecord(recordKey, recordValue); } public PropertyDatabaseRecordKey CreateRecordKey(string documentId, string propertyPath) { LogMessage(); return PropertyDatabase.CreateRecordKey(documentId, propertyPath); } public PropertyDatabaseRecordKey CreateRecordKey(ulong documentKey, Hash128 propertyPathHash) { LogMessage(); return PropertyDatabase.CreateRecordKey(documentKey, propertyPathHash); } public PropertyDatabaseRecordKey CreateRecordKey(string propertyPath) { LogMessage(); return PropertyDatabase.CreateRecordKey(propertyPath); } public PropertyDatabaseRecordKey CreateRecordKey(string documentId, Hash128 propertyHash) { LogMessage(); return PropertyDatabase.CreateRecordKey(documentId, propertyHash); } public PropertyDatabaseRecordKey CreateRecordKey(Hash128 propertyHash) { LogMessage(); return PropertyDatabase.CreateRecordKey(propertyHash); } public ulong CreateDocumentKey(string documentId) { LogMessage(); return PropertyDatabase.CreateDocumentKey(documentId); } public Hash128 CreatePropertyHash(string propertyPath) { LogMessage(); return PropertyDatabase.CreatePropertyHash(propertyPath); } public PropertyDatabaseRecordValue CreateRecordValue(object value) { LogMessage(); return PropertyDatabaseRecordValue.invalid; } public object GetObjectFromRecordValue(in PropertyDatabaseRecordValue recordValue) { LogMessage(); return null; } public object GetObjectFromRecordValue(IPropertyDatabaseRecordValue recordValue) { LogMessage(); return null; } public TValue GetValueFromRecord<TValue>(IPropertyDatabaseRecordValue recordValue) { LogMessage(); return default; } public bool IsPersistableType(Type type) { LogMessage(); return PropertyDatabase.IsPersistableType(type); } public bool IsSupportedPropertyType(byte propertyType) { LogMessage(); return PropertyDatabase.IsSupportedPropertyType(propertyType); } internal void MergeStores() { LogMessage(); } } }
UnityCsReference/Modules/QuickSearch/Editor/PropertyDatabase/PropertyDatabase.cs/0
{ "file_path": "UnityCsReference/Modules/QuickSearch/Editor/PropertyDatabase/PropertyDatabase.cs", "repo_id": "UnityCsReference", "token_count": 22887 }
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 System.Collections.Generic; using Unity.Profiling; using Unity.Profiling.LowLevel.Unsafe; namespace UnityEditor.Search.Providers { class ProfilerMarkersProvider : BasePerformanceProvider<ProfilerMarkersProvider.ProfilerRecorderInfo> { internal struct ProfilerRecorderCumulativeData { public long totalValue; public long totalCount; public long maxValue; public double average; public static ProfilerRecorderCumulativeData clear = new(); } internal class ProfilerRecorderInfo { public ProfilerRecorder recorder; public ProfilerRecorderDescription description; public ProfilerRecorderCumulativeData data; public long GetSampleCount() { return data.totalCount; } public long GetMaxValue() { return data.maxValue; } public long GetTotalValue() { return data.totalValue; } public double GetAverageValue() { return data.average; } public void ResetData() { data = ProfilerRecorderCumulativeData.clear; } } internal const string providerId = "profilermarkers"; const int k_SamplesCount = 5; const double k_NanoSecondsInSeconds = 1e9; const double k_KiloByte = 1024 * 1024; const double k_MegaByte = k_KiloByte * 1024; List<ProfilerRecorderInfo> m_Recorders = new(); bool m_Enabled; static readonly UnitTypeHandle k_SecondUnitTypeHandle = UnitType.GetHandle("s"); static readonly UnitTypeHandle k_ByteUnitTypeHandle = UnitType.GetHandle("b"); static readonly UnitTypeHandle k_PercentUnitTypeHandle = UnitType.GetHandle("%"); static readonly UnitTypeHandle k_HertzUnitTypeHandle = UnitType.GetHandle("hz"); [SearchItemProvider] public static SearchProvider CreateProvider() { var p = new ProfilerMarkersProvider(providerId, "Profiler Markers"); p.Initialize(); p.filterId = "profile:"; return p; } protected ProfilerMarkersProvider(string id, string displayName) : base(id, displayName) { var defaultTimeAvgLimit = GetDefaultPerformanceLimit(sampleAvgSelector); var defaultTimePeakLimit = GetDefaultPerformanceLimit(samplePeakSelector); AddPerformanceLimit(samplePeakSelector, ProfilerMarkerDataUnit.TimeNanoseconds, defaultTimePeakLimit.warningLimit, defaultTimePeakLimit.errorLimit); AddPerformanceLimit(sampleAvgSelector, ProfilerMarkerDataUnit.TimeNanoseconds, defaultTimeAvgLimit.warningLimit, defaultTimeAvgLimit.errorLimit); AddPerformanceLimit(samplePeakSelector, ProfilerMarkerDataUnit.Bytes, 100 * k_KiloByte, k_MegaByte); AddPerformanceLimit(sampleAvgSelector, ProfilerMarkerDataUnit.Bytes, 100 * k_KiloByte, k_MegaByte); AddUnitType("s", k_SecondUnitTypeHandle, UnitPowerType.One, UnitPowerType.Milli, UnitPowerType.Micro, UnitPowerType.Nano); AddUnitType("b", k_ByteUnitTypeHandle, UnitPowerType.One, UnitPowerType.Kilo, UnitPowerType.Mega, UnitPowerType.Giga, UnitPowerType.Tera, UnitPowerType.Peta); AddUnitType("%", k_PercentUnitTypeHandle, UnitPowerType.One); AddUnitType("hz", k_HertzUnitTypeHandle, UnitPowerType.One, UnitPowerType.Kilo, UnitPowerType.Mega, UnitPowerType.Giga, UnitPowerType.Tera, UnitPowerType.Peta); } public override void Initialize() { base.Initialize(); onEnable = EnableProvider; onDisable = DisableProvider; } void EnableProvider() { var availableStatHandles = new List<ProfilerRecorderHandle>(); ProfilerRecorderHandle.GetAvailable(availableStatHandles); foreach (var profilerRecorderHandle in availableStatHandles) { if (!profilerRecorderHandle.Valid) continue; var recorderInfo = new ProfilerRecorderInfo() { data = new ProfilerRecorderCumulativeData(), description = ProfilerRecorderHandle.GetDescription(profilerRecorderHandle), recorder = new ProfilerRecorder(profilerRecorderHandle, k_SamplesCount) }; recorderInfo.recorder.Start(); m_Recorders.Add(recorderInfo); } EditorApplication.update += OnUpdate; m_Enabled = true; } void DisableProvider() { m_Enabled = false; EditorApplication.update -= OnUpdate; foreach (var profilerRecorder in m_Recorders) { profilerRecorder.recorder.Stop(); profilerRecorder.recorder.Dispose(); } m_Recorders.Clear(); } void OnUpdate() { if (!m_Enabled) return; foreach (var profilerRecorder in m_Recorders) { profilerRecorder.data = UpdateRecorderData(profilerRecorder.recorder, profilerRecorder.data); } } static ProfilerRecorderCumulativeData UpdateRecorderData(ProfilerRecorder recorder, ProfilerRecorderCumulativeData data) { var samplesCount = recorder.Capacity; if (samplesCount != k_SamplesCount) return data; if (recorder.Count == 0) return data; unsafe { var samples = stackalloc ProfilerRecorderSample[samplesCount]; recorder.CopyTo(samples, samplesCount); var lastSampleIndex = recorder.Count - 1; var lastSample = samples[lastSampleIndex]; if (lastSample is { Value: >= 0, Count: > 0 }) { data.totalValue = AddWithoutOverflow(data.totalValue, lastSample.Value); data.maxValue = Math.Max(data.maxValue, lastSample.Value); data.totalCount = AddWithoutOverflow(data.totalCount, lastSample.Count); } // Compute average over samples double totalValue = 0; double totalCount = 0; for (var i = 0; i < samplesCount; ++i) { var sampleValue = samples[i].Value; var sampleCount = samples[i].Count; if (sampleValue < 0 || sampleCount <= 0) continue; totalValue += sampleValue; totalCount += sampleCount; } if (totalCount > 0) { data.average = totalValue / totalCount; } } return data; } static long AddWithoutOverflow(long a, long b) { if (b > long.MaxValue - a) return long.MaxValue; return a + b; } static ProfilerRecorderInfo GetRecorderInfo(SearchItem item) { return (ProfilerRecorderInfo)item.data; } protected override string FormatColumnValue(SearchColumnEventArgs args) { if (!m_Enabled) return string.Empty; if (args.value == null) return string.Empty; var valueWithUnit = (ValueWithUnit)args.value; if (args.column.selector == sampleCountSelector) return valueWithUnit.value.ToString("F0"); var pri = GetRecorderInfo(args.item); if (!pri.recorder.Valid) return string.Empty; return FormatUnit(valueWithUnit.value, args.column.selector, pri.recorder.UnitType); } static double ConvertLongWithMaxValue(long value) { if (value == long.MaxValue) return double.PositiveInfinity; return value; } protected override void ResetItems(SearchItem[] items) { foreach (var item in items) GetRecorderInfo(item).ResetData(); } static ValueWithUnit GetSampleCount(SearchItem item) { var pri = GetRecorderInfo(item); return ProfilerRecorderInfoToUnitWithValue(pri, pri.GetSampleCount()); } static ValueWithUnit GetMaxValue(SearchItem item) { var pri = GetRecorderInfo(item); return ProfilerRecorderInfoToUnitWithValue(pri, pri.GetMaxValue()); } static ValueWithUnit GetTotalValue(SearchItem item) { var pri = GetRecorderInfo(item); return ProfilerRecorderInfoToUnitWithValue(pri, ConvertLongWithMaxValue(pri.GetTotalValue())); } static ValueWithUnit GetAverageValue(SearchItem item) { var pri = GetRecorderInfo(item); return ProfilerRecorderInfoToUnitWithValue(pri, pri.GetAverageValue()); } [SearchSelector(sampleCountSelector, provider: providerId, cacheable = false)] static object SelectCount(SearchSelectorArgs args) => GetSampleCount(args.current); [SearchSelector(samplePeakSelector, provider: providerId, cacheable = false)] static object SelectPeak(SearchSelectorArgs args) => GetMaxValue(args.current); [SearchSelector(sampleAvgSelector, provider: providerId, cacheable = false)] static object SelectAvg(SearchSelectorArgs args) => GetAverageValue(args.current); [SearchSelector(sampleTotalSelector, provider: providerId, cacheable = false)] static object SelectTotal(SearchSelectorArgs args) => GetTotalValue(args.current); protected override string FetchDescription(SearchItem item, SearchContext context) { var fullDescription = item.options.HasAny(SearchItemOptions.FullDescription); var description = GetTrackerDescription(item, fullDescription ? '\n' : ' '); if (item.options.HasAny(SearchItemOptions.Compacted)) return $"<b>{item.id}</b> {description}"; return description; } string GetTrackerDescription(SearchItem item, char splitter) { if (!m_Enabled) return string.Empty; var pri = GetRecorderInfo(item); var sampleCount = pri.GetSampleCount(); var peak = pri.GetMaxValue(); var avg = pri.GetAverageValue(); var total = pri.GetTotalValue(); var unitType = pri.recorder.UnitType; return $"Sample Count: <b>{sampleCount}</b>{splitter}" + $"Peak: {FormatUnit(peak, samplePeakSelector, unitType)}{splitter}" + $"Avg: {FormatUnit(avg, sampleAvgSelector, unitType)}{splitter}" + $"Total: {FormatUnit(total, sampleTotalSelector, unitType)}{splitter}" + $"Category: {pri.description.Category}{splitter}" + $"Unit Type: {pri.description.UnitType}{splitter}" + $"Data Type: {pri.description.DataType}"; } string FormatUnit(double value, string selector, ProfilerMarkerDataUnit unit) { var performanceLimitKey = GetPerformanceLimitKey(selector, unit); var performanceLimit = GetPerformanceLimit(performanceLimitKey); switch (unit) { case ProfilerMarkerDataUnit.Undefined: return FormatUndefined(value, performanceLimit); case ProfilerMarkerDataUnit.TimeNanoseconds: return FormatTime(value, performanceLimit); case ProfilerMarkerDataUnit.Bytes: return FormatByte(value, performanceLimit); case ProfilerMarkerDataUnit.Count: return FormatCount(value, performanceLimit); case ProfilerMarkerDataUnit.Percent: if (selector == sampleTotalSelector) return string.Empty; return FormatPercent(value, performanceLimit); case ProfilerMarkerDataUnit.FrequencyHz: if (selector == sampleTotalSelector) return string.Empty; return FormatFrequency(value, performanceLimit); default: throw new ArgumentOutOfRangeException(nameof(unit), unit, null); } } static string FormatUndefined(double value, in PerformanceLimit performanceLimit) { return GetPerformanceLimitLabel(value, performanceLimit, d => $"{d}"); } static string FormatCount(double value, in PerformanceLimit performanceLimit) { return GetPerformanceLimitLabel(value, performanceLimit, d => $"{Utils.FormatCount((ulong)d)} hit(s)"); } static string FormatTime(double value, in PerformanceLimit performanceLimit) { // GetTimeLabel expects time in seconds return GetTimeLabel(value / k_NanoSecondsInSeconds, performanceLimit); } static string FormatByte(double value, in PerformanceLimit performanceLimit) { return GetPerformanceLimitLabel(value, performanceLimit, d => $"{Utils.FormatBytes((long)d)}"); } static string FormatPercent(double value, in PerformanceLimit performanceLimit) { return GetPerformanceLimitLabel(value, performanceLimit, d => $"{d}%"); } static string FormatFrequency(double value, in PerformanceLimit performanceLimit) { return GetPerformanceLimitLabel(value, performanceLimit, d => $"{Utils.FormatCount((ulong)d)}Hz"); } protected override IEnumerable<string> YieldPerformanceDataWords(ProfilerRecorderInfo pri) { yield return pri.description.Name; yield return pri.description.Category.Name; } protected override ValueWithUnit GetPerformanceAverageValue(ProfilerRecorderInfo pri) => ProfilerRecorderInfoToUnitWithValue(pri, pri.GetAverageValue()); protected override ValueWithUnit GetPerformanceTotalValue(ProfilerRecorderInfo pri) => ProfilerRecorderInfoToUnitWithValue(pri, pri.GetTotalValue()); protected override ValueWithUnit GetPerformancePeakValue(ProfilerRecorderInfo pri) => ProfilerRecorderInfoToUnitWithValue(pri, pri.GetMaxValue()); protected override ValueWithUnit GetPerformanceSampleCountValue(ProfilerRecorderInfo pri) => ProfilerRecorderInfoToUnitWithValue(pri, pri.GetSampleCount()); static ValueWithUnit ProfilerRecorderInfoToUnitWithValue(ProfilerRecorderInfo pri, double value) { switch (pri.description.UnitType) { case ProfilerMarkerDataUnit.Undefined: return new ValueWithUnit(value, k_UnitlessTypeHandle, UnitPowerType.One); case ProfilerMarkerDataUnit.TimeNanoseconds: return new ValueWithUnit(value, k_SecondUnitTypeHandle, UnitPowerType.Nano); case ProfilerMarkerDataUnit.Bytes: return new ValueWithUnit(value, k_ByteUnitTypeHandle, UnitPowerType.One); case ProfilerMarkerDataUnit.Count: return new ValueWithUnit(value, k_UnitlessTypeHandle, UnitPowerType.One); case ProfilerMarkerDataUnit.Percent: return new ValueWithUnit(value, k_PercentUnitTypeHandle, UnitPowerType.One); case ProfilerMarkerDataUnit.FrequencyHz: return new ValueWithUnit(value, k_HertzUnitTypeHandle, UnitPowerType.One); default: throw new ArgumentOutOfRangeException(); } } protected override IEnumerable<SearchItem> FetchItem(SearchContext context, SearchProvider provider) { var query = m_QueryEngine.ParseQuery(context.searchQuery); if (!query.valid) yield break; foreach (var trackerName in query.Apply(m_Recorders)) yield return CreateItem(context, provider, trackerName); } static SearchItem CreateItem(in SearchContext context, in SearchProvider provider, in ProfilerRecorderInfo pri) { var markerName = pri.description.Name; var item = provider.CreateItem(context, markerName, markerName, null, null, pri); item.options = SearchItemOptions.AlwaysRefresh; return item; } static int GetPerformanceLimitKey(string selector, ProfilerMarkerDataUnit unit) { return HashCode.Combine(selector, unit); } void AddPerformanceLimit(string selector, ProfilerMarkerDataUnit unit, double warningLimit, double errorLimit) { AddPerformanceLimit(GetPerformanceLimitKey(selector, unit), warningLimit, errorLimit); } } }
UnityCsReference/Modules/QuickSearch/Editor/Providers/ProfilerMarkersProvider.cs/0
{ "file_path": "UnityCsReference/Modules/QuickSearch/Editor/Providers/ProfilerMarkersProvider.cs", "repo_id": "UnityCsReference", "token_count": 7652 }
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; namespace UnityEditor.Search { public interface IQuerySource { ISearchView searchView { get; } SearchContext context { get; } internal QueryBlock AddBlock(string text); internal QueryBlock AddBlock(QueryBlock block); internal QueryBlock AddProposition(in SearchProposition searchProposition); internal void RemoveBlock(in QueryBlock block); internal void BlockActivated(in QueryBlock block); internal IEnumerable<QueryBlock> EnumerateBlocks(); internal bool SwapBlock(QueryBlock bl, QueryBlock br); void Apply(); void Repaint(); } }
UnityCsReference/Modules/QuickSearch/Editor/QueryBuilder/IQuerySource.cs/0
{ "file_path": "UnityCsReference/Modules/QuickSearch/Editor/QueryBuilder/IQuerySource.cs", "repo_id": "UnityCsReference", "token_count": 277 }
439
// 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.Search { [Obsolete("Query has been deprecated. Use ParsedQuery instead (UnityUpgradable) -> ParsedQuery<TData, TPayload>", false)] public class Query<TData, TPayload> where TPayload : class { /// <summary> /// The text that generated this query. /// </summary> public string text { get; } /// <summary> Indicates if the query is valid or not. </summary> public bool valid => errors.Count == 0 && evaluationGraph != null; /// <summary> List of QueryErrors. </summary> public ICollection<QueryError> errors { get; } /// <summary> /// List of tokens found in the query. /// </summary> public ICollection<string> tokens { get; } internal ICollection<QueryToggle> toggles { get; } internal IQueryHandler<TData, TPayload> graphHandler { get; set; } public QueryGraph evaluationGraph { get; } public QueryGraph queryGraph { get; } internal Query(string text, QueryGraph evaluationGraph, QueryGraph queryGraph, ICollection<QueryError> errors, ICollection<string> tokens, ICollection<QueryToggle> toggles) { this.text = text; this.evaluationGraph = evaluationGraph; this.queryGraph = queryGraph; this.errors = errors; this.tokens = tokens; this.toggles = toggles; } internal Query(string text, QueryGraph evaluationGraph, QueryGraph queryGraph, ICollection<QueryError> errors, ICollection<string> tokens, ICollection<QueryToggle> toggles, IQueryHandler<TData, TPayload> graphHandler) : this(text, evaluationGraph, queryGraph, errors, tokens, toggles) { if (valid) { this.graphHandler = graphHandler; } } /// <summary> /// Apply the filtering on a payload. /// </summary> /// <param name="payload">The data to filter</param> /// <returns>A filtered IEnumerable.</returns> public virtual IEnumerable<TData> Apply(TPayload payload = null) { if (!valid) return null; return graphHandler.Eval(payload); } /// <summary> /// Optimize the query by optimizing the underlying filtering graph. /// </summary> /// <param name="propagateNotToLeaves">Propagate "Not" operations to leaves, so only leaves can have "Not" operations as parents.</param> /// <param name="swapNotToRightHandSide">Swaps "Not" operations to the right hand side of combining operations (i.e. "And", "Or"). Useful if a "Not" operation is slow.</param> public void Optimize(bool propagateNotToLeaves, bool swapNotToRightHandSide) { evaluationGraph?.Optimize(propagateNotToLeaves, swapNotToRightHandSide); } /// <summary> /// Optimize the query by optimizing the underlying filtering graph. /// </summary> /// <param name="options">Optimization options.</param> public void Optimize(QueryGraphOptimizationOptions options) { evaluationGraph?.Optimize(options); } /// <summary> /// Get the query node located at the specified position in the query. /// </summary> /// <param name="position">The position of the query node in the text.</param> /// <returns>An IQueryNode.</returns> public IQueryNode GetNodeAtPosition(int position) { // Allow position at Length, to support cursor at end of word. if (position < 0 || position > text.Length) throw new ArgumentOutOfRangeException(nameof(position)); if (queryGraph == null || queryGraph.empty) return null; return GetNodeAtPosition(queryGraph.root, position); } internal bool HasToggle(string toggle) { return HasToggle(toggle, StringComparison.Ordinal); } internal bool HasToggle(string toggle, StringComparison stringComparison) { return toggles.Any(s => s.value.Equals(toggle, stringComparison)); } static IQueryNode GetNodeAtPosition(IQueryNode root, int position) { if (root.type == QueryNodeType.Where || root.type == QueryNodeType.Group) return GetNodeAtPosition(root.children[0], position); if (!string.IsNullOrEmpty(root.token.text) && position >= root.token.position && position <= root.token.position + root.token.length) return root; if (root.leaf || root.children == null) return null; if (root.children.Count == 1) return GetNodeAtPosition(root.children[0], position); // We have no more than two children return GetNodeAtPosition(position < root.token.position ? root.children[0] : root.children[1], position); } } [Obsolete("Query has been deprecated. Use ParsedQuery instead (UnityUpgradable) -> ParsedQuery<T>", false)] public class Query<T> : Query<T, IEnumerable<T>> { /// <summary> /// Boolean indicating if the original payload should be return when the query is empty. /// If set to false, an empty array is returned instead. /// </summary> public bool returnPayloadIfEmpty { get; set; } = true; internal Query(string text, QueryGraph evaluationGraph, QueryGraph queryGraph, ICollection<QueryError> errors, ICollection<string> tokens, ICollection<QueryToggle> toggles, IQueryHandler<T, IEnumerable<T>> graphHandler) : base(text, evaluationGraph, queryGraph, errors, tokens, toggles, graphHandler) {} /// <summary> /// Apply the filtering on an IEnumerable data set. /// </summary> /// <param name="data">The data to filter</param> /// <returns>A filtered IEnumerable.</returns> public override IEnumerable<T> Apply(IEnumerable<T> data) { return Apply(data, returnPayloadIfEmpty); } internal IEnumerable<T> Apply(IEnumerable<T> data, bool returnInputIfEmpty) { if (!valid) return new T[] {}; if (evaluationGraph.empty) { return returnInputIfEmpty ? data : new T[] {}; } return graphHandler.Eval(data); } /// <summary> /// Test the query on a single object. Returns true if the test passes. /// </summary> /// <param name="element">A single object to be tested.</param> /// <returns>True if the object passes the query, false otherwise.</returns> public bool Test(T element) { if (!valid) return false; if (evaluationGraph.empty) { return returnPayloadIfEmpty; } return graphHandler.Eval(element); } } }
UnityCsReference/Modules/QuickSearch/Editor/QueryEngine/Query.Deprecated.cs/0
{ "file_path": "UnityCsReference/Modules/QuickSearch/Editor/QueryEngine/Query.Deprecated.cs", "repo_id": "UnityCsReference", "token_count": 2946 }
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; using System.Linq; using System.Collections.Generic; using System.Diagnostics; using UnityEngine; namespace UnityEditor.Search { /// <summary> /// Define an action that can be applied on SearchItem of a specific provider type. /// </summary> [DebuggerDisplay("{displayName} - {id}")] public class SearchAction { /// <summary> /// Default constructor to build a search action. /// </summary> /// <param name="providerId">Provider Id that supports this action.</param> /// <param name="id">Action unique id.</param> /// <param name="content">Display information when displaying the action in the Action Menu</param> public SearchAction(string providerId, string id, GUIContent content) { this.providerId = providerId; this.id = id; this.content = content; handler = null; execute = null; enabled = (a) => true; } /// <summary> /// Default constructor to build a search action. /// </summary> /// <param name="providerId">Provider Id that supports this action.</param> /// <param name="id">Action unique id.</param> /// <param name="content">Display information when displaying the action in the Action Menu</param> /// <param name="handler">Handler that will execute the action.</param> public SearchAction(string providerId, string id, GUIContent content, Action<SearchItem[]> handler) : this(providerId, id, content) { execute = handler; } /// <summary> /// Default constructor to build a search action. /// </summary> /// <param name="providerId">Provider Id that supports this action.</param> /// <param name="id">Action unique id.</param> /// <param name="content">Display information when displaying the action in the Action Menu</param> /// <param name="handler">Handler that will execute the action.</param> public SearchAction(string providerId, string id, GUIContent content, Action<SearchItem> handler) : this(providerId, id, content) { this.handler = handler; } /// <summary> /// Extended constructor to build a search action. /// </summary> /// <param name="providerId">Provider Id that supports this action.</param> /// <param name="name">Label name when displaying the action in the Action Menu</param> /// <param name="icon">Icon when displaying the action in the Action Menu</param> /// <param name="tooltip">Tooltip assocoated with the when displayed in the Action Menu</param> /// <param name="handler">Handler that will execute the action.</param> public SearchAction(string providerId, string name, Texture2D icon, string tooltip, Action<SearchItem[]> handler) : this(providerId, name, new GUIContent(SearchUtils.ToPascalWithSpaces(name), icon, tooltip ?? name), handler) { } /// <summary> /// Extended constructor to build a search action. /// </summary> /// <param name="providerId">Provider Id that supports this action.</param> /// <param name="name">Label name when displaying the action in the Action Menu</param> /// <param name="icon">Icon when displaying the action in the Action Menu</param> /// <param name="tooltip">Tooltip assocoated with the when displayed in the Action Menu</param> /// <param name="handler">Handler that will execute the action.</param> public SearchAction(string providerId, string name, Texture2D icon, string tooltip, Action<SearchItem> handler) : this(providerId, name, new GUIContent(SearchUtils.ToPascalWithSpaces(name), icon, tooltip ?? name), handler) { } internal SearchAction(string providerId, string name, Texture2D icon, string tooltip, Action<SearchItem> handler, Func<IReadOnlyCollection<SearchItem>, bool> enabledHandler) : this(providerId, name, icon, tooltip, handler) { enabled = enabledHandler; } internal SearchAction(string name, string label, Action<SearchItem> execute) : this(name, label, execute, null) { } internal SearchAction(string name, string label, Action<SearchItem[]> execute) : this(name, label, null, null, execute) { } internal SearchAction(string name, string label, Action<SearchItem> execute, Func<SearchItem, bool> enabled) : this(string.Empty, name, new GUIContent(label)) { handler = execute; if (enabled != null) this.enabled = (items) => items.All(e => enabled(e)); } /// <summary> /// Extended constructor to build a search action. /// </summary> /// <param name="providerId">Provider Id that supports this action.</param> /// <param name="name">Label name when displaying the action in the Action Menu</param> /// <param name="icon">Icon when displaying the action in the Action Menu</param> /// <param name="tooltip">Tooltip associated with the when displayed in the Action Menu</param> public SearchAction(string providerId, string name, Texture2D icon = null, string tooltip = null) : this(providerId, name, new GUIContent(SearchUtils.ToPascalWithSpaces(name), icon, tooltip ?? name)) { } /// <summary> /// Action unique identifier. /// </summary> public string id { get; private set; } /// <summary> /// Name used to display /// </summary> public string displayName => content.tooltip; /// <summary> /// Indicates if the search view should be closed after the action execution. /// </summary> public bool closeWindowAfterExecution = true; /// <summary> /// Unique (for a given provider) id of the action /// </summary> internal string providerId; /// <summary> /// GUI content used to display the action in the search view. /// </summary> public GUIContent content; /// <summary> /// Callback used to check if the action is enabled based on the current context. /// </summary> public Func<IReadOnlyCollection<SearchItem>, bool> enabled; /// <summary> /// Execute a action on a set of items. /// </summary> public Action<SearchItem[]> execute; /// <summary> /// This handler is used for action that do not support multi selection. /// </summary> public Action<SearchItem> handler; } }
UnityCsReference/Modules/QuickSearch/Editor/SearchAction.cs/0
{ "file_path": "UnityCsReference/Modules/QuickSearch/Editor/SearchAction.cs", "repo_id": "UnityCsReference", "token_count": 2574 }
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.Linq; using System.Collections.Generic; using System.ComponentModel; namespace UnityEditor.Search { static partial class Evaluators { // intersect{...sets[, @intersectBy]} [Description("Produces the set intersection of two sequences."), Category("Set Manipulation")] [SearchExpressionEvaluator(SearchExpressionEvaluationHints.DoNotValidateSignature/*SearchExpressionType.Iterable | SearchExpressionType.Variadic, SearchExpressionType.Selector | SearchExpressionType.Optional*/)] public static IEnumerable<SearchItem> Intersect(SearchExpressionContext c) { if (c.args.Length < 2) c.ThrowError("Invalid arguments"); var setExpr = c.args[0]; if (!setExpr.types.IsIterable()) c.ThrowError("Primary set is not iterable", setExpr.outerText); string selector = null; if (c.args[c.args.Length - 1].types.HasFlag(SearchExpressionType.Selector)) selector = c.args[c.args.Length - 1].innerText.ToString(); var set = new HashSet<SearchItem>(new ItemComparer(selector)); foreach (var r in setExpr.Execute(c)) { if (r == null || !set.Add(r)) yield return null; } // Remove from primary set all items from subsequent sets that do not intersect foreach (var e in c.args.Skip(1)) { if (e != null && !e.types.HasFlag(SearchExpressionType.Selector)) { var intersectWith = new HashSet<SearchItem>(); foreach (var r in e.Execute(c)) { if (r == null || !intersectWith.Add(r)) yield return null; } set.IntersectWith(intersectWith); } else yield return null; } foreach (var r in set) yield return r; } readonly struct ItemComparer : IEqualityComparer<SearchItem> { public readonly string selector; public ItemComparer(string selector) => this.selector = selector; public bool Equals(SearchItem x, SearchItem y) => DefaultComparer(GetValueToCompare(x), GetValueToCompare(y)) == 0; public int GetHashCode(SearchItem obj) => GetValueToCompare(obj).GetHashCode(); public object GetValueToCompare(SearchItem obj) { var value = obj.GetValue(selector); if (value != null) return value; return obj.id; } } } }
UnityCsReference/Modules/QuickSearch/Editor/SearchExpression/Evaluators/IntersectEvaluator.cs/0
{ "file_path": "UnityCsReference/Modules/QuickSearch/Editor/SearchExpression/Evaluators/IntersectEvaluator.cs", "repo_id": "UnityCsReference", "token_count": 1362 }
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.Linq; namespace UnityEditor.Search { static partial class Parsers { static readonly SearchExpressionEvaluator SetEvaluator = EvaluatorManager.GetConstantEvaluatorByName("set"); [SearchExpressionParser("fixedset", BuiltinParserPriority.Set)] internal static SearchExpression FixedSetParser(SearchExpressionParserArgs args) { var outerText = args.text; var text = ParserUtils.SimplifyExpression(outerText); if (text.length < 2 || text[0] != '[' || text[text.length - 1] != ']') return null; var expressions = ParserUtils.GetExpressionsStartAndLength(text, out _, out _); if (expressions.Length != 1 || expressions[0].startIndex != text.startIndex || expressions[0].length != text.length) return null; var parameters = ParserUtils.ExtractArguments(text) .Select(paramText => ParserManager.Parse(args.With(paramText).With(SearchExpressionParserFlags.ImplicitLiterals))) .ToArray(); var innerText = ParserUtils.SimplifyExpression(text.Substring(1, text.length - 2)); return new SearchExpression(SearchExpressionType.Set, outerText, innerText, SetEvaluator, parameters); } [SearchExpressionParser("set", BuiltinParserPriority.Set)] internal static SearchExpression ExpressionSetParser(SearchExpressionParserArgs args) { var outerText = args.text; if (outerText.length < 2) return null; var innerText = ParserUtils.SimplifyExpression(outerText, false); if (outerText.length == innerText.length) return null; var text = outerText.Substring(innerText.startIndex - outerText.startIndex - 1, innerText.length + 2); if (text[0] != '{' || text[text.length - 1] != '}') return null; var expressions = ParserUtils.GetExpressionsStartAndLength(innerText, out var rootHasParameters, out _); if (!rootHasParameters) return null; var parameters = ParserUtils.ExtractArguments(text) .Select(paramText => ParserManager.Parse(args.With(paramText).Without(SearchExpressionParserFlags.ImplicitLiterals))) .ToArray(); return new SearchExpression(SearchExpressionType.Set, outerText, innerText.Trim(), SetEvaluator, parameters); } } }
UnityCsReference/Modules/QuickSearch/Editor/SearchExpression/Parsers/SetExpressionParser.cs/0
{ "file_path": "UnityCsReference/Modules/QuickSearch/Editor/SearchExpression/Parsers/SetExpressionParser.cs", "repo_id": "UnityCsReference", "token_count": 1082 }
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.Concurrent; using System.Collections.Generic; using System.Linq; using UnityEditorInternal; using UnityEngine; namespace UnityEditor.Search { delegate SearchPreview FetchPreviewCallback(SearchItem item, SearchContext context, FetchPreviewOptions options, Vector2 size); delegate void AsyncFetchPreviewCallback(SearchItem item, SearchContext context, FetchPreviewOptions options, Vector2 size, OnPreviewReady onReadyCallback); delegate void OnPreviewReady(SearchItem item, SearchContext context, SearchPreview preview); readonly struct SearchPreviewKey : IComparable<SearchPreviewKey>, IEquatable<SearchPreviewKey> { public readonly int searchItemHashCode; public readonly FetchPreviewOptions options; public readonly Vector2 size; public SearchPreviewKey(int searchItemHashCode, FetchPreviewOptions options, in Vector2 size) { this.searchItemHashCode = searchItemHashCode; this.options = options; this.size = size; } public SearchPreviewKey(SearchItem item, FetchPreviewOptions options, in Vector2 size) : this(item.GetHashCode(), options, size) {} public int CompareTo(SearchPreviewKey other) { var compare = searchItemHashCode.CompareTo(other.searchItemHashCode); if (compare != 0) return compare; compare = options.CompareTo(other.options); if (compare != 0) return compare; return size.sqrMagnitude.CompareTo(other.size.sqrMagnitude); } public bool Equals(SearchPreviewKey other) { return searchItemHashCode == other.searchItemHashCode && options == other.options && size == other.size; } public override int GetHashCode() { return HashCode.Combine(searchItemHashCode, options, size); } } readonly struct SearchPreview { public readonly SearchPreviewKey key; public readonly Texture2D texture; public readonly DateTime creationTime; public bool valid => texture != null && texture; public static SearchPreview invalid = new(new SearchPreviewKey(0, FetchPreviewOptions.None, Vector2.zero), null); public SearchPreview(in SearchPreviewKey key, Texture2D texture) : this(key, texture, DateTime.UtcNow) {} public SearchPreview(in SearchPreviewKey key, Texture2D texture, in DateTime creationTime) { this.key = key; this.texture = texture; this.creationTime = creationTime; } public SearchPreview(SearchItem item, FetchPreviewOptions options, in Vector2 size, Texture2D texture) : this(new SearchPreviewKey(item, options, size), texture, DateTime.UtcNow) {} public SearchPreview(SearchItem item, FetchPreviewOptions options, in Vector2 size, Texture2D texture, in DateTime creationTime) : this(new SearchPreviewKey(item, options, size), texture, creationTime) {} } class SearchPreviewAsyncFetch { public readonly Action asyncCallbackOff; public readonly ConcurrentBag<OnPreviewReady> readyCallbacks; public SearchPreviewAsyncFetch(Action off) { this.readyCallbacks = new ConcurrentBag<OnPreviewReady>(); this.asyncCallbackOff = off; } } class SearchPreviewManager { ConcurrentDictionary<SearchPreviewKey, SearchPreview> m_PreviewCollections = new(); ConcurrentDictionary<SearchPreviewKey, SearchPreviewAsyncFetch> m_FetchPreviewOffs = new(); public int poolSize { get; set; } public int count => m_PreviewCollections.Count; public SearchPreviewManager(int poolSize) { this.poolSize = poolSize; } public SearchPreviewManager() { poolSize = 50; } public Action FetchPreview(SearchItem item, SearchContext context, FetchPreviewOptions options, in Vector2 size, FetchPreviewCallback fetchCallback, OnPreviewReady readyCallback, double delayInSeconds = 0.2d) { return FetchPreview(item, context, new SearchPreviewKey(item, options, size), fetchCallback, readyCallback, delayInSeconds); } public Action FetchPreview(SearchItem item, SearchContext context, FetchPreviewOptions options, in Vector2 size, AsyncFetchPreviewCallback fetchCallback, OnPreviewReady readyCallback, double delayInSeconds = 0.2d) { return FetchPreview(item, context, new SearchPreviewKey(item, options, size), fetchCallback, readyCallback, delayInSeconds); } public Action FetchPreview(SearchItem item, SearchContext context, in SearchPreviewKey key, FetchPreviewCallback fetchCallback, OnPreviewReady readyCallback, double delayInSeconds = 0.2d) { return FetchPreview(item, context, key, (searchItem, searchContext, options, size, callback) => { var searchPreview = fetchCallback(searchItem, searchContext, options, size); callback(searchItem, searchContext, searchPreview); }, readyCallback, delayInSeconds); } public Action FetchPreview(SearchItem item, SearchContext context, in SearchPreviewKey key, AsyncFetchPreviewCallback fetchCallback, OnPreviewReady readyCallback, double delayInSeconds = 0.2d) { if (m_PreviewCollections.TryGetValue(key, out var searchPreview) && searchPreview.valid) { readyCallback?.Invoke(item, context, searchPreview); return () => { }; } return FetchPreviewAsync(item, context, key, fetchCallback, readyCallback, delayInSeconds); } public SearchPreview FetchPreview(SearchItem item, FetchPreviewOptions options, in Vector2 size) { return FetchPreview(new SearchPreviewKey(item, options, size)); } public SearchPreview FetchPreview(in SearchPreviewKey key) { if (!m_PreviewCollections.TryGetValue(key, out var searchPreview)) return SearchPreview.invalid; if (!searchPreview.valid) return SearchPreview.invalid; return searchPreview; } public void CancelFetch(SearchItem item, FetchPreviewOptions options, in Vector2 size) { CancelFetch(new SearchPreviewKey(item, options, size)); } public void CancelFetch(in SearchPreviewKey key) { if (!m_FetchPreviewOffs.TryRemove(key, out var previewAsyncFetch)) return; previewAsyncFetch.asyncCallbackOff?.Invoke(); previewAsyncFetch.readyCallbacks.Clear(); } public void ReleasePreview(SearchItem item, FetchPreviewOptions options, in Vector2 size) { ReleasePreview(new SearchPreviewKey(item, options, size)); } public void ReleasePreview(in SearchPreviewKey key) { m_PreviewCollections.TryRemove(key, out _); CancelFetch(key); } public void ReleaseOldPreviews(TimeSpan elapsedTime) { var now = DateTime.UtcNow; var oldPreviews = m_PreviewCollections.Where(pair => { var lifeTime = now - pair.Value.creationTime; return lifeTime > elapsedTime; }).Select(pair => pair.Key).ToArray(); foreach (var oldPreviewKey in oldPreviews) { ReleasePreview(oldPreviewKey); } } public bool HasPreview(SearchItem item, FetchPreviewOptions options, in Vector2 size) { return m_PreviewCollections.TryGetValue(new SearchPreviewKey(item, options, size), out _); } public bool HasPreview(in SearchPreviewKey key) { return m_PreviewCollections.TryGetValue(key, out _); } internal bool IsAnyPreviewRequestedForItem(SearchItem item) { var itemHash = item.GetHashCode(); foreach (var k in m_FetchPreviewOffs.Keys) if (k.searchItemHashCode == itemHash) return true; return false; } internal bool IsAnyPreviewLoadedForItem(SearchItem item) { var itemHash = item.GetHashCode(); foreach (var k in m_PreviewCollections.Keys) if (k.searchItemHashCode == itemHash) return true; return false; } public void Clear() { m_PreviewCollections.Clear(); // Not really atomic var asyncFetchOffs = m_FetchPreviewOffs.ToArray(); m_FetchPreviewOffs.Clear(); foreach (var kvp in asyncFetchOffs) { kvp.Value.asyncCallbackOff(); } } Action FetchPreviewAsync(SearchItem item, SearchContext context, in SearchPreviewKey key, AsyncFetchPreviewCallback fetchCallback, OnPreviewReady readyCallback, double delayInSeconds) { SearchPreviewAsyncFetch created = null; var localKey = key; var asyncFetch = m_FetchPreviewOffs.GetOrAdd(key, previewKey => { // I don't think we will often be in a situation where we try to fetch multiple previews for the same key // therefore I think this is fine. var asyncCallbackOff = Utils.CallDelayed(() => OnAsyncFetch(item, context, localKey, fetchCallback), delayInSeconds); created = new SearchPreviewAsyncFetch(asyncCallbackOff); return created; }); if (created != null && !ReferenceEquals(created, asyncFetch)) created.asyncCallbackOff(); asyncFetch.readyCallbacks.Add(readyCallback); return asyncFetch.asyncCallbackOff; } void OnAsyncFetch(SearchItem item, SearchContext context, in SearchPreviewKey key, AsyncFetchPreviewCallback fetchCallback) { // If we were already canceled, return if (!m_FetchPreviewOffs.ContainsKey(key)) return; var localKey = key; fetchCallback(item, context, key.options, key.size, (searchItem, searchContext, preview) => OnAsyncFetchDone(searchItem, searchContext, preview, localKey)); } void OnAsyncFetchDone(SearchItem item, SearchContext context, in SearchPreview searchPreview, in SearchPreviewKey originalKey) { if (searchPreview.valid) AddSearchPreview(searchPreview); // Might have been canceled and removed already if (!m_FetchPreviewOffs.Remove(originalKey, out var asyncFetch)) return; if (InternalEditorUtility.CurrentThreadIsMainThread()) { DispatchFetchPreviewResult(asyncFetch.readyCallbacks, item, context, searchPreview); } else { var localPreview = searchPreview; Dispatcher.Enqueue(() => { DispatchFetchPreviewResult(asyncFetch.readyCallbacks, item, context, localPreview); }); } } static void DispatchFetchPreviewResult(ConcurrentBag<OnPreviewReady> readyCallbacks, SearchItem item, SearchContext context, in SearchPreview preview) { while (readyCallbacks.TryTake(out var readyCallback)) { readyCallback?.Invoke(item, context, preview); } } void AddSearchPreview(in SearchPreview searchPreview) { // This block is not atomic. There is a chance that we add multiple previews and check the size at the same time. // This means that we might end up removing more than we needed. // Also, this doesn't protect against releases that might happen at the same time, once again leading to more // previews being removed than necessary. // But there is a guarantee that we will never have more than poolsize item. var localPreview = searchPreview; m_PreviewCollections.AddOrUpdate(searchPreview.key, localPreview, (_, _) => localPreview); while (m_PreviewCollections.Count > poolSize) { var oldestKey = FindOldestPreview(); if (m_PreviewCollections.TryRemove(oldestKey, out _)) return; // Since Count and TryRemove already spins for access, we don't need to spin before retrying. } } SearchPreviewKey FindOldestPreview() { SearchPreviewKey oldestKey = new(); var oldestLifeTime = new TimeSpan(0); var now = DateTime.UtcNow; foreach (var (key, preview) in m_PreviewCollections) { var previewLifeTime = now - preview.creationTime; if (previewLifeTime > oldestLifeTime) { oldestKey = key; oldestLifeTime = previewLifeTime; } } return oldestKey; } } }
UnityCsReference/Modules/QuickSearch/Editor/SearchPreviewManager.cs/0
{ "file_path": "UnityCsReference/Modules/QuickSearch/Editor/SearchPreviewManager.cs", "repo_id": "UnityCsReference", "token_count": 5635 }
444
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System.Collections.Generic; using System.Linq; using UnityEditor.Search.Providers; using UnityEngine; using UnityEngine.UIElements; namespace UnityEditor.Search { class SceneSelectors { const string providerId = "scene"; [SearchSelector("type", provider: providerId, priority: 99)] static object GetSceneObjectType(SearchSelectorArgs args) { var go = args.current.ToObject<GameObject>(); if (!go) return null; var components = go.GetComponents<Component>(); if (components.Length == 0) return go.GetType().Name; else if (components.Length == 1) return components[0]?.GetType().Name; return components[1]?.GetType().Name; } [SearchSelector("tag", provider: providerId, priority: 99)] static object GetSceneObjectTag(SearchSelectorArgs args) { var go = args.current.ToObject<GameObject>(); if (!go) return null; return go.tag; } [SearchSelector("path", provider: providerId, priority: 99)] static object GetSceneObjectPath(SearchSelectorArgs args) { var go = args.current.ToObject<GameObject>(); if (!go) return null; return SearchUtils.GetHierarchyPath(go, false); } [SearchSelector("name", provider: providerId, priority: 99)] static object GetObjectName(SearchSelectorArgs args) { var go = args.current.ToObject<GameObject>(); if (!go) return null; return go.name; } [SearchSelector("enabled", provider: providerId, priority: 99)] static object GetEnabled(SearchSelectorArgs args) { return GetEnabled(args.current); } private static object GetEnabled(SearchItem item) { var go = item.ToObject<GameObject>(); if (!go) return null; return go.activeSelf; } private static object DrawEnabled(SearchColumnEventArgs args) { if (args.value == null) return null; var w = 14f + EditorStyles.toggle.margin.horizontal; if (args.column.options.HasAny(SearchColumnFlags.TextAlignmentRight)) args.rect.xMin = args.rect.xMax - w; else if (args.column.options.HasAny(SearchColumnFlags.TextAlignmentCenter)) args.rect.xMin += (args.rect.width - w) / 2f; else args.rect.x += EditorStyles.toggle.margin.left; args.value = EditorGUI.Toggle(args.rect, (bool)args.value); return args.value; } static object SetEnabled(SearchColumnEventArgs args) { var go = args.item.ToObject<GameObject>(); if (!go) return null; go.SetActive((bool)args.value); return go.activeSelf; } [SearchColumnProvider("GameObject/Enabled")] public static void InitializeObjectReferenceColumn(SearchColumn column) { column.getter = args => GetEnabled(args.item); column.setter = args => SetEnabled(args); column.cellCreator = col => new Toggle { style = { alignSelf = Align.Center } }; column.binder = (SearchColumnEventArgs args, VisualElement ve) => { var field = (Toggle)ve; if (args.value != null) { field.visible = true; field.SetValueWithoutNotify(System.Convert.ToBoolean(args.value)); } else { field.visible = false; } }; } public static IEnumerable<SearchColumn> Enumerate(IEnumerable<SearchItem> items) { return PropertySelectors.Enumerate(items).Concat(new[] { new SearchColumn("GameObject/Enabled", "enabled", "GameObject/Enabled", options: SearchColumnFlags.TextAlignmentCenter) }); } [SceneQueryEngineFilter("vdist")] [System.ComponentModel.Description("Object distance from view")] public static float SceneFilterViewDistance(GameObject go) { if (!go || !SceneView.lastActiveSceneView) return float.NaN; var cam = SceneView.lastActiveSceneView.camera; var dir = go.transform.position - cam.transform.position; return dir.magnitude; } [SceneQueryEngineFilter("position")] [System.ComponentModel.Description("Object world position")] public static Vector4 SceneFilterPosition(GameObject go) { return go.transform.position; } [SceneQueryEngineFilter("x"), System.ComponentModel.Description("Object world position X")] public static int SceneFilterPositionX(GameObject go) => Mathf.RoundToInt(go.transform.position.z); [SceneQueryEngineFilter("y"), System.ComponentModel.Description("Object world position Y")] public static int SceneFilterPositionY(GameObject go) => Mathf.RoundToInt(go.transform.position.y); [SceneQueryEngineFilter("z"), System.ComponentModel.Description("Object world position Z")] public static int SceneFilterPositionZ(GameObject go) => Mathf.RoundToInt(go.transform.position.z); [SearchSelector("position", provider: providerId)] public static object SceneSelectPosition(SearchItem item) { var go = item.ToObject<GameObject>(); if (!go) return null; return SceneFilterPosition(go); } [SearchSelector("x", provider: providerId)] public static object SceneSelectPositionX(SearchItem item) { var go = item.ToObject<GameObject>(); if (!go) return null; return Mathf.RoundToInt(go.transform.position.x); } [SearchSelector("y", provider: providerId)] public static object SceneSelectPositionY(SearchItem item) { var go = item.ToObject<GameObject>(); if (!go) return null; return Mathf.RoundToInt(go.transform.position.y); } [SearchSelector("z", provider: providerId)] public static object SceneSelectPositionZ(SearchItem item) { var go = item.ToObject<GameObject>(); if (!go) return null; return Mathf.RoundToInt(go.transform.position.z); } [SearchSelector("vertices", provider: "scene")] public static object SelectVertices(SearchSelectorArgs args) { var go = args.current.ToObject<GameObject>(); if (!go) return null; return SceneFilterVertices(go); } [SceneQueryEngineFilter("vertices")] [System.ComponentModel.Description("Mesh vertex count")] public static int SceneFilterVertices(GameObject go) { var meshFilter = go.GetComponent<MeshFilter>(); if (!meshFilter || !meshFilter.sharedMesh) return 0; return meshFilter.sharedMesh.vertexCount; } [SearchSelector("faces", provider: "scene")] public static object SelectFaces(SearchSelectorArgs args) { var go = args.current.ToObject<GameObject>(); if (!go) return null; return SceneFilterFaces(go) ?? null; } [SceneQueryEngineFilter("faces")] [System.ComponentModel.Description("Mesh triangle face count")] public static int? SceneFilterFaces(GameObject go) { var meshFilter = go.GetComponent<MeshFilter>(); if (!meshFilter || !meshFilter.sharedMesh) return null; return meshFilter.sharedMesh.triangles.Length; } [SearchSelector("static", provider: "scene")] [System.ComponentModel.Description("Static States")] public static object SelectObjectStaticStates(SearchItem item) { var go = item.ToObject<GameObject>(); if (!go) return (StaticEditorFlags)0; return GameObjectUtility.GetStaticEditorFlags(go); } [SceneQueryEngineFilter("static")] [System.ComponentModel.Description("Static States")] public static StaticEditorFlags FilterObjectStaticStates(GameObject go) { return GameObjectUtility.GetStaticEditorFlags(go); } } }
UnityCsReference/Modules/QuickSearch/Editor/Selectors/SceneSelectors.cs/0
{ "file_path": "UnityCsReference/Modules/QuickSearch/Editor/Selectors/SceneSelectors.cs", "repo_id": "UnityCsReference", "token_count": 4023 }
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 System.Collections.Generic; using UnityEditor.SceneManagement; using UnityEngine; using UnityEngine.Internal; using UnityEngine.Search; using UnityEngine.UIElements; using Object = UnityEngine.Object; namespace UnityEditor.Search { /// <summary> /// Makes a field to receive any object type. /// </summary> public class ObjectField : BaseField<Object> { [Obsolete("Use singleLineHeight instead. (UnityUpgradable) -> singleLineHeight", error: true)] // 2022.2 public static float kSingleLineHeight => singleLineHeight; public static float singleLineHeight { get { return EditorGUI.kSingleLineHeight; } } [ExcludeFromDocs, Serializable] public new class UxmlSerializedData : BaseField<Object>.UxmlSerializedData { #pragma warning disable 649 [SerializeField, UxmlTypeReference(typeof(Object))] string type; [SerializeField, UxmlIgnore, HideInInspector] UxmlAttributeFlags type_UxmlAttributeFlags; #pragma warning restore 649 public override object CreateInstance() => new ObjectField(); public override void Deserialize(object obj) { base.Deserialize(obj); if (ShouldWriteAttributeValue(type_UxmlAttributeFlags)) { var e = (ObjectField)obj; e.objectType = UxmlUtility.ParseType(type, typeof(Object)); } } } public override void SetValueWithoutNotify(Object newValue) { newValue = TryReadComponentFromGameObject(newValue, objectType); var valueChanged = !EqualityComparer<Object>.Default.Equals(this.value, newValue); base.SetValueWithoutNotify(newValue); if (valueChanged) { m_ObjectFieldDisplay.Update(); } } private Type m_ObjectType = typeof(Object); Object m_OriginalObject = null; /// <summary> /// The type of the objects that can be assigned. /// </summary> public Type objectType { get { return m_ObjectType; } set { if (m_ObjectType != value) { m_ObjectType = value; m_ObjectFieldDisplay.Update(); } } } public SearchContext searchContext { get; set; } public SearchViewFlags searchViewFlags { get; set; } private class ObjectFieldDisplay : VisualElement { private readonly ObjectField m_ObjectField; private readonly Image m_ObjectIcon; private readonly Label m_ObjectLabel; static readonly string ussClassName = "unity-object-field-display"; static readonly string iconUssClassName = ussClassName + "__icon"; static readonly string labelUssClassName = ussClassName + "__label"; static readonly string acceptDropVariantUssClassName = ussClassName + "--accept-drop"; public ObjectFieldDisplay(ObjectField objectField) { AddToClassList(ussClassName); m_ObjectIcon = new Image {scaleMode = ScaleMode.ScaleAndCrop, pickingMode = PickingMode.Ignore}; m_ObjectIcon.AddToClassList(iconUssClassName); m_ObjectLabel = new Label {pickingMode = PickingMode.Ignore}; m_ObjectLabel.AddToClassList(labelUssClassName); m_ObjectField = objectField; Update(); Add(m_ObjectIcon); Add(m_ObjectLabel); } public void Update() { GUIContent content = EditorGUIUtility.ObjectContent(m_ObjectField.value, m_ObjectField.objectType); m_ObjectIcon.image = content.image; m_ObjectLabel.text = content.text; } [EventInterest(typeof(MouseDownEvent), typeof(KeyDownEvent), typeof(DragUpdatedEvent), typeof(DragPerformEvent), typeof(DragLeaveEvent))] protected override void HandleEventBubbleUp(EventBase evt) { base.HandleEventBubbleUp(evt); if (evt == null) { return; } if ((evt as MouseDownEvent)?.button == (int)MouseButton.LeftMouse) OnMouseDown(evt as MouseDownEvent); else if (evt.eventTypeId == KeyDownEvent.TypeId()) { var kdEvt = evt as KeyDownEvent; if (((evt as KeyDownEvent)?.keyCode == KeyCode.Space) || ((evt as KeyDownEvent)?.keyCode == KeyCode.KeypadEnter) || ((evt as KeyDownEvent)?.keyCode == KeyCode.Return)) { OnKeyboardEnter(); } else if (kdEvt.keyCode == KeyCode.Delete || kdEvt.keyCode == KeyCode.Backspace) { OnKeyboardDelete(); } } else if (evt.eventTypeId == DragUpdatedEvent.TypeId()) OnDragUpdated(evt); else if (evt.eventTypeId == DragPerformEvent.TypeId()) OnDragPerform(evt); else if (evt.eventTypeId == DragLeaveEvent.TypeId()) OnDragLeave(); } private void OnDragLeave() { // Make sure we've cleared the accept drop look, whether we we in a drop operation or not. RemoveFromClassList(acceptDropVariantUssClassName); } private void OnMouseDown(MouseDownEvent evt) { Object actualTargetObject = m_ObjectField.value; Component com = actualTargetObject as Component; if (com) actualTargetObject = com.gameObject; if (actualTargetObject == null) return; // One click shows where the referenced object is, or pops up a preview if (evt.clickCount == 1) { // ping object bool anyModifiersPressed = evt.shiftKey || evt.ctrlKey; if (!anyModifiersPressed && actualTargetObject) { EditorGUIUtility.PingObject(actualTargetObject); } evt.StopPropagation(); } // Double click opens the asset in external app or changes selection to referenced object else if (evt.clickCount == 2) { if (actualTargetObject) { AssetDatabase.OpenAsset(actualTargetObject); GUIUtility.ExitGUI(); } evt.StopPropagation(); } } private void OnKeyboardEnter() { m_ObjectField.ShowObjectSelector(); } private void OnKeyboardDelete() { m_ObjectField.value = null; } private Object DNDValidateObject() { Object[] references = DragAndDrop.objectReferences; Object validatedObject = EditorGUI.ValidateObjectFieldAssignment(references, m_ObjectField.objectType, null, EditorGUI.ObjectFieldValidatorOptions.None); return validatedObject; } private void OnDragUpdated(EventBase evt) { Object validatedObject = DNDValidateObject(); if (validatedObject != null) { DragAndDrop.visualMode = DragAndDropVisualMode.Generic; AddToClassList(acceptDropVariantUssClassName); evt.StopPropagation(); } } private void OnDragPerform(EventBase evt) { Object validatedObject = DNDValidateObject(); if (validatedObject != null) { DragAndDrop.visualMode = DragAndDropVisualMode.Generic; m_ObjectField.value = validatedObject; DragAndDrop.AcceptDrag(); RemoveFromClassList(acceptDropVariantUssClassName); evt.StopPropagation(); } } } private class ObjectFieldSelector : VisualElement { private readonly ObjectField m_ObjectField; public ObjectFieldSelector(ObjectField objectField) { m_ObjectField = objectField; } [EventInterest(typeof(MouseDownEvent))] protected override void HandleEventBubbleUp(EventBase evt) { base.HandleEventBubbleUp(evt); if ((evt as MouseDownEvent)?.button == (int)MouseButton.LeftMouse) m_ObjectField.ShowObjectSelector(); } } private readonly ObjectFieldDisplay m_ObjectFieldDisplay; private readonly Action m_AsyncOnProjectOrHierarchyChangedCallback; private readonly Action m_OnProjectOrHierarchyChangedCallback; /// <summary> /// USS class name of elements of this type. /// </summary> internal new static readonly string ussClassName = "unity-object-field"; /// <summary> /// USS class name of labels in elements of this type. /// </summary> internal new static readonly string labelUssClassName = ussClassName + "__label"; /// <summary> /// USS class name of input elements in elements of this type. /// </summary> internal new static readonly string inputUssClassName = ussClassName + "__input"; /// <summary> /// USS class name of object elements in elements of this type. /// </summary> internal static readonly string objectUssClassName = ussClassName + "__object"; /// <summary> /// USS class name of selector elements in elements of this type. /// </summary> internal static readonly string selectorUssClassName = ussClassName + "__selector"; /// <summary> /// Constructor. /// </summary> public ObjectField() : this(null) {} /// <summary> /// Constructor. /// </summary> public ObjectField(string label) : base(label, null) { visualInput.focusable = false; labelElement.focusable = false; AddToClassList(ussClassName); labelElement.AddToClassList(labelUssClassName); m_ObjectFieldDisplay = new ObjectFieldDisplay(this) { focusable = true }; m_ObjectFieldDisplay.AddToClassList(objectUssClassName); var objectSelector = new ObjectFieldSelector(this); objectSelector.AddToClassList(selectorUssClassName); visualInput.AddToClassList(inputUssClassName); visualInput.Add(m_ObjectFieldDisplay); visualInput.Add(objectSelector); // Get notified when hierarchy or project changes so we can update the display to handle renamed/missing objects. // This event is occasionally triggered before the reference in memory is updated, so we give it time to process. m_AsyncOnProjectOrHierarchyChangedCallback = () => schedule.Execute(m_OnProjectOrHierarchyChangedCallback); m_OnProjectOrHierarchyChangedCallback = () => m_ObjectFieldDisplay.Update(); RegisterCallback<AttachToPanelEvent>((evt) => { EditorApplication.projectChanged += m_AsyncOnProjectOrHierarchyChangedCallback; EditorApplication.hierarchyChanged += m_AsyncOnProjectOrHierarchyChangedCallback; }); RegisterCallback<DetachFromPanelEvent>((evt) => { EditorApplication.projectChanged -= m_AsyncOnProjectOrHierarchyChangedCallback; EditorApplication.hierarchyChanged -= m_AsyncOnProjectOrHierarchyChangedCallback; }); searchViewFlags = SearchViewFlags.ObjectPicker; } private void OnObjectChanged(Object obj) { value = TryReadComponentFromGameObject(obj, objectType); } void OnSelection(Object item, bool canceled) { if (canceled) value = m_OriginalObject; } internal void ShowObjectSelector() { m_OriginalObject = value; var runtimeContext = new RuntimeSearchContext { contextId = bindingPath ?? name ?? label, pickerType = SearchPickerType.ObjectField, currentObject = m_OriginalObject, requiredTypes = new[] { objectType }, requiredTypeNames = new[] { objectType.ToString() } }; if (searchContext == null) { searchContext = SearchService.CreateContext(runtimeContext, ""); } var newContext = new SearchContext(searchContext.providers, searchContext.searchText, searchContext.options, runtimeContext); var searchViewState = SearchViewState.CreatePickerState($"{objectType.Name}", newContext, OnSelection, OnObjectChanged, objectType.ToString(), objectType, searchViewFlags); if (m_OriginalObject) searchViewState.selectedIds = new int[] { m_OriginalObject.GetInstanceID() }; SearchService.ShowPicker(searchViewState); SearchAnalytics.SendEvent(null, SearchAnalytics.GenericEventType.QuickSearchPickerOpens, searchContext.searchText, "object", "objectfield"); } private Object TryReadComponentFromGameObject(Object obj, Type type) { var go = obj as GameObject; if (go != null && type != null && type.IsSubclassOf(typeof(Component))) { var comp = go.GetComponent(objectType); if (comp != null) return comp; } return obj; } public static void DoObjectField(Rect position, SerializedProperty property, Type objType, GUIContent label, SearchContext context, SearchViewFlags searchViewFlags = SearchViewFlags.None) { label = EditorGUI.BeginProperty(position, label, property); var id = GUIUtility.GetControlID(ObjectFieldGUI.objectFieldHash, FocusType.Keyboard, position); position = EditorGUI.PrefixLabel(position, id, label); ObjectFieldGUI.DoObjectField(position, position, id, objType, property, null, context, searchViewFlags); EditorGUI.EndProperty(); } public static Object DoObjectField(Rect position, Object obj, Type objType, GUIContent label, SearchContext context, SearchViewFlags searchViewFlags = SearchViewFlags.None) { var id = GUIUtility.GetControlID(ObjectFieldGUI.objectFieldHash, FocusType.Keyboard, position); position = EditorGUI.PrefixLabel(position, id, label); return ObjectFieldGUI.DoObjectField(position, position, id, obj, null, objType, null, context, searchViewFlags); } } static class ObjectFieldGUI { static private GUIContent s_SceneMismatch = EditorGUIUtility.TrTextContent("Scene mismatch (cross scene references not supported)"); static private GUIContent s_TypeMismatch = EditorGUIUtility.TrTextContent("Type mismatch"); static private GUIContent s_Select = EditorGUIUtility.TrTextContent("Select"); const string k_PickerClosedCommand = "SearchPickerClosed"; const string k_PickerUpdatedCommand = "SearchPickerUpdated"; static EditorWindow s_DelegateWindow; static Object s_LastSelectedItem; static Object s_OriginalItem; public static readonly int objectFieldHash = "s_ObjectFieldHash".GetHashCode(); static int s_LastPickerId; static bool s_LastSelectionWasCanceled; static int s_ModalUndoGroup = -1; // Takes object directly, no SerializedProperty. internal static Object DoObjectField(Rect position, Rect dropRect, int id, Object obj, Object objBeingEdited, System.Type objType, EditorGUI.ObjectFieldValidator validator, SearchContext context, SearchViewFlags searchViewFlags = SearchViewFlags.None, GUIStyle style = null) { return DoObjectField(position, dropRect, id, obj, objBeingEdited, objType, null, validator, style != null ? style : EditorStyles.objectField, context, searchViewFlags); } // Takes SerializedProperty, no direct reference to object. internal static Object DoObjectField(Rect position, Rect dropRect, int id, System.Type objType, SerializedProperty property, EditorGUI.ObjectFieldValidator validator, SearchContext context, SearchViewFlags searchViewFlags = SearchViewFlags.None, GUIStyle style = null) { return DoObjectField(position, dropRect, id, null, null, objType, property, validator, style != null ? style : EditorStyles.objectField, context, searchViewFlags); } internal enum ObjectFieldVisualType { IconAndText, LargePreview, MiniPreview } // when current event is mouse click, this function pings the object, or // if shift/control is pressed and object is a texture, pops up a large texture // preview window internal static void PingObjectOrShowPreviewOnClick(Object targetObject, Rect position) { if (targetObject == null) return; Event evt = Event.current; // ping object bool anyModifiersPressed = evt.shift || evt.control; if (!anyModifiersPressed) { EditorGUIUtility.PingObject(targetObject); return; } // show large object preview popup; right now only for textures if (targetObject is Texture) { Utils.PopupWindowWithoutFocus(new RectOffset(6, 3, 0, 3).Add(position), new ObjectPreviewPopup(targetObject)); } } static Object AssignSelectedObject(SerializedProperty property, EditorGUI.ObjectFieldValidator validator, System.Type objectType, Event evt) { Object[] references = { s_LastSelectedItem }; Object assigned = validator(references, objectType, property, EditorGUI.ObjectFieldValidatorOptions.None); // Assign the value if (property != null) property.objectReferenceValue = assigned; GUI.changed = true; evt.Use(); return assigned; } static private Rect GetButtonRect(ObjectFieldVisualType visualType, Rect position) { switch (visualType) { case ObjectFieldVisualType.IconAndText: return new Rect(position.xMax - 19, position.y, 19, position.height); case ObjectFieldVisualType.MiniPreview: return new Rect(position.xMax - 14, position.y, 14, position.height); case ObjectFieldVisualType.LargePreview: return new Rect(position.xMax - 36, position.yMax - 14, 36, 14); default: throw new ArgumentOutOfRangeException(); } } static bool HasValidScript(UnityEngine.Object obj) { MonoScript script = Utils.MonoScriptFromScriptedObject(obj); if (script == null) { return false; } Type type = script.GetClass(); if (type == null) { return false; } return true; } static bool ValidDroppedObject(Object[] references, System.Type objType, out string errorString) { errorString = ""; if (references == null || references.Length == 0) { return true; } var reference = references[0]; Object obj = EditorUtility.InstanceIDToObject(reference.GetInstanceID()); if (obj is MonoBehaviour || obj is ScriptableObject) { if (!HasValidScript(obj)) { errorString = $"Type cannot be found: {reference.GetType()}. Containing file and class name must match."; return false; } } return true; } // Timeline package is using this internal overload so can't remove until that's fixed. internal static Object DoObjectField(Rect position, Rect dropRect, int id, Object obj, System.Type objType, SerializedProperty property, EditorGUI.ObjectFieldValidator validator, GUIStyle style, SearchContext context, SearchViewFlags searchViewFlags = SearchViewFlags.None) { return DoObjectField(position, dropRect, id, objType, property, validator, context, searchViewFlags); } static Object DoObjectField(Rect position, Rect dropRect, int id, Object obj, Object objBeingEdited, System.Type objType, SerializedProperty property, EditorGUI.ObjectFieldValidator validator, GUIStyle style, SearchContext context, SearchViewFlags searchViewFlags = SearchViewFlags.None) { if (validator == null) validator = EditorGUI.ValidateObjectFieldAssignment; if (property != null) obj = property.objectReferenceValue; Event evt = Event.current; EventType eventType = evt.type; // special case test, so we continue to ping/select objects with the object field disabled if (!GUI.enabled && Utils.IsGUIClipEnabled() && (Event.current.rawType == EventType.MouseDown)) eventType = Event.current.rawType; bool hasThumbnail = EditorGUIUtility.HasObjectThumbnail(objType); // Determine visual type ObjectFieldVisualType visualType = ObjectFieldVisualType.IconAndText; if (hasThumbnail && position.height <= EditorGUI.kObjectFieldMiniThumbnailHeight && position.width <= EditorGUI.kObjectFieldMiniThumbnailWidth) visualType = ObjectFieldVisualType.MiniPreview; else if (hasThumbnail && position.height > EditorGUI.kSingleLineHeight) visualType = ObjectFieldVisualType.LargePreview; Vector2 oldIconSize = EditorGUIUtility.GetIconSize(); if (visualType == ObjectFieldVisualType.IconAndText) EditorGUIUtility.SetIconSize(new Vector2(12, 12)); // Have to be this small to fit inside a single line height ObjectField else if (visualType == ObjectFieldVisualType.LargePreview) EditorGUIUtility.SetIconSize(new Vector2(64, 64)); if ((eventType == EventType.MouseDown && Event.current.button == 1 || eventType == EventType.ContextClick) && position.Contains(Event.current.mousePosition)) { var actualObject = property != null ? property.objectReferenceValue : obj; var contextMenu = new GenericMenu(); if (EditorGUI.FillPropertyContextMenu(property, null, contextMenu) != null) contextMenu.AddSeparator(""); contextMenu.AddItem(Utils.GUIContentTemp("Properties..."), false, () => Utils.OpenPropertyEditor(actualObject)); contextMenu.DropDown(position); Event.current.Use(); } switch (eventType) { case EventType.DragExited: if (GUI.enabled) HandleUtility.Repaint(); break; case EventType.DragUpdated: case EventType.DragPerform: if (eventType == EventType.DragPerform) { string errorString; if (!ValidDroppedObject(DragAndDrop.objectReferences, objType, out errorString)) { Object reference = DragAndDrop.objectReferences[0]; EditorUtility.DisplayDialog("Can't assign script", errorString, "OK"); break; } } if (dropRect.Contains(Event.current.mousePosition) && GUI.enabled) { Object[] references = DragAndDrop.objectReferences; Object validatedObject = validator(references, objType, property, EditorGUI.ObjectFieldValidatorOptions.None); if (validatedObject != null) { DragAndDrop.visualMode = DragAndDropVisualMode.Generic; if (eventType == EventType.DragPerform) { if (property != null) property.objectReferenceValue = validatedObject; else obj = validatedObject; GUI.changed = true; DragAndDrop.AcceptDrag(); DragAndDrop.activeControlID = 0; } else { DragAndDrop.activeControlID = id; } Event.current.Use(); } } break; case EventType.MouseDown: if (position.Contains(Event.current.mousePosition) && Event.current.button == 0) { // Get button rect for Object Selector Rect buttonRect = GetButtonRect(visualType, position); EditorGUIUtility.editingTextField = false; if (buttonRect.Contains(Event.current.mousePosition)) { if (GUI.enabled) { GUIUtility.keyboardControl = id; ShowSearchPicker(context, searchViewFlags, property, property == null ? obj : null, id, evt, objType); } } else { Object actualTargetObject = property != null ? property.objectReferenceValue : obj; Component com = actualTargetObject as Component; if (com) actualTargetObject = com.gameObject; if (EditorGUI.showMixedValue) actualTargetObject = null; // One click shows where the referenced object is, or pops up a preview if (Event.current.clickCount == 1) { GUIUtility.keyboardControl = id; PingObjectOrShowPreviewOnClick(actualTargetObject, position); evt.Use(); } // Double click opens the asset in external app or changes selection to referenced object else if (Event.current.clickCount == 2) { if (actualTargetObject) { AssetDatabase.OpenAsset(actualTargetObject); evt.Use(); GUIUtility.ExitGUI(); } } } } break; case EventType.ExecuteCommand: string commandName = evt.commandName; if (commandName == k_PickerUpdatedCommand && s_LastPickerId == id && GUIUtility.keyboardControl == id && (property == null || !Utils.SerializedPropertyIsScript(property))) return AssignSelectedObject(property, validator, objType, evt); else if (commandName == k_PickerClosedCommand && s_LastPickerId == id && GUIUtility.keyboardControl == id) { if (s_LastSelectionWasCanceled) { // User canceled object selection; don't apply evt.Use(); // When we operate directly on objects, the undo system doesn't work. // We added a hack that sets the s_LastSelectedItem to the original item // when canceling with an object. if (property == null) return s_LastSelectedItem; break; } // When property is script, it is not assigned on update, so assign it on close if (property != null && Utils.SerializedPropertyIsScript(property)) return AssignSelectedObject(property, validator, objType, evt); return property != null ? property.objectReferenceValue : obj; } else if (Utils.IsCommandDelete(evt.commandName) && GUIUtility.keyboardControl == id) { if (property != null) property.objectReferenceValue = null; else obj = null; GUI.changed = true; evt.Use(); } break; case EventType.ValidateCommand: if (Utils.IsCommandDelete(evt.commandName) && GUIUtility.keyboardControl == id) { evt.Use(); } break; case EventType.KeyDown: if (GUIUtility.keyboardControl == id) { if (evt.keyCode == KeyCode.Backspace || (evt.keyCode == KeyCode.Delete && (evt.modifiers & EventModifiers.Shift) == 0)) { if (property != null) property.objectReferenceValue = null; else obj = null; GUI.changed = true; evt.Use(); } // Apparently we have to check for the character being space instead of the keyCode, // otherwise the Inspector will maximize upon pressing space. if (Utils.MainActionKeyForControl(evt, id)) { ShowSearchPicker(context, searchViewFlags, property, property == null ? obj : null, id, evt, objType); } } break; case EventType.Repaint: GUIContent temp; if (EditorGUI.showMixedValue) { temp = EditorGUI.mixedValueContent; } else { // If obj or objType are both null, we have to rely on // property.objectReferenceStringValue to display None/Missing and the // correct type. But if not, EditorGUIUtility.ObjectContent is more reliable. // It can take a more specific object type specified as argument into account, // and it gets the icon at the same time. if (obj == null && objType == null && property != null) { temp = Utils.GUIContentTemp(Utils.SerializedPropertyObjectReferenceStringValue(property)); } else { // In order for ObjectContext to be able to distinguish between None/Missing, // we need to supply an instanceID. For some reason, getting the instanceID // from property.objectReferenceValue is not reliable, so we have to // explicitly check property.objectReferenceInstanceIDValue if a property exists. if (property != null) temp = Utils.ObjectContent(obj, objType, property.objectReferenceInstanceIDValue); else temp = EditorGUIUtility.ObjectContent(obj, objType); } if (property != null) { if (obj != null) { Object[] references = { obj }; if (EditorSceneManager.preventCrossSceneReferences && EditorGUI.CheckForCrossSceneReferencing(obj, property.serializedObject.targetObject)) { if (!EditorApplication.isPlaying) temp = s_SceneMismatch; else temp.text = temp.text + string.Format(" ({0})", EditorGUI.GetGameObjectFromObject(obj).scene.name); } else if (validator(references, objType, property, EditorGUI.ObjectFieldValidatorOptions.ExactObjectTypeValidation) == null) temp = s_TypeMismatch; } } } switch (visualType) { case ObjectFieldVisualType.IconAndText: EditorGUI.BeginHandleMixedValueContentColor(); style.Draw(position, temp, id, DragAndDrop.activeControlID == id, position.Contains(Event.current.mousePosition)); Rect buttonRect = Utils.objectFieldButton.margin.Remove(GetButtonRect(visualType, position)); Utils.objectFieldButton.Draw(buttonRect, GUIContent.none, id, DragAndDrop.activeControlID == id, buttonRect.Contains(Event.current.mousePosition)); EditorGUI.EndHandleMixedValueContentColor(); break; case ObjectFieldVisualType.LargePreview: DrawObjectFieldLargeThumb(position, id, obj, temp); break; case ObjectFieldVisualType.MiniPreview: DrawObjectFieldMiniThumb(position, id, obj, temp); break; default: throw new ArgumentOutOfRangeException(); } break; } EditorGUIUtility.SetIconSize(oldIconSize); return obj; } private static void DrawObjectFieldLargeThumb(Rect position, int id, Object obj, GUIContent content) { GUIStyle thumbStyle = EditorStyles.objectFieldThumb; thumbStyle.Draw(position, GUIContent.none, id, DragAndDrop.activeControlID == id, position.Contains(Event.current.mousePosition)); if (obj != null && !EditorGUI.showMixedValue) { Matrix4x4 guiMatrix = GUI.matrix; // Initial matrix is saved in order to be able to reset it to default bool isSprite = obj is Sprite; bool alphaIsTransparencyTex2D = (obj is Texture2D && (obj as Texture2D).alphaIsTransparency); Rect thumbRect = thumbStyle.padding.Remove(position); Texture2D t2d = AssetPreview.GetAssetPreview(obj); if (t2d != null) { // A checkerboard background is drawn behind transparent textures (for visibility) if (isSprite || t2d.alphaIsTransparency || alphaIsTransparencyTex2D) GUI.DrawTexture(thumbRect, EditorGUI.transparentCheckerTexture, ScaleMode.StretchToFill, false); // Draw asset preview (scaled to fit inside the frame) GUIUtility.ScaleAroundPivot(thumbRect.size / position.size, thumbRect.position); GUIStyle.none.Draw(thumbRect, t2d, false, false, false, false); GUI.matrix = guiMatrix; } else { // Preview not loaded -> Draw icon if (isSprite || alphaIsTransparencyTex2D) { // A checkerboard background is drawn behind transparent textures (for visibility) GUI.DrawTexture(thumbRect, EditorGUI.transparentCheckerTexture, ScaleMode.StretchToFill, false); GUI.DrawTexture(thumbRect, content.image, ScaleMode.StretchToFill, true); } else EditorGUI.DrawPreviewTexture(thumbRect, content.image); // Keep repainting until the object field has a proper preview HandleUtility.Repaint(); } } else { GUIStyle s2 = thumbStyle.name + "Overlay"; EditorGUI.BeginHandleMixedValueContentColor(); s2.Draw(position, content, id); EditorGUI.EndHandleMixedValueContentColor(); } GUIStyle s3 = thumbStyle.name + "Overlay2"; s3.Draw(position, s_Select, id); } private static void DrawObjectFieldMiniThumb(Rect position, int id, Object obj, GUIContent content) { GUIStyle thumbStyle = EditorStyles.objectFieldMiniThumb; position.width = EditorGUI.kObjectFieldMiniThumbnailWidth; EditorGUI.BeginHandleMixedValueContentColor(); bool hover = obj != null; // we use hover texture for enhancing the border if we have a reference bool on = DragAndDrop.activeControlID == id; bool keyFocus = GUIUtility.keyboardControl == id; thumbStyle.Draw(position, hover, false, on, keyFocus); EditorGUI.EndHandleMixedValueContentColor(); if (obj != null && !EditorGUI.showMixedValue) { Rect thumbRect = new Rect(position.x + 1, position.y + 1, position.height - 2, position.height - 2); // subtract 1 px border Texture2D t2d = content.image as Texture2D; if (t2d != null && t2d.alphaIsTransparency) EditorGUI.DrawTextureTransparent(thumbRect, t2d); else EditorGUI.DrawPreviewTexture(thumbRect, content.image); // Tooltip if (thumbRect.Contains(Event.current.mousePosition)) GUI.Label(thumbRect, Search.Utils.GUIContentTemp(string.Empty, "Ctrl + Click to show preview")); } } internal static Object DoDropField(Rect position, int id, System.Type objType, EditorGUI.ObjectFieldValidator validator, bool allowSceneObjects, GUIStyle style) { if (validator == null) validator = EditorGUI.ValidateObjectFieldAssignment; Event evt = Event.current; EventType eventType = evt.type; // special case test, so we continue to ping/select objects with the object field disabled if (!GUI.enabled && Utils.IsGUIClipEnabled() && (Event.current.rawType == EventType.MouseDown)) eventType = Event.current.rawType; switch (eventType) { case EventType.DragExited: if (GUI.enabled) HandleUtility.Repaint(); break; case EventType.DragUpdated: case EventType.DragPerform: if (position.Contains(Event.current.mousePosition) && GUI.enabled) { Object[] references = DragAndDrop.objectReferences; Object validatedObject = validator(references, objType, null, EditorGUI.ObjectFieldValidatorOptions.None); if (validatedObject != null) { // If scene objects are not allowed and object is a scene object then clear if (!allowSceneObjects && !EditorUtility.IsPersistent(validatedObject)) validatedObject = null; } if (validatedObject != null) { DragAndDrop.visualMode = DragAndDropVisualMode.Generic; if (eventType == EventType.DragPerform) { GUI.changed = true; DragAndDrop.AcceptDrag(); DragAndDrop.activeControlID = 0; Event.current.Use(); return validatedObject; } else { DragAndDrop.activeControlID = id; Event.current.Use(); } } } break; case EventType.Repaint: style.Draw(position, GUIContent.none, id, DragAndDrop.activeControlID == id); break; } return null; } static void ShowSearchPicker(SearchContext context, SearchViewFlags searchViewFlags, SerializedProperty property, Object originalObject, int id, Event evt, Type objType) { s_DelegateWindow = EditorWindow.focusedWindow; s_ModalUndoGroup = Undo.GetCurrentGroup(); s_OriginalItem = originalObject; var title = property != null ? $"{property.displayName} ({objType.Name})" : objType.Name; var searchViewState = SearchViewState.CreatePickerState(title, context, (item, canceled) => SendSelectionEvent(item, canceled, id), item => SendTrackingEvent(item, id), objType.ToString(), objType) .SetSearchViewFlags(searchViewFlags); if (property != null && property.propertyType == SerializedPropertyType.ObjectReference && property.objectReferenceValue) { searchViewState.selectedIds = new int[] { property.objectReferenceValue.GetInstanceID() }; } else if (originalObject) { searchViewState.selectedIds = new int[] { originalObject.GetInstanceID() }; } SearchAnalytics.SendEvent(null, SearchAnalytics.GenericEventType.QuickSearchPickerOpens, context.searchText, "object", "objectfield"); SearchService.ShowPicker(searchViewState); evt.Use(); GUIUtility.ExitGUI(); } static void SendSelectionEvent(Object item, bool canceled, int id) { s_LastPickerId = id; s_LastSelectedItem = item; s_LastSelectionWasCanceled = canceled; if (canceled) { if (s_OriginalItem) { s_LastSelectedItem = s_OriginalItem; s_OriginalItem = null; } Undo.RevertAllDownToGroup(s_ModalUndoGroup); } Undo.CollapseUndoOperations(s_ModalUndoGroup); SendEvent(k_PickerClosedCommand, false); } static void SendTrackingEvent(Object item, int id) { s_LastPickerId = id; s_LastSelectedItem = item; SendEvent(k_PickerUpdatedCommand, false); } static void SendEvent(string eventName, bool exitGUI) { if (s_DelegateWindow && s_DelegateWindow.m_Parent != null) { Event e = EditorGUIUtility.CommandEvent(eventName); try { s_DelegateWindow.SendEvent(e); } finally { if (exitGUI) GUIUtility.ExitGUI(); } } } class ObjectPreviewPopup : PopupWindowContent { readonly Editor m_Editor; readonly GUIContent m_ObjectName; const float kToolbarHeight = 22f; internal class Styles { public readonly GUIStyle toolbar = "preToolbar"; public readonly GUIStyle toolbarText = "ToolbarBoldLabel"; public GUIStyle background = "preBackground"; } Styles s_Styles; public ObjectPreviewPopup(Object previewObject) { if (previewObject == null) { Debug.LogError("ObjectPreviewPopup: Check object is not null, before trying to show it!"); return; } m_ObjectName = new GUIContent(previewObject.name, AssetDatabase.GetAssetPath(previewObject)); // Show path as tooltip on label m_Editor = Editor.CreateEditor(previewObject); } public override void OnClose() { if (m_Editor != null) Editor.DestroyImmediate(m_Editor); } public override void OnGUI(Rect rect) { if (m_Editor == null) { editorWindow.Close(); return; } if (s_Styles == null) s_Styles = new Styles(); // Toolbar Rect toolbarRect = Utils.BeginHorizontal(GUIContent.none, s_Styles.toolbar, GUILayout.Height(kToolbarHeight)); { GUILayout.FlexibleSpace(); Rect contentRect = EditorGUILayout.BeginHorizontal(); m_Editor.OnPreviewSettings(); EditorGUILayout.EndHorizontal(); const float kPadding = 5f; Rect labelRect = new Rect(toolbarRect.x + kPadding, toolbarRect.y, toolbarRect.width - contentRect.width - 2 * kPadding, toolbarRect.height); Vector2 labelSize = s_Styles.toolbarText.CalcSize(m_ObjectName); labelRect.width = Mathf.Min(labelRect.width, labelSize.x); m_ObjectName.tooltip = m_ObjectName.text; GUI.Label(labelRect, m_ObjectName, s_Styles.toolbarText); } EditorGUILayout.EndHorizontal(); // Object preview Rect previewRect = new Rect(rect.x, rect.y + kToolbarHeight, rect.width, rect.height - kToolbarHeight); m_Editor.OnPreviewGUI(previewRect, s_Styles.background); } public override Vector2 GetWindowSize() { return new Vector2(600f, 300f + kToolbarHeight); } } } }
UnityCsReference/Modules/QuickSearch/Editor/UI/ObjectField.cs/0
{ "file_path": "UnityCsReference/Modules/QuickSearch/Editor/UI/ObjectField.cs", "repo_id": "UnityCsReference", "token_count": 24132 }
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 System.Collections.Generic; using System.Linq; using UnityEngine.UIElements; namespace UnityEditor.Search { delegate bool SearchGlobalEventHandler<in T>(T evt) where T : EventBase; readonly struct SearchGlobalEventHandlerContainer { public readonly int priority; public readonly Type type; public readonly object handler; public readonly int handlerHashCode; SearchGlobalEventHandlerContainer(object handler, Type type, int priority, int handlerHashCode) { this.priority = priority; this.type = type; this.handler = handler; this.handlerHashCode = handlerHashCode; } public static SearchGlobalEventHandlerContainer Make<T>(SearchGlobalEventHandler<T> handler, int priority) where T : EventBase { return new SearchGlobalEventHandlerContainer(handler, typeof(T), priority, handler.GetHashCode()); } public bool IsType<T>() { return IsType(typeof(T)); } public bool IsType(Type targetType) { return type == targetType; } public bool Invoke<T>(T evt) where T : EventBase { if (handler is not SearchGlobalEventHandler<T> eventHandler) return false; return eventHandler.Invoke(evt); } } class SearchGlobalEventHandlerManager { Dictionary<Type, List<SearchGlobalEventHandlerContainer>> m_GlobalEventHandlers = new Dictionary<Type, List<SearchGlobalEventHandlerContainer>>(); public Action RegisterGlobalEventHandler<T>(SearchGlobalEventHandler<T> eventHandler, int priority) where T : EventBase { var eventType = typeof(T); if (!m_GlobalEventHandlers.ContainsKey(eventType)) m_GlobalEventHandlers.Add(eventType, new List<SearchGlobalEventHandlerContainer>()); var handlerList = m_GlobalEventHandlers[eventType]; var eventHandlerHashCode = eventHandler.GetHashCode(); RemoveHandlerWithHashCode(eventHandlerHashCode, handlerList); handlerList.Add(SearchGlobalEventHandlerContainer.Make(eventHandler, priority)); return () => UnregisterGlobalEventHandler(eventHandler); } public void UnregisterGlobalEventHandler<T>(SearchGlobalEventHandler<T> eventHandler) where T : EventBase { var eventType = typeof(T); if (!m_GlobalEventHandlers.TryGetValue(eventType, out var handlerList)) return; var eventHandlerHashCode = eventHandler.GetHashCode(); RemoveHandlerWithHashCode(eventHandlerHashCode, handlerList); } public IEnumerable<SearchGlobalEventHandler<T>> GetOrderedGlobalEventHandlers<T>() where T : EventBase { if (!m_GlobalEventHandlers.TryGetValue(typeof(T), out var handlerList)) return Enumerable.Empty<SearchGlobalEventHandler<T>>(); return handlerList .Where(container => container.IsType<T>()) .OrderBy(container => container.priority) .Select(container => container.handler as SearchGlobalEventHandler<T>); } static void RemoveHandlerWithHashCode(int handlerHashCode, List<SearchGlobalEventHandlerContainer> handlerList) { var existingHandlerIndex = handlerList.FindIndex(container => container.handlerHashCode == handlerHashCode); if (existingHandlerIndex >= 0) handlerList.RemoveAt(existingHandlerIndex); } public static bool HandleGlobalEventHandlers<T>(SearchGlobalEventHandlerManager eventManager, T evt) where T : EventBase { var globalEventHandlers = eventManager.GetOrderedGlobalEventHandlers<T>(); foreach (var globalEventHandler in globalEventHandlers) { if (globalEventHandler?.Invoke(evt) ?? false) return true; } return false; } } }
UnityCsReference/Modules/QuickSearch/Editor/UITK/SearchGlobalEventHandlerManager.cs/0
{ "file_path": "UnityCsReference/Modules/QuickSearch/Editor/UITK/SearchGlobalEventHandlerManager.cs", "repo_id": "UnityCsReference", "token_count": 1745 }
447
// 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 UnityEditor.Profiling; using UnityEditor.ShortcutManagement; using UnityEditor.Utils; using UnityEngine; using UnityEngine.Search; using UnityEngine.UIElements; namespace UnityEditor.Search { interface ISearchWindow { void Close(); bool IsPicker(); bool HasFocus(); void Show(); ISearchView ShowWindow(); ISearchView ShowWindow(SearchFlags flags); ISearchView ShowWindow(float width, float height); ISearchView ShowWindow(float width, float height, SearchFlags flags); IEnumerable<SearchItem> FetchItems(); void AddProvidersToMenu(GenericMenu menu); void AddItemsToMenu(GenericMenu menu); } [EditorWindowTitle(title="Search")] class SearchWindow : EditorWindow, ISearchView, ISearchQueryView, ISearchElement, IDisposable, ISearchWindow { internal const float defaultWidth = 700f; internal const float defaultHeight = 450f; private const string k_TogleSyncShortcutName = "Search/Toggle Sync Search View"; private const string k_LastSearchPrefKey = "last_search"; private const string k_SideBarWidthKey = "Search.SidebarWidth"; private const string k_DetailsWidthKey = "Search.DetailsWidth"; private static readonly string k_CheckWindowKeyName = $"{typeof(SearchWindow).FullName}h"; private static EditorWindow s_FocusedWindow; private static SearchViewState s_GlobalViewState = null; private bool m_Disposed = false; private Action m_DebounceOff = null; private SearchMonitorView m_SearchMonitorView; private List<Action> m_SearchEventOffs; private TwoPaneSplitView m_LeftSplitter; private const string k_LeftSplitterViewDataKey = "search-left-splitter__view-data-key"; private TwoPaneSplitView m_RightSplitter; private const string k_RightSplitterViewDataKey = "search-right-splitter__view-data-key"; private SearchView m_SearchView = default; private SearchToolbar m_SearchToolbar; private SearchAutoCompleteWindow m_SearchAutoCompleteWindow; private VisualElement m_SearchQueryPanelContainer; private VisualElement m_DetailsPanelContainer; private IEnumerable<SearchProvider> m_AvailableProviders; [SerializeField] protected int m_ContextHash; [SerializeField] private float m_PreviousItemSize = -1; [SerializeField] protected SearchViewState m_ViewState = null; [SerializeField] protected EditorWindow m_LastFocusedWindow; internal IResultView resultView => m_SearchView.resultView; internal QueryBuilder queryBuilder => m_SearchToolbar.queryBuilder; internal SearchAutoCompleteWindow autoComplete => m_SearchAutoCompleteWindow; internal SearchToolbar searchToolbar => m_SearchToolbar; public Action<SearchItem, bool> selectCallback { get => m_ViewState.selectHandler; set => m_ViewState.selectHandler = value; } Func<SearchItem, bool> ISearchView.filterCallback { get => (item) => m_ViewState.filterHandler?.Invoke(item) ?? true; } Action<SearchItem> ISearchView.trackingCallback => m_ViewState.trackingHandler; public bool searchInProgress => (m_SearchView?.searchInProgress ?? context?.searchInProgress ?? false) || m_DebounceOff != null; public string currentGroup { get => m_SearchView?.currentGroup ?? viewState.group; set => SelectGroup(value); } public SearchViewState state => m_ViewState; protected SearchViewState viewState => m_ViewState; SearchViewState ISearchElement.viewState => m_ViewState; public ISearchQuery activeQuery { get => m_ViewState.activeQuery; set => m_ViewState.activeQuery = value; } public SearchSelection selection => m_SearchView.selection; public SearchContext context => m_ViewState.context; public ISearchList results => m_SearchView.results; public DisplayMode displayMode => m_SearchView.displayMode; public float itemIconSize { get => m_SearchView?.itemSize ?? 0; set { if (m_SearchView != null) m_SearchView.itemSize = value; } } public bool multiselect { get => m_SearchView.multiselect; set => m_SearchView.multiselect = value; } internal string windowId => m_ViewState.sessionId; int ISearchView.totalCount => m_SearchView.totalCount; bool ISearchView.syncSearch { get => m_SearchView.syncSearch; set { if (m_SearchView != null) m_SearchView.syncSearch = value; } } SearchPreviewManager ISearchView.previewManager => m_SearchView.previewManager; public void CreateGUI() { VisualElement body = rootVisualElement; body.style.flexGrow = 1.0f; body.RegisterCallback<KeyDownEvent>(OnGlobalKeyDownEvent, invokePolicy: InvokePolicy.IncludeDisabled, useTrickleDown: TrickleDown.TrickleDown); // Create main layout if (m_ViewState.flags.HasNone(SearchViewFlags.HideSearchBar)) body.Add(m_SearchToolbar = new SearchToolbar("SearchToolbar", this)); else m_SearchView?.RegisterCallback<AttachToPanelEvent>(SetFocusOnViewAttached); body.Add(CreateContent(m_SearchView)); body.Add(new SearchStatusBar("SearchStatusBar", this)); // Don't add it to the body, the SearchAutoCompleteWindow will take care of it when shown. m_SearchAutoCompleteWindow = new SearchAutoCompleteWindow(this, body); } int ISearchView.GetViewId() { return ((ISearchView)m_SearchView).GetViewId(); } private void SetFocusOnViewAttached(AttachToPanelEvent evt) { SelectSearch(); } private void OnGlobalKeyDownEvent(KeyDownEvent evt) { var e = evt.target as VisualElement; if (HandleKeyboardNavigation(e, evt, evt.imguiEvent)) { evt.StopImmediatePropagation(); } } private bool HandleDefaultPressEnter(Event evt) { if (evt.type != EventType.KeyDown) return false; if (evt.modifiers > 0) return false; if (GUIUtility.textFieldInput) return false; if (selection.Count != 0 || results.Count == 0) return false; if (evt.keyCode != KeyCode.KeypadEnter && evt.keyCode != KeyCode.Return) return false; SetSelection(0); evt.Use(); GUIUtility.ExitGUI(); return true; } private bool HandleKeyboardNavigation(VisualElement target, KeyDownEvent evt, Event imguiEvt) { // Note: Inspector done with IMGUI (ex: transform, Light...) can allow TextField editing that is not done through a UIElements.TextElement so // assume all KeyDownEvent coming from UIElements.InspectorElement needs to be handle by the Embedded Inspector. if ((target is TextElement || target?.parent is UIElements.InspectorElement) && !SearchElement.IsPartOf<SearchToolbar>(target)) return false; // Ignore tabbing and line return in quicksearch if (evt.keyCode == KeyCode.None && (evt.character == '\t' || (int)evt.character == 10)) return true; if (SearchGlobalEventHandlerManager.HandleGlobalEventHandlers(m_ViewState.globalEventManager, evt)) return true; if (imguiEvt != null && HandleDefaultPressEnter(imguiEvt)) return true; if (evt is KeyDownEvent && !GUIUtility.textFieldInput) { var ctrl = evt.ctrlKey || evt.commandKey; if (evt.keyCode == KeyCode.Escape) { HandleEscapeKeyDown(evt); return true; } else if (evt.keyCode == KeyCode.F5) { Refresh(); return true; } else if (evt.keyCode == KeyCode.F1) { ToggleQueryBuilder(); return true; } else if (evt.keyCode == KeyCode.F4 && viewState.flags.HasNone(SearchViewFlags.DisableInspectorPreview)) { TogglePanelView(SearchViewFlags.OpenInspectorPreview); return true; } else if (evt.keyCode == KeyCode.F3 && IsSavedSearchQueryEnabled()) { TogglePanelView(SearchViewFlags.OpenLeftSidePanel); return true; } else if (evt.modifiers.HasAny(EventModifiers.Alt) && evt.keyCode == KeyCode.LeftArrow) { string previousGroupId = null; foreach (var group in EnumerateGroups()) { if (previousGroupId != null && group.id == m_SearchView.currentGroup) { SelectGroup(previousGroupId); break; } previousGroupId = group.id; } return true; } else if (evt.modifiers.HasAny(EventModifiers.Alt) && evt.keyCode == KeyCode.RightArrow) { bool selectNext = false; foreach (var group in EnumerateGroups()) { if (selectNext) { SelectGroup(group.id); break; } else if (group.id == m_SearchView.currentGroup) selectNext = true; } return true; } else if (evt.keyCode == KeyCode.Tab && evt.modifiers == EventModifiers.None) { m_SearchAutoCompleteWindow.Show(m_SearchToolbar); return true; } } if (imguiEvt != null && imguiEvt.type == EventType.Used) return true; return false; } protected virtual void HandleEscapeKeyDown(EventBase evt) { if (!docked) { SendEvent(SearchAnalytics.GenericEventType.QuickSearchDismissEsc); selectCallback?.Invoke(null, true); selectCallback = null; CloseSearchWindow(); } else { ClearSearch(); } } private VisualElement CreateContent(SearchView resultView) { var groupBar = !viewState.hideTabs ? new SearchGroupBar("SearchGroupbar", this) : null; var resultContainer = SearchElement.Create<VisualElement>("SearchResultContainer", "search-panel", "search-result-container", "search-splitter__flexed-pane"); if (groupBar != null) resultContainer.Add(groupBar); resultContainer.Add(resultView); m_SearchQueryPanelContainer = new VisualElement() { name = "SearchQueryPanelContainer" }; m_SearchQueryPanelContainer.AddToClassList("search-panel-container"); if (IsSavedSearchQueryEnabled() && m_ViewState.flags.HasAny(SearchViewFlags.OpenLeftSidePanel)) m_SearchQueryPanelContainer.Add(new SearchQueryPanelView("SearchQueryPanel", this, "search-panel", "search-query-panel")); m_DetailsPanelContainer = new VisualElement() { name = "SearchDetailViewContainer" }; m_DetailsPanelContainer.AddToClassList("search-panel-container"); if (m_ViewState.flags.HasAny(SearchViewFlags.OpenInspectorPreview)) m_DetailsPanelContainer.Add(new SearchDetailView("SearchDetailView", this, "search-panel", "search-detail-panel")); m_LeftSplitter = new TwoPaneSplitView(0, EditorPrefs.GetFloat(k_SideBarWidthKey, 120f), TwoPaneSplitViewOrientation.Horizontal) { name = "SearchLeftSidePanels" }; m_LeftSplitter.viewDataKey = k_LeftSplitterViewDataKey; m_LeftSplitter.AddToClassList("search-splitter"); m_LeftSplitter.AddToClassList("search-splitter__flexed-pane"); m_LeftSplitter.Add(m_SearchQueryPanelContainer); m_LeftSplitter.Add(resultContainer); m_RightSplitter = new TwoPaneSplitView(1, EditorPrefs.GetFloat(k_DetailsWidthKey, 160f), TwoPaneSplitViewOrientation.Horizontal) { name = "SearchContent" }; m_RightSplitter.viewDataKey = k_RightSplitterViewDataKey; m_RightSplitter.AddToClassList("search-content"); m_RightSplitter.AddToClassList("search-splitter"); m_RightSplitter.Add(m_LeftSplitter); m_RightSplitter.Add(m_DetailsPanelContainer); m_RightSplitter.RegisterCallback<GeometryChangedEvent>(UpdateLayout); return m_RightSplitter; } private void UpdateLayout(GeometryChangedEvent evt) { if (evt.target is CallbackEventHandler eh) eh.UnregisterCallback<GeometryChangedEvent>(UpdateLayout); UpdateSplitterPanes(); } public void SetSearchText(string searchText, TextCursorPlacement moveCursor = TextCursorPlacement.Default) { SetSearchText(searchText, moveCursor, -1); } public void SetSearchText(string searchText, TextCursorPlacement moveCursor, int cursorInsertPosition) { if (context == null) return; // Always emit event as cursor might have changed even if the text didn't var oldText = context.searchText; m_SearchView.SetSearchText(searchText, moveCursor); Dispatcher.Emit(SearchEvent.SearchTextChanged, new SearchEventPayload(this, oldText, context.searchText, moveCursor, cursorInsertPosition)); if (viewState.queryBuilderEnabled && queryBuilder != null && queryBuilder.BuildQuery() != searchText) { Dispatcher.Emit(SearchEvent.RefreshBuilder, new SearchEventPayload(this)); } } public virtual void Refresh(RefreshFlags flags = RefreshFlags.Default) { m_SearchView?.Refresh(flags); } private void SetContext(SearchContext newContext) { if (context == null || context != newContext) { var searchText = context?.searchText ?? string.Empty; context?.Dispose(); m_ViewState.context = newContext ?? SearchService.CreateContext(searchText); Dispatcher.Emit(SearchEvent.SearchContextChanged, new SearchEventPayload(this)); } m_SearchView?.Reset(); ComputeContextHash(); context.searchView = this; Refresh(); } public void SetSelection(params int[] selection) { m_SearchView.SetSelection(selection); } public void SetColumns(IEnumerable<SearchColumn> columns) { if (viewState.tableConfig == null) throw new NotSupportedException("This result view cannot set columns"); viewState.tableConfig.columns = columns.ToArray(); m_SearchView.resultView.Refresh(RefreshFlags.DisplayModeChanged); } public void AddSelection(params int[] selection) { m_SearchView.AddSelection(selection); } public void ExecuteSearchQuery(ISearchQuery query) { SetSelection(); // Capture previous view flags so we can keep the same state. var preservedViewFlags = viewState.flags & SearchViewFlags.ContextSwitchPreservedMask; var queryBuilderEnabled = viewState.queryBuilderEnabled; var queryContext = CreateQueryContext(query); SetContext(queryContext); viewState.Assign(query.GetViewState(), queryContext); viewState.flags &= ~SearchViewFlags.ContextSwitchPreservedMask; viewState.flags |= preservedViewFlags; viewState.queryBuilderEnabled = queryBuilderEnabled; itemIconSize = viewState.itemSize; if (!viewState.hideTabs && !string.IsNullOrEmpty(viewState.group)) SelectGroup(viewState.group); activeQuery = query; SearchQueryAsset.AddToRecentSearch(query); var evt = CreateEvent(SearchAnalytics.GenericEventType.QuickSearchSavedSearchesExecuted, query.searchText, "", query is SearchQueryAsset ? "project" : "user"); evt.intPayload1 = viewState.tableConfig != null ? 1 : 0; SearchAnalytics.SendEvent(evt); SearchQuery.SaveLastUsedTimeToPropertyDatabase(activeQuery); } private void HandleExecuteSearchQuery(ISearchEvent evt) { if (evt.sourceViewState != m_ViewState) return; var query = evt.GetArgument<ISearchQuery>(0); ExecuteSearchQuery(query); evt.Use(); } protected virtual SearchContext CreateQueryContext(ISearchQuery query) { var providers = context?.GetProviders() ?? SearchService.GetActiveProviders(); var flags = context?.options ?? SearchFlags.Default; if (query.GetViewState() != null) { flags |= (query.GetViewState().searchFlags & (SearchFlags.WantsMore | SearchFlags.Packages)); } return SearchService.CreateContext(SearchUtils.GetMergedProviders(providers, query.GetProviderIds()), query.searchText, flags); } public virtual void ExecuteSelection() { ExecuteSelection(0); } private void ExecuteSelection(int actionIndex) { if (selection.Count == 0) return; // Execute default action var item = selection.First(); if (item.provider.actions.Count > actionIndex) ExecuteAction(item.provider.actions.Skip(actionIndex).First(), selection.ToArray(), !SearchSettings.keepOpen); } public void ExecuteAction(SearchAction action, SearchItem[] items, bool endSearch = true) { m_SearchView.ExecuteAction(action, items, endSearch); } public void ShowItemContextualMenu(SearchItem item, Rect position) { m_SearchView.ShowItemContextualMenu(item, position); } internal virtual void OnEnable() { using (new EditorPerformanceTracker("SearchView.OnEnable")) { minSize = new Vector2(200f, minSize.y); rootVisualElement.name = nameof(SearchWindow); rootVisualElement.AddToClassList("search-window"); SearchElement.AppendStyleSheets(rootVisualElement); hideFlags |= HideFlags.DontSaveInEditor; wantsLessLayoutEvents = true; m_LastFocusedWindow = m_LastFocusedWindow ?? focusedWindow; m_ViewState = s_GlobalViewState ?? m_ViewState ?? SearchViewState.LoadDefaults(); SetContext(m_ViewState.context); LoadSessionSettings(m_ViewState); SearchSettings.SortActionsPriority(); m_SearchMonitorView = SearchMonitor.GetView(); m_SearchView = new SearchView(m_ViewState, GetInstanceID()) { multiselect = true }; UpdateWindowTitle(); SearchSettings.providerActivationChanged += OnProviderActivationChanged; m_SearchEventOffs = new List<Action>() { Dispatcher.On(SearchEvent.ExecuteSearchQuery, HandleExecuteSearchQuery), Dispatcher.On(SearchEvent.SaveUserQuery, HandleSaveUserQuery), Dispatcher.On(SearchEvent.SaveProjectQuery, HandleSaveProjectQuery), Dispatcher.On(SearchEvent.SaveActiveSearchQuery, HandleSaveActiveSearchQuery), Dispatcher.On(SearchEvent.RefreshContent, RefreshContent) }; m_AvailableProviders = (IsPicker() || !context.options.HasFlag(SearchFlags.OpenGlobal)) ? new List<SearchProvider>(context.providers) : SearchService.OrderedProviders; s_GlobalViewState = null; } } void HandleSaveActiveSearchQuery(ISearchEvent evt) { if (evt.sourceViewState != m_ViewState) return; SaveActiveSearchQuery(); } void HandleSaveProjectQuery(ISearchEvent evt) { if (evt.sourceViewState != m_ViewState) return; string savePath = null; if (evt.HasArgument(0)) savePath = evt.GetArgument<string>(0); SaveProjectSearchQuery(savePath); } void HandleSaveUserQuery(ISearchEvent evt) { if (evt.sourceViewState != m_ViewState) return; SaveUserSearchQuery(); } private bool HasCustomTitle() { return viewState.windowTitle != null && !string.IsNullOrEmpty(viewState.windowTitle.text); } internal virtual void OnDisable() { s_FocusedWindow = null; m_DebounceOff?.Invoke(); m_DebounceOff = null; EditorApplication.delayCall -= m_SearchView.DelayTrackSelection; SearchSettings.providerActivationChanged -= OnProviderActivationChanged; try { selectCallback?.Invoke(selection?.FirstOrDefault(), selection == null || selection.Count == 0); } catch { } selectCallback = null; SaveSessionSettings(); m_SearchView.syncSearch = false; m_SearchView?.Dispose(); m_SearchMonitorView.Dispose(); // End search session context.Dispose(); } internal protected virtual bool IsSavedSearchQueryEnabled() { return m_ViewState.hasQueryPanel; } public bool CanSaveQuery() { return !string.IsNullOrWhiteSpace(context.searchQuery); } private void SaveItemCountToPropertyDatabase(bool isSaving) { if (activeQuery == null || m_SearchView == null) return; if (activeQuery.searchText != context.searchText && !isSaving) return; using (var view = SearchMonitor.GetView()) { var recordKey = PropertyDatabase.CreateRecordKey(activeQuery.guid, SearchQuery.k_QueryItemsNumberPropertyName); // Always save the total count, taking the count from the query providers can be misleading. var itemCount = m_SearchView.GetItemCount(null); view.StoreProperty(recordKey, itemCount); Dispatcher.Emit(SearchEvent.SearchQueryItemCountUpdated, new SearchEventPayload(this, activeQuery.guid, itemCount)); } } protected virtual void UpdateAsyncResults() { if (!this) return; m_DebounceOff = null; UpdateWindowTitle(); SaveItemCountToPropertyDatabase(false); } private void RefreshContent(ISearchEvent evt) { if (evt.sourceViewState != viewState) return; m_DebounceOff?.Invoke(); m_DebounceOff = Utils.CallDelayed(UpdateAsyncResults, 0.1d); } protected bool ToggleFilter(string providerId) { var toggledEnabled = !context.IsEnabled(providerId); var provider = SearchService.GetProvider(providerId); if (provider != null && toggledEnabled) { // Force activate a provider we would want to toggle ON SearchService.SetActive(providerId); } if (providerId == m_SearchView.currentGroup) SelectGroup(null); context.SetFilter(providerId, toggledEnabled); if (toggledEnabled && provider == null && !context.providers.Any(p => p.id == providerId)) { // Provider that are not stored in the SearchService, might only exists in the m_AvailableProviders (local providers created directly in the context). var localProvider = m_AvailableProviders.FirstOrDefault(p => p.id == providerId); if (localProvider != null) { var newProviderList = context.GetProviders().Concat(new[] { localProvider }).ToArray(); context.SetProviders(newProviderList); } } Dispatcher.Emit(SearchEvent.FilterToggled, new SearchEventPayload(this, providerId)); SendEvent(SearchAnalytics.GenericEventType.FilterWindowToggle, providerId, context.IsEnabled(providerId).ToString()); Refresh(); return toggledEnabled; } internal void TogglePanelView(SearchViewFlags panelOption) { var hasOptions = !m_ViewState.flags.HasAny(panelOption); SendEvent(SearchAnalytics.GenericEventType.QuickSearchOpenToggleToggleSidePanel, panelOption.ToString(), hasOptions.ToString()); if (hasOptions) m_ViewState.flags |= panelOption; else m_ViewState.flags &= ~panelOption; if (panelOption == SearchViewFlags.OpenLeftSidePanel && IsSavedSearchQueryEnabled()) { SearchSettings.showSavedSearchPanel = hasOptions; SearchSettings.Save(); } UpdateSplitterPanes(); } private void UpdateSplitterPanes() { // We collapse/uncollapse the splitter panes according to the state of the view // (showing left/right side panels). To reduce resource consumption, we also remove the // inner panels when they are hidden. if (IsSavedSearchQueryEnabled() && m_ViewState.flags.HasAny(SearchViewFlags.OpenLeftSidePanel)) { if (m_SearchQueryPanelContainer.childCount == 0) m_SearchQueryPanelContainer.Add(new SearchQueryPanelView("SearchQueryPanel", this, "search-panel", "search-query-panel")); m_LeftSplitter?.UnCollapse(); } else { m_SearchQueryPanelContainer.Clear(); m_LeftSplitter?.CollapseChild(0); } if (m_ViewState.flags.HasAny(SearchViewFlags.OpenInspectorPreview)) { if (m_DetailsPanelContainer.childCount == 0) m_DetailsPanelContainer.Add(new SearchDetailView("SearchDetailView", this, "search-panel", "search-detail-panel")); m_RightSplitter?.UnCollapse(); } else { m_DetailsPanelContainer.Clear(); m_RightSplitter?.CollapseChild(1); } Dispatcher.Emit(SearchEvent.ViewStateUpdated, new SearchEventPayload(this)); } void ISearchWindow.AddItemsToMenu(GenericMenu menu) { if (m_ViewState.isSimplePicker) return; if (!IsPicker()) { menu.AddItem(new GUIContent(L10n.Tr("Preferences")), false, () => SearchUtils.OpenPreferences()); menu.AddSeparator(""); } var savedSearchContent = new GUIContent(L10n.Tr("Searches")); var previewInspectorContent = new GUIContent(L10n.Tr("Inspector")); if (IsSavedSearchQueryEnabled()) menu.AddItem(savedSearchContent, m_ViewState.flags.HasAny(SearchViewFlags.OpenLeftSidePanel), () => TogglePanelView(SearchViewFlags.OpenLeftSidePanel)); if (m_ViewState.flags.HasNone(SearchViewFlags.DisableInspectorPreview)) menu.AddItem(previewInspectorContent, m_ViewState.flags.HasAny(SearchViewFlags.OpenInspectorPreview), () => TogglePanelView(SearchViewFlags.OpenInspectorPreview)); if (m_ViewState.flags.HasNone(SearchViewFlags.DisableBuilderModeToggle)) menu.AddItem(new GUIContent(L10n.Tr($"Query Builder\tF1")), viewState.queryBuilderEnabled, ToggleQueryBuilder); menu.AddItem(new GUIContent(L10n.Tr($"Status Bar")), SearchSettings.showStatusBar, ToggleShowStatusBar); if (IsSavedSearchQueryEnabled() || m_ViewState.flags.HasNone(SearchViewFlags.DisableInspectorPreview)) menu.AddSeparator(""); if (Utils.isDeveloperBuild) { menu.AddItem(new GUIContent(L10n.Tr($"Debug")), context?.options.HasAny(SearchFlags.Debug) ?? false, ToggleDebugQuery); menu.AddItem(new GUIContent(L10n.Tr("Serialize SearchContext")), false, () => SerializeSearchContext()); } if (!IsPicker()) { menu.AddSeparator(""); menu.AddItem(new GUIContent(L10n.Tr($"Keep Open")), SearchSettings.keepOpen, ToggleKeepOpen); } } private void SerializeSearchContext() { var json = EditorJsonUtility.ToJson(context, prettyPrint: true); Debug.Log($"(JSON) Search Context: {context}\r\n{json}"); Debug.Log(Utils.PrintObject($"A. {context}", context)); { var ssvs = new SearchContext(); EditorJsonUtility.FromJsonOverwrite(json, ssvs); Debug.Log(Utils.PrintObject($"B. {ssvs}", ssvs)); } } private void ToggleShowTabs() { var currentTabs = rootVisualElement.Q<SearchGroupBar>(); viewState.hideTabs = !viewState.hideTabs; SearchSettings.hideTabs = viewState.hideTabs; SearchSettings.Save(); if (viewState.hideTabs) currentTabs?.RemoveFromHierarchy(); else if (currentTabs == null) rootVisualElement.Q("SearchResultContainer")?.Insert(0, new SearchGroupBar("SearchGroupbar", this)); SelectGroup(null); Refresh(); } internal void ToggleQueryBuilder() { if (!viewState.hasQueryBuilderToggle) return; SearchSettings.queryBuilder = viewState.queryBuilderEnabled = !viewState.queryBuilderEnabled; SearchSettings.Save(); var evt = CreateEvent(SearchAnalytics.GenericEventType.QuickSearchToggleBuilder, viewState.queryBuilderEnabled.ToString()); evt.intPayload1 = viewState.queryBuilderEnabled ? 1 : 0; SearchAnalytics.SendEvent(evt); Dispatcher.Emit(SearchEvent.RefreshBuilder, new SearchEventPayload(this)); Dispatcher.Emit(SearchEvent.ViewStateUpdated, new SearchEventPayload(this)); } private void ToggleShowStatusBar() { SearchSettings.showStatusBar = !SearchSettings.showStatusBar; Dispatcher.Emit(SearchEvent.ViewStateUpdated, new SearchEventPayload(this)); SendEvent(SearchAnalytics.GenericEventType.PreferenceChanged, nameof(SearchSettings.showStatusBar), SearchSettings.showStatusBar.ToString()); } private void ToggleKeepOpen() { SearchSettings.keepOpen = !SearchSettings.keepOpen; SendEvent(SearchAnalytics.GenericEventType.PreferenceChanged, nameof(SearchSettings.keepOpen), SearchSettings.keepOpen.ToString()); } private void ToggleDebugQuery() { if (context.debug) { SearchSettings.defaultFlags &= ~SearchFlags.Debug; context.debug = false; } else { SearchSettings.defaultFlags |= SearchFlags.Debug; context.debug = true; } Refresh(); } protected virtual void UpdateWindowTitle() { if (HasCustomTitle()) titleContent = viewState.windowTitle; else { titleContent.image = activeQuery?.thumbnail ?? Icons.quickSearchWindow; if (!titleContent.image) titleContent.image = Icons.quickSearchWindow; if (context == null) return; if (m_SearchView == null || m_SearchView.results.Count == 0) titleContent.text = L10n.Tr("Search"); else titleContent.text = $"Search ({m_SearchView.results.Count})"; } if (Utils.isDeveloperBuild) { if (context?.options.HasAny(SearchFlags.Debug) ?? false) titleContent.tooltip = $"{Profiling.EditorPerformanceTracker.GetAverageTime("SearchWindow.Paint") * 1000:0.#} ms"; if (Utils.IsRunningTests()) titleContent.text = $"[TEST] {titleContent.text}"; } } IEnumerable<SearchQueryError> ISearchView.GetAllVisibleErrors() { return m_SearchView.GetAllVisibleErrors(); } public void SelectSearch() { FocusSearch(); if (m_SearchToolbar != null) m_SearchToolbar.searchField.FocusSearchField(); } public void FocusSearch() { rootVisualElement.Query<SearchElement>().Visible().Where(e => e.focusable).First()?.Focus(); } internal protected void CloseSearchWindow() { if (s_FocusedWindow) s_FocusedWindow.Focus(); Utils.CallDelayed(Close); } IEnumerable<IGroup> ISearchView.EnumerateGroups() { return EnumerateGroups(); } private IEnumerable<IGroup> EnumerateGroups() { return m_SearchView.EnumerateGroups(); } void ISearchWindow.AddProvidersToMenu(GenericMenu menu) { var allEnabledProviders = m_AvailableProviders.Where(p => context.IsEnabled(p.id)); var singleProviderEnabled = allEnabledProviders.Count() == 1 ? allEnabledProviders.First() : null; foreach (var p in m_AvailableProviders) { var filterContent = new GUIContent($"{p.name} ({p.filterId})"); if (singleProviderEnabled == p) { menu.AddDisabledItem(filterContent, context.IsEnabled(p.id)); } else { menu.AddItem(filterContent, context.IsEnabled(p.id), () => ToggleFilter(p.id)); } } } internal void SelectGroup(string groupId) { if (m_SearchView.currentGroup == groupId) return; var selectedProvider = SearchService.GetProvider(groupId); if (selectedProvider != null && selectedProvider.showDetailsOptions.HasAny(ShowDetailsOptions.ListView)) { if (m_PreviousItemSize == -1f) m_PreviousItemSize = itemIconSize; itemIconSize = 1; } else if (m_PreviousItemSize >= 0f) { itemIconSize = m_PreviousItemSize; m_PreviousItemSize = -1f; } var evt = SearchAnalytics.GenericEvent.Create(windowId, SearchAnalytics.GenericEventType.QuickSearchSwitchTab, groupId ?? string.Empty); evt.stringPayload1 = m_SearchView.currentGroup; evt.intPayload1 = m_SearchView.GetGroupById(groupId)?.count ?? 0; SearchAnalytics.SendEvent(evt); m_SearchView.currentGroup = groupId; } protected void ClearSearch() { SendEvent(SearchAnalytics.GenericEventType.QuickSearchClearSearch); SetSearchText(IsPicker() ? m_ViewState.initialQuery : string.Empty); SetSelection(); SelectSearch(); Dispatcher.Emit(SearchEvent.RefreshBuilder, new SearchEventPayload(this)); } public virtual bool IsPicker() { return false; } public void SaveActiveSearchQuery() { if (activeQuery is SearchQueryAsset sqa) { var searchQueryPath = AssetDatabase.GetAssetPath(sqa); if (!string.IsNullOrEmpty(searchQueryPath)) { SaveSearchQueryFromContext(searchQueryPath, false); } } else if (activeQuery is SearchQuery sq) { sq.Set(viewState); SearchQuery.SaveSearchQuery(sq); SaveItemCountToPropertyDatabase(true); } } void ISearchQueryView.SaveUserSearchQuery() { SaveUserSearchQuery(); } private void SaveUserSearchQuery() { var query = SearchQuery.AddUserQuery(viewState); AddNewQuery(query); } void ISearchQueryView.SaveProjectSearchQuery() { SaveProjectSearchQuery(); } private void SaveProjectSearchQuery(in string path = null) { var initialFolder = SearchSettings.GetFullQueryFolderPath(); var searchQueryFileName = SearchQueryAsset.GetQueryName(context.searchQuery); var searchQueryPath = string.IsNullOrWhiteSpace(path) ? EditorUtility.SaveFilePanel("Save search query...", initialFolder, searchQueryFileName, "asset") : path; if (string.IsNullOrEmpty(searchQueryPath)) return; if (!SearchUtils.ValidateAssetPath(ref searchQueryPath, ".asset", out var errorMessage)) { Debug.LogWarning($"Save Search Query has failed. {errorMessage}"); return; } SearchSettings.queryFolder = Utils.CleanPath(Path.GetDirectoryName(searchQueryPath)); SaveSearchQueryFromContext(searchQueryPath, true); } private void SaveSearchQueryFromContext(string searchQueryPath, bool newQuery) { try { var searchQuery = AssetDatabase.LoadAssetAtPath<SearchQueryAsset>(searchQueryPath) ?? SearchQueryAsset.Create(context); if (!searchQuery) throw new Exception($"Failed to create search query asset {searchQueryPath}"); var folder = Utils.CleanPath(Path.GetDirectoryName(searchQueryPath)); var queryName = Path.GetFileNameWithoutExtension(searchQueryPath); var newContext = new SearchContext(context); searchQuery.viewState ??= new SearchViewState(newContext); searchQuery.viewState.Assign(viewState); if (SearchQueryAsset.SaveQuery(searchQuery, context, viewState, folder, queryName) && newQuery) { Selection.activeObject = searchQuery; AddNewQuery(searchQuery); } else SaveItemCountToPropertyDatabase(true); } catch { Debug.LogError($"Failed to save search query at {searchQueryPath}"); } } private void AddNewQuery(ISearchQuery newQuery) { SearchSettings.AddRecentSearch(newQuery.searchText); SearchQueryAsset.ResetSearchQueryItems(); activeQuery = newQuery; SendNewQueryAnalyticsEvent(newQuery); if (IsSavedSearchQueryEnabled() && m_ViewState.flags.HasNone(SearchViewFlags.OpenLeftSidePanel)) TogglePanelView(SearchViewFlags.OpenLeftSidePanel); SaveItemCountToPropertyDatabase(true); } void SendNewQueryAnalyticsEvent(ISearchQuery newQuery) { SearchAnalytics.GenericEvent evt = default; if (newQuery is SearchQueryAsset sqa) evt = CreateEvent(SearchAnalytics.GenericEventType.QuickSearchCreateSearchQuery, sqa.searchText, sqa.filePath, "project"); else if (newQuery is SearchQuery sq && SearchQuery.IsUserQuery(sq)) evt = CreateEvent(SearchAnalytics.GenericEventType.QuickSearchCreateSearchQuery, sq.searchText, "", "user"); if (!string.IsNullOrEmpty(evt.windowId)) { evt.intPayload1 = newQuery.GetSearchTable() != null ? 1 : 0; SearchAnalytics.SendEvent(evt); } } protected virtual void ComputeContextHash() { m_ContextHash = context.GetHashCode(); if (context.options.HasAny(SearchFlags.FocusContext)) { var contextualProvider = GetContextualProvider(); if (contextualProvider != null) m_ContextHash = Utils.CombineHashCodes(m_ContextHash, contextualProvider.id.GetHashCode()); } m_ContextHash = Utils.CombineHashCodes(m_ContextHash, GetType().Name.GetHashCode()); if (context.filterType != null) m_ContextHash = Utils.CombineHashCodes(m_ContextHash, context.filterType.Name.GetHashCode()); if (context.runtimeContext != null && !string.IsNullOrEmpty(context.runtimeContext.contextId)) m_ContextHash = Utils.CombineHashCodes(m_ContextHash, context.runtimeContext.contextId.GetHashCode()); } protected void UpdateViewState(SearchViewState args) { if (args.hideAllGroup && (args.group == null || string.Equals(GroupedSearchList.allGroupId, args.group, StringComparison.Ordinal))) args.group = args.context?.GetProviders().FirstOrDefault()?.id; if (context?.options.HasAny(SearchFlags.Expression) ?? false) args.itemSize = (int)DisplayMode.Table; } protected virtual void LoadSessionSettings(SearchViewState args) { string loadGroup = null; if (!Utils.IsRunningTests()) { RestoreSearchText(args); if (args.flags.HasNone(SearchViewFlags.OpenInspectorPreview | SearchViewFlags.OpenLeftSidePanel | SearchViewFlags.HideSearchBar)) { if (SearchSettings.GetScopeValue(nameof(SearchViewFlags.OpenInspectorPreview), m_ContextHash, 0) != 0) args.flags |= SearchViewFlags.OpenInspectorPreview; if (SearchSettings.showSavedSearchPanel) args.flags |= SearchViewFlags.OpenLeftSidePanel; } loadGroup = SearchSettings.GetScopeValue(nameof(m_SearchView.currentGroup), m_ContextHash, args.group); } else if (!string.IsNullOrEmpty(args.searchText)) { args.flags |= SearchViewFlags.DisableQueryHelpers; } if (context.options.HasAny(SearchFlags.FocusContext)) { var contextualProvider = GetContextualProvider(); if (contextualProvider != null) loadGroup = contextualProvider.id; } args.group = args.hideTabs ? null : (loadGroup ?? args.group); UpdateViewState(args); } protected virtual void RestoreSearchText(SearchViewState args) { if (!args.ignoreSaveSearches && args.context != null && string.IsNullOrEmpty(args.context.searchText)) { args.searchText = SearchSettings.GetScopeValue(k_LastSearchPrefKey, m_ContextHash, "").TrimStart(); if (args.context != null) { args.context.searchText = args.searchText; SearchSettings.ApplyContextOptions(args.context); } } } protected virtual void SaveSessionSettings() { SearchSettings.SetScopeValue(k_LastSearchPrefKey, m_ContextHash, context.searchText.TrimStart()); SearchSettings.SetScopeValue(nameof(SearchViewFlags.OpenInspectorPreview), m_ContextHash, m_ViewState.flags.HasAny(SearchViewFlags.OpenInspectorPreview) ? 1 : 0); if (m_SearchView != null) SearchSettings.SetScopeValue(nameof(m_SearchView.currentGroup), m_ContextHash, viewState.group); SearchSettings.Save(); } private SearchAnalytics.GenericEvent CreateEvent(SearchAnalytics.GenericEventType category, string name = null, string message = null, string description = null) { var e = SearchAnalytics.GenericEvent.Create(windowId, category, name); e.message = message; e.description = description; return e; } protected void SendEvent(SearchAnalytics.GenericEventType category, string name = null, string message = null, string description = null) { SearchAnalytics.SendEvent(windowId, category, name, message, description); } protected virtual void Dispose(bool disposing) { if (m_Disposed) return; if (disposing) Close(); m_Disposed = true; } public void Dispose() { Dispose(true); } private SearchProvider GetContextualProvider() { return context.providers.FirstOrDefault(p => p.active && (p.isEnabledForContextualSearch?.Invoke() ?? false)); } private void OnProviderActivationChanged(string providerId, bool isActive) { // If a provider was enabled in the settings, we do not want to mess with the current context. User might have disabled it in the CONTEXT for a reason. if (isActive) return; // Already disabled if (!context.IsEnabled(providerId)) return; ToggleFilter(providerId); } // TODO: Use ISearchWindow when possible public static SearchWindow Create(SearchFlags flags = SearchFlags.OpenDefault) { return Create<SearchWindow>(flags); } public static SearchWindow Create<T>(SearchFlags flags = SearchFlags.OpenDefault) where T : SearchWindow { return Create<T>(null, null, flags); } public static SearchWindow Create(SearchContext context, string topic = "Unity", SearchFlags flags = SearchFlags.OpenDefault) { return Create<SearchWindow>(context, topic, flags); } public static SearchWindow Create<T>(SearchContext context, string topic = "Unity", SearchFlags flags = SearchFlags.OpenDefault) where T : SearchWindow { context = context ?? SearchService.CreateContext(""); if (context != null) context.options |= flags; var viewState = new SearchViewState(context) { title = topic }; return Create<T>(viewState.LoadDefaults()); } public static ISearchWindow Create(SearchViewState viewArgs) { return Create<SearchWindow>(viewArgs); } public static T Create<T>(SearchViewState viewArgs) where T : SearchWindow { s_GlobalViewState = viewArgs; s_FocusedWindow = focusedWindow; var context = viewArgs.context; var flags = viewArgs.context?.options ?? SearchFlags.OpenDefault; SearchWindow searchWindow; if (flags.HasAny(SearchFlags.ReuseExistingWindow) && HasOpenInstances<T>()) { searchWindow = Resources.FindObjectsOfTypeAll<SearchWindow>() .Where(w => w.viewState.searchFlags.HasAny(SearchFlags.ReuseExistingWindow) || (w.context?.options.HasAny(SearchFlags.ReuseExistingWindow) ?? false)) .FirstOrDefault(); if (!searchWindow) { searchWindow = CreateInstance<T>(); } else if (context != null) { if (context.empty) context.searchText = searchWindow.context?.searchText ?? string.Empty; searchWindow.SetContext(context); } } else { searchWindow = CreateInstance<T>(); } return (T)searchWindow; } internal static SearchWindow Open(float width = defaultWidth, float height= defaultHeight, SearchFlags flags = SearchFlags.OpenDefault) { return Create(flags).ShowWindow(width, height, flags); } [MenuItem("Edit/Search/Search All... %k", priority = 141)] internal static ISearchView OpenDefaultQuickSearch() { var window = Open(flags: SearchFlags.OpenGlobal); SearchAnalytics.SendEvent(window.state.sessionId, SearchAnalytics.GenericEventType.QuickSearchOpen, "Default"); return window; } public ISearchView ShowWindow() { return ShowWindow(defaultWidth, defaultHeight, SearchFlags.OpenDefault); } public ISearchView ShowWindow(SearchFlags flags) { return ShowWindow(defaultWidth, defaultHeight, flags); } public ISearchView ShowWindow(float width, float height) { return ShowWindow(width, height, SearchFlags.OpenDefault); } ISearchView ISearchWindow.ShowWindow(float width, float height, SearchFlags flags) { return ShowWindow(width, height, flags); } public SearchWindow ShowWindow(float width, float height, SearchFlags flags) { using (new EditorPerformanceTracker("SearchView.ShowWindow")) { var windowSize = new Vector2(width, height); if (flags.HasAny(SearchFlags.Dockable) && viewState.flags.HasNone(SearchViewFlags.Borderless)) { bool firstOpen = Utils.IsRunningTests() || !EditorPrefs.HasKey(k_CheckWindowKeyName); Show(true); if (firstOpen) { var centeredPosition = Utils.GetMainWindowCenteredPosition(windowSize); position = centeredPosition; } else if (!firstOpen && !docked) { var newWindow = this; var existingWindow = Resources.FindObjectsOfTypeAll<SearchWindow>().FirstOrDefault(w => w != newWindow); if (existingWindow) { var cascadedWindowPosition = existingWindow.position.position; cascadedWindowPosition += new Vector2(30f, 30f); position = new Rect(cascadedWindowPosition, position.size); } } } else { this.ShowDropDown(windowSize); } Focus(); return this; } } void ISearchView.SetupColumns(IList<SearchField> fields) { m_SearchView.SetupColumns(fields); } [CommandHandler("OpenQuickSearch")] internal static void OpenQuickSearchCommand(CommandExecuteContext c) { OpenDefaultQuickSearch(); } [MenuItem("Window/Search/New Window", priority = 0)] public static void OpenNewWindow() { var window = Open(flags: SearchFlags.OpenDefault); SearchAnalytics.SendEvent(window.state.sessionId, SearchAnalytics.GenericEventType.QuickSearchOpen, "NewWindow"); } [Shortcut("Help/Search Transient Window")] public static void OpenPopupWindow() { if (SearchService.ShowWindow(defaultWidth: 600, defaultHeight: 400, dockable: false) is SearchWindow window) SearchAnalytics.SendEvent(window.windowId, SearchAnalytics.GenericEventType.QuickSearchOpen, "PopupWindow"); } [CommandHandler("OpenQuickSearchInContext")] internal static void OpenQuickSearchInContextCommand(CommandExecuteContext c) { var query = c.GetArgument<string>(0); var sourceContext = c.GetArgument<string>(1); var wasReused = HasOpenInstances<SearchWindow>(); var flags = SearchFlags.OpenContextual | SearchFlags.ReuseExistingWindow; var context = SearchService.CreateContext(query); context.options |= flags; var viewState = new SearchViewState(context) { title = null }; var ignoreRestoreContext = c.GetArgument(2, false); viewState.ignoreSaveSearches = ignoreRestoreContext; var searchWindow = Create(viewState) as SearchWindow; SearchProvider contextualProvider = null; if (wasReused) contextualProvider = searchWindow.GetContextualProvider(); searchWindow.ShowWindow(flags: flags); if (contextualProvider != null) searchWindow.SelectGroup(contextualProvider.id); searchWindow.SendEvent(SearchAnalytics.GenericEventType.QuickSearchJumpToSearch, searchWindow.currentGroup, sourceContext); ((ISearchView)searchWindow).syncSearch = true; c.result = true; } [Shortcut("Help/Search Contextual")] internal static void OpenContextual() { Open(flags: SearchFlags.OpenContextual); } internal void ForceTrackSelection() { m_SearchView.DelayTrackSelection(); } protected virtual IEnumerable<SearchItem> FetchItems() { return Enumerable.Empty<SearchItem>(); } IEnumerable<SearchItem> ISearchWindow.FetchItems() { return FetchItems(); } bool ISearchWindow.HasFocus() { return hasFocus; } [WindowAction] internal static WindowAction CreateSearchHelpWindowAction() { // Developer-mode render doc button to enable capturing any HostView content/panels var action = WindowAction.CreateWindowActionButton("HelpSearch", OpenSearchHelp, null, ContainerWindow.kButtonWidth + 1, Icons.help); action.validateHandler = (window, _) => window && window.GetType() == typeof(SearchWindow); return action; } internal static string GetHelpURL() { return Help.FindHelpNamed("search-overview"); } private static void OpenSearchHelp(EditorWindow window, WindowAction action) { var windowId = (window as SearchWindow)?.windowId ?? null; SearchAnalytics.SendEvent(windowId, SearchAnalytics.GenericEventType.QuickSearchOpenDocLink); EditorUtility.OpenWithDefaultApp(GetHelpURL()); } } }
UnityCsReference/Modules/QuickSearch/Editor/UITK/SearchWindow.cs/0
{ "file_path": "UnityCsReference/Modules/QuickSearch/Editor/UITK/SearchWindow.cs", "repo_id": "UnityCsReference", "token_count": 25454 }
448
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License // #define SCENE_TEMPLATE_ANALYTICS_LOGGING using System; using System.Collections.Generic; using System.Linq; using UnityEngine.Analytics; namespace UnityEditor.SceneTemplate { internal static class SceneTemplateAnalytics { const string vendorKey = "unity.scene-template"; [Serializable] internal class AnalyticDepInfo { public AnalyticDepInfo(DependencyInfo info) { dependencyType = info.dependency.GetType().ToString(); _instantiationMode = info.instantiationMode; instantiationMode = Enum.GetName(typeof(TemplateInstantiationMode), info.instantiationMode); count = 1; } internal TemplateInstantiationMode _instantiationMode; public string dependencyType; public int count; public string instantiationMode; } internal static bool FillAnalyticDepInfos(SceneTemplateAsset template, List<AnalyticDepInfo> infos) { if (template.dependencies == null) return false; var hasCloneableDependencies = false; var tempDepInfos = new Dictionary<string, List<AnalyticDepInfo>>(); if (template.dependencies != null) { foreach (var dep in template.dependencies) { if (dep.instantiationMode == TemplateInstantiationMode.Clone) hasCloneableDependencies = true; if (!dep.dependency || dep.dependency == null) continue; var typeName = dep.dependency.GetType().FullName; if (tempDepInfos.TryGetValue(typeName, out var infosPerType)) { var foundInfo = infosPerType.Find(info => info._instantiationMode == dep.instantiationMode); if (foundInfo != null) { foundInfo.count++; } else { infosPerType.Add(new AnalyticDepInfo(dep)); } } else { infosPerType = new List<AnalyticDepInfo>(); infosPerType.Add(new AnalyticDepInfo(dep)); tempDepInfos.Add(typeName, infosPerType); } } } foreach (var kvp in tempDepInfos) { foreach (var depInfo in kvp.Value) { infos.Add(depInfo); } } return hasCloneableDependencies; } internal enum SceneInstantiationType { NewSceneMenu, TemplateDoubleClick, Scripting, EmptyScene, DefaultScene } [Serializable] internal class SceneInstantiationEvent : IAnalytic.IData { private DateTime m_StartTime; public long elapsedTimeMs => (long)(DateTime.Now - m_StartTime).TotalMilliseconds; public string sceneName; public List<AnalyticDepInfo> dependencyInfos = new List<AnalyticDepInfo>(); public string instantiationType; public long duration; public bool isCancelled; public bool additive; public bool hasCloneableDependencies; public SceneInstantiationEvent(SceneTemplateAsset template, SceneInstantiationType instantiationType) { this.instantiationType = Enum.GetName(typeof(SceneInstantiationType), instantiationType); sceneName = AssetDatabase.GetAssetPath(template.templateScene); hasCloneableDependencies = FillAnalyticDepInfos(template, dependencyInfos); m_StartTime = DateTime.Now; } public SceneInstantiationEvent(SceneInstantiationType instantiationType) { this.instantiationType = Enum.GetName(typeof(SceneInstantiationType), instantiationType); m_StartTime = DateTime.Now; } public void Done() { if (duration == 0) duration = elapsedTimeMs; } } [AnalyticInfo(eventName: "SceneInstantiationEvent", vendorKey: vendorKey)] internal class SceneInstantiationEventAnalytic : IAnalytic { public SceneInstantiationEventAnalytic(SceneInstantiationEvent data) { m_data = data; } public bool TryGatherData(out IAnalytic.IData data, out Exception error) { error = null; data = m_data; return data != null; } private SceneInstantiationEvent m_data = null; } internal enum TemplateCreationType { CreateFromTargetSceneMenu, SaveCurrentSceneAsTemplateMenu, Scripting } [Serializable] internal class SceneTemplateCreationEvent : IAnalytic.IData { public string sceneName; public List<AnalyticDepInfo> dependencyInfos = new List<AnalyticDepInfo>(); public string templateCreationType; public int numberOfTemplatesInProject; public bool hasCloneableDependencies; public void SetData(SceneTemplateAsset template, TemplateCreationType templateCreationType) { this.templateCreationType = Enum.GetName(typeof(TemplateCreationType), templateCreationType); sceneName = AssetDatabase.GetAssetPath(template.templateScene); hasCloneableDependencies = FillAnalyticDepInfos(template, dependencyInfos); numberOfTemplatesInProject = SceneTemplateUtils.GetSceneTemplates().Count(); } } [AnalyticInfo(eventName: "SceneTemplateCreationEvent", vendorKey: vendorKey)] internal class SceneTemplateCreationEventAnalytic : IAnalytic { public SceneTemplateCreationEventAnalytic(SceneTemplateCreationEvent data) { m_data = data; } public bool TryGatherData(out IAnalytic.IData data, out Exception error) { error = null; data = m_data; return data != null; } private SceneTemplateCreationEvent m_data = null; } internal static string Version; static SceneTemplateAnalytics() { } internal static void SendSceneInstantiationEvent(SceneInstantiationEvent evt) { evt.Done(); SceneInstantiationEventAnalytic analytic = new SceneInstantiationEventAnalytic(evt); EditorAnalytics.SendAnalytic(analytic); } internal static void SendSceneTemplateCreationEvent(SceneTemplateCreationEvent evt) { SceneTemplateCreationEventAnalytic analytic = new SceneTemplateCreationEventAnalytic(evt); EditorAnalytics.SendAnalytic(analytic); } } }
UnityCsReference/Modules/SceneTemplateEditor/SceneTemplateAnalytics.cs/0
{ "file_path": "UnityCsReference/Modules/SceneTemplateEditor/SceneTemplateAnalytics.cs", "repo_id": "UnityCsReference", "token_count": 3615 }
449
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEditor.Overlays; using UnityEditorInternal; using UnityEditor.Snap; using UnityEngine; using UnityEngine.UIElements; using FrameCapture = UnityEngine.Apple.FrameCapture; using FrameCaptureDestination = UnityEngine.Apple.FrameCaptureDestination; namespace UnityEditor.Toolbars { [EditorToolbarElement("SceneView/Common Camera Mode", typeof(SceneView))] sealed class CommonCameraModeElement : VisualElement, IAccessContainerWindow { public EditorWindow containerWindow { get; set; } SceneView sceneView => containerWindow as SceneView; static readonly string s_UssClassName_Wireframe = "cameramode-wireframe"; static readonly string s_UssClassName_ShadedWireframe = "cameramode-shadedwireframe"; static readonly string s_UssClassName_Unlit = "cameramode-unlit"; static readonly string s_UssClassName_Shaded = "cameramode-shaded"; readonly EditorToolbarToggle m_WireframeButton; readonly EditorToolbarToggle m_ShadedWireframeButton; readonly EditorToolbarToggle m_UnlitButton; readonly EditorToolbarToggle m_ShadedButton; readonly VisualElement m_UIElementsRoot; public CommonCameraModeElement() { name = "CommonCameraModes"; EditorToolbarUtility.SetupChildrenAsButtonStrip(this); SceneViewToolbarStyles.AddStyleSheets(this); Add(m_UIElementsRoot = new VisualElement()); m_UIElementsRoot.AddToClassList("toolbar-contents"); m_UIElementsRoot.Add(m_WireframeButton = new EditorToolbarToggle { name = "Wireframe", tooltip = "Wireframe Draw Mode", }); m_WireframeButton.AddToClassList(s_UssClassName_Wireframe); m_WireframeButton.RegisterValueChangedCallback((evt) => { sceneView.SwitchToRenderMode(DrawCameraMode.Wireframe); }); m_UIElementsRoot.Add(m_ShadedWireframeButton = new EditorToolbarToggle { name = "Shaded Wireframe", tooltip = "Shaded Wireframe Draw Mode", }); m_ShadedWireframeButton.AddToClassList(s_UssClassName_ShadedWireframe); m_ShadedWireframeButton.RegisterValueChangedCallback((evt) => { sceneView.SwitchToRenderMode(DrawCameraMode.TexturedWire); }); m_UIElementsRoot.Add(m_UnlitButton = new EditorToolbarToggle { name = "Unlit", tooltip = "Unlit Draw Mode", }); m_UnlitButton.AddToClassList(s_UssClassName_Unlit); m_UnlitButton.RegisterValueChangedCallback((evt) => { sceneView.SwitchToUnlit(); }); m_UIElementsRoot.Add(m_ShadedButton = new EditorToolbarToggle { name = "Shaded", tooltip = "Shaded Draw Mode", }); m_ShadedButton.AddToClassList(s_UssClassName_Shaded); m_ShadedButton.RegisterValueChangedCallback((evt) => { sceneView.SwitchToRenderMode(DrawCameraMode.Textured); }); EditorToolbarUtility.SetupChildrenAsButtonStrip(m_UIElementsRoot); RegisterCallback<AttachToPanelEvent>(OnAttachedToPanel); RegisterCallback<DetachFromPanelEvent>(OnDetachedFromPanel); } void OnAttachedToPanel(AttachToPanelEvent evt) { sceneView.onCameraModeChanged += OnCameraModeChanged; sceneView.debugDrawModesUseInteractiveLightBakingDataChanged += OnUseInteractiveLightBakingDataChanged; sceneView.sceneLightingChanged += OnSceneLightingChanged; ValidateShadingMode(sceneView.cameraMode.drawMode); } void OnDetachedFromPanel(DetachFromPanelEvent evt) { sceneView.onCameraModeChanged -= OnCameraModeChanged; sceneView.debugDrawModesUseInteractiveLightBakingDataChanged -= OnUseInteractiveLightBakingDataChanged; sceneView.sceneLightingChanged -= OnSceneLightingChanged; } void OnCameraModeChanged(SceneView.CameraMode mode) => ValidateShadingMode(mode.drawMode); void OnSceneLightingChanged(bool lit) { m_UnlitButton.SetValueWithoutNotify(!lit); ValidateShadingMode(sceneView.cameraMode.drawMode); } void OnUseInteractiveLightBakingDataChanged(bool useInteractiveLightBakingData) { ValidateShadingMode(sceneView.cameraMode.drawMode); } // Given the current DrawCameraMode, make sure the state of this toolbar is correct. void ValidateShadingMode(DrawCameraMode mode) { m_WireframeButton.SetValueWithoutNotify(false); m_ShadedWireframeButton.SetValueWithoutNotify(false); m_UnlitButton.SetValueWithoutNotify(false); m_ShadedButton.SetValueWithoutNotify(false); switch (mode) { case DrawCameraMode.Wireframe: m_WireframeButton.SetValueWithoutNotify(true); break; case DrawCameraMode.TexturedWire: m_ShadedWireframeButton.SetValueWithoutNotify(true); break; case DrawCameraMode.Textured when !sceneView.sceneLighting: m_UnlitButton.SetValueWithoutNotify(true); break; case DrawCameraMode.Textured: m_ShadedButton.SetValueWithoutNotify(true); break; default: break; } } } [EditorToolbarElement("SceneView/Camera Mode", typeof(SceneView))] sealed class CameraModeElement : EditorToolbarDropdownToggle, IAccessContainerWindow { public EditorWindow containerWindow { get; set; } SceneView sceneView => containerWindow as SceneView; static readonly string s_UssClassName_Debug = "cameramode-debug"; public CameraModeElement() { name = "CameraModeDropDown"; tooltip = L10n.Tr("Debug Draw Mode"); dropdownClicked += () => PopupWindow.Show(worldBound, new SceneRenderModeWindow(sceneView)); this.RegisterValueChangedCallback((evt) => sceneView.ToggleLastDebugDrawMode()); RegisterCallback<AttachToPanelEvent>(OnAttachedToPanel); RegisterCallback<DetachFromPanelEvent>(OnDetachedFromPanel); AddToClassList(s_UssClassName_Debug); SceneViewToolbarStyles.AddStyleSheets(this); } void OnAttachedToPanel(AttachToPanelEvent evt) { sceneView.onCameraModeChanged += OnCameraModeChanged; OnCameraModeChanged(sceneView.cameraMode); //Settings the icon display explicitly as this is set to DisplayStyle.Flex when icon = null //Here the icon is set using USS so on the C# side icon = null var iconElement = this.Q<Image>(); iconElement.style.display = DisplayStyle.Flex; } void OnDetachedFromPanel(DetachFromPanelEvent evt) { sceneView.onCameraModeChanged -= OnCameraModeChanged; } void OnCameraModeChanged(SceneView.CameraMode mode) { // These modes are handled in CommonCameraModeElement if (mode.drawMode == DrawCameraMode.Textured || mode.drawMode == DrawCameraMode.Wireframe || mode.drawMode == DrawCameraMode.TexturedWire) { SetValueWithoutNotify(false); } else { SetValueWithoutNotify(true); } } } [EditorToolbarElement("SceneView/2D", typeof(SceneView))] sealed class In2DModeElement : EditorToolbarToggle, IAccessContainerWindow { public EditorWindow containerWindow { get; set; } SceneView sceneView => containerWindow as SceneView; public In2DModeElement() { name = "SceneView2D"; tooltip = L10n.Tr("When toggled on, the Scene is in 2D view. When toggled off, the Scene is in 3D view."); this.RegisterValueChangedCallback(evt => sceneView.in2DMode = evt.newValue); RegisterCallback<AttachToPanelEvent>(OnAttachedToPanel); RegisterCallback<DetachFromPanelEvent>(OnDetachFromPanel); SceneViewToolbarStyles.AddStyleSheets(this); } void OnAttachedToPanel(AttachToPanelEvent evt) { value = sceneView.in2DMode; sceneView.modeChanged2D += OnModeChanged; } void OnDetachFromPanel(DetachFromPanelEvent evt) { sceneView.modeChanged2D -= OnModeChanged; } void OnModeChanged(bool enabled) { value = enabled; } } [EditorToolbarElement("SceneView/Audio", typeof(SceneView))] sealed class SceneAudioElement : EditorToolbarToggle, IAccessContainerWindow { public EditorWindow containerWindow { get; set; } SceneView sceneView => containerWindow as SceneView; public SceneAudioElement() { name = "SceneviewAudio"; tooltip = "Toggle audio on or off."; RegisterCallback<AttachToPanelEvent>(OnAttachedToPanel); RegisterCallback<DetachFromPanelEvent>(OnDetachFromPanel); this.RegisterValueChangedCallback(evt => sceneView.audioPlay = evt.newValue); SceneViewToolbarStyles.AddStyleSheets(this); } void OnAttachedToPanel(AttachToPanelEvent evt) { value = sceneView.audioPlay; sceneView.sceneAudioChanged += SceneViewOnsceneAudioChanged; EditorApplication.update += CheckAvailability; } void OnDetachFromPanel(DetachFromPanelEvent evt) { sceneView.sceneAudioChanged -= SceneViewOnsceneAudioChanged; EditorApplication.update -= CheckAvailability; } void SceneViewOnsceneAudioChanged(bool audio) { value = audio; } void CheckAvailability() { SetEnabled(!EditorApplication.isPlaying); } } [EditorToolbarElement("SceneView/Fx", typeof(SceneView))] sealed class SceneFxElement : EditorToolbarDropdownToggle, IAccessContainerWindow { public EditorWindow containerWindow { get; set; } SceneView sceneView => containerWindow as SceneView; public SceneFxElement() { name = "SceneviewFx"; tooltip = L10n.Tr("Toggle skybox, fog, and various other effects."); dropdownClicked += () => PopupWindow.Show(worldBound, new SceneFXWindow(sceneView)); this.RegisterValueChangedCallback(delegate(ChangeEvent<bool> evt) { sceneView.sceneViewState.fxEnabled = evt.newValue; }); RegisterCallback<AttachToPanelEvent>(OnAttachedToPanel); RegisterCallback<DetachFromPanelEvent>(OnDetachFromPanel); SceneViewToolbarStyles.AddStyleSheets(this); } void OnAttachedToPanel(AttachToPanelEvent evt) { sceneView.sceneViewState.fxEnableChanged += OnSceneFxChanged; OnSceneFxChanged(sceneView.sceneViewState.fxEnabled); } void OnDetachFromPanel(DetachFromPanelEvent evt) { sceneView.sceneViewState.fxEnableChanged -= OnSceneFxChanged; } void OnSceneFxChanged(bool enabled) { value = enabled; } } [EditorToolbarElement("SceneView/Scene Visibility", typeof(SceneView))] sealed class SceneVisElement : EditorToolbarToggle, IAccessContainerWindow { public EditorWindow containerWindow { get; set; } SceneView sceneView => containerWindow as SceneView; public SceneVisElement() { name = "SceneViewVisibility"; tooltip = "Number of hidden objects, click to toggle scene visibility"; this.RegisterValueChangedCallback(evt => sceneView.sceneVisActive = evt.newValue); RegisterCallback<AttachToPanelEvent>(OnAttachedToPanel); RegisterCallback<DetachFromPanelEvent>(OnDetachFromPanel); SceneViewToolbarStyles.AddStyleSheets(this); } void OnAttachedToPanel(AttachToPanelEvent evt) { sceneView.sceneVisActiveChanged += SceneViewOnsceneVisActiveChanged; value = sceneView.sceneVisActive; } void OnDetachFromPanel(DetachFromPanelEvent evt) { sceneView.sceneVisActiveChanged -= SceneViewOnsceneVisActiveChanged; } void SceneViewOnsceneVisActiveChanged(bool active) { value = active; } } [EditorToolbarElement("SceneView/Grids", typeof(SceneView))] sealed class SceneViewGridSettingsElement : EditorToolbarDropdownToggle, IAccessContainerWindow { public EditorWindow containerWindow { get; set; } SceneView sceneView => containerWindow as SceneView; public SceneViewGridSettingsElement() { name = "SceneviewGrids"; tooltip = L10n.Tr("Toggle the visibility of the grid"); this.RegisterValueChangedCallback(delegate(ChangeEvent<bool> evt) { sceneView.sceneViewGrids.showGrid = evt.newValue; }); RegisterCallback<AttachToPanelEvent>(OnAttachedToPanel); RegisterCallback<DetachFromPanelEvent>(OnDetachFromPanel); SceneViewToolbarStyles.AddStyleSheets(this); } void OnDropdownClicked() { if (!(containerWindow is SceneView view)) return; var w = PopupWindowBase.Show<GridSettingsWindow>(this, new Vector2(300, 88)); if(w != null) w.Init(view); } void OnAttachedToPanel(AttachToPanelEvent evt) { value = sceneView.sceneViewGrids.showGrid; sceneView.gridVisibilityChanged += SceneViewOngridVisibilityChanged; sceneView.sceneViewGrids.gridRenderAxisChanged += OnSceneViewOngridRenderAxisChanged; OnSceneViewOngridRenderAxisChanged(sceneView.sceneViewGrids.gridAxis); dropdownClicked += OnDropdownClicked; } void OnDetachFromPanel(DetachFromPanelEvent evt) { sceneView.gridVisibilityChanged -= SceneViewOngridVisibilityChanged; sceneView.sceneViewGrids.gridRenderAxisChanged -= OnSceneViewOngridRenderAxisChanged; dropdownClicked -= OnDropdownClicked; } void OnSceneViewOngridRenderAxisChanged(SceneViewGrid.GridRenderAxis axis) { EnableInClassList("unity-sceneview-grid-axis--x", axis == SceneViewGrid.GridRenderAxis.X); EnableInClassList("unity-sceneview-grid-axis--y", axis == SceneViewGrid.GridRenderAxis.Y); EnableInClassList("unity-sceneview-grid-axis--z", axis == SceneViewGrid.GridRenderAxis.Z); } void SceneViewOngridVisibilityChanged(bool visibility) { value = visibility; } } [EditorToolbarElement("SceneView/Render Doc", typeof(SceneView))] sealed class RenderDocElement : EditorToolbarButton, IAccessContainerWindow { public EditorWindow containerWindow { get; set; } SceneView sceneView => containerWindow as SceneView; public RenderDocElement() { name = "FrameCapture"; tooltip = L10n.Tr(RenderDocUtil.openInRenderDocTooltip); icon = EditorGUIUtility.FindTexture("FrameCapture"); UpdateState(); RegisterCallback<AttachToPanelEvent>(OnAttachedToPanel); RegisterCallback<DetachFromPanelEvent>(OnDetachFromPanel); SceneViewToolbarStyles.AddStyleSheets(this); } void UpdateState() { style.display = RenderDoc.IsLoaded() && RenderDoc.IsSupported() ? DisplayStyle.Flex : DisplayStyle.None; } void OnAttachedToPanel(AttachToPanelEvent evt) { clicked += OnAction; EditorApplication.update += OnUpdate; } void OnDetachFromPanel(DetachFromPanelEvent evt) { clicked -= OnAction; EditorApplication.update -= OnUpdate; } void OnAction() { sceneView.m_Parent.CaptureRenderDocScene(); } void OnUpdate() { UpdateState(); } } [EditorToolbarElement("SceneView/Metal Capture", typeof(SceneView))] sealed class MetalCaptureElement : EditorToolbarButton, IAccessContainerWindow { public EditorWindow containerWindow { get; set; } SceneView sceneView => containerWindow as SceneView; public MetalCaptureElement() { name = "MetalCapture"; tooltip = L10n.Tr("Capture the current view and open in Xcode frame debugger"); icon = EditorGUIUtility.FindTexture("FrameCapture"); UpdateState(); RegisterCallback<AttachToPanelEvent>(OnAttachedToPanel); RegisterCallback<DetachFromPanelEvent>(OnDetachFromPanel); SceneViewToolbarStyles.AddStyleSheets(this); } void UpdateState() { style.display = FrameCapture.IsDestinationSupported(FrameCaptureDestination.DevTools) || FrameCapture.IsDestinationSupported(FrameCaptureDestination.GPUTraceDocument) ? DisplayStyle.Flex : DisplayStyle.None; } void OnAttachedToPanel(AttachToPanelEvent evt) { clicked += OnAction; EditorApplication.update += OnUpdate; } void OnDetachFromPanel(DetachFromPanelEvent evt) { clicked -= OnAction; EditorApplication.update -= OnUpdate; } void OnAction() { sceneView.m_Parent.CaptureMetalScene(); } void OnUpdate() { UpdateState(); } } [EditorToolbarElement("SceneView/Scene Camera", typeof(SceneView))] sealed class SceneCameraElement : EditorToolbarDropdown, IAccessContainerWindow { public EditorWindow containerWindow { get; set; } SceneView sceneView => containerWindow as SceneView; public SceneCameraElement() { name = "SceneViewCamera"; tooltip = "Settings for the Scene view camera."; RegisterCallback<AttachToPanelEvent>(OnAttachedToPanel); RegisterCallback<DetachFromPanelEvent>(OnDetachFromPanel); SceneViewToolbarStyles.AddStyleSheets(this); } void OnAttachedToPanel(AttachToPanelEvent evt) { //Settings the icon display explicitly as this is set to DisplayStyle.Flex when icon = null //Here the icon is set using USS so on the C# side icon = null var iconElement = this.Q<Image>(); iconElement.style.display = DisplayStyle.Flex; clickable.clickedWithEventInfo += OnClickableOnclickedWithEventInfo; } void OnDetachFromPanel(DetachFromPanelEvent evt) { clickable.clickedWithEventInfo -= OnClickableOnclickedWithEventInfo; } void OnClickableOnclickedWithEventInfo(EventBase eventBase) { if (eventBase.eventTypeId == ContextClickEvent.TypeId()) SceneViewCameraWindow.ShowContextMenu(sceneView); else PopupWindow.Show(worldBound, new SceneViewCameraWindow(sceneView)); } } [EditorToolbarElement("SceneView/Gizmos", typeof(SceneView))] sealed class GizmosElement : EditorToolbarDropdownToggle, IAccessContainerWindow { public EditorWindow containerWindow { get; set; } SceneView sceneView => containerWindow as SceneView; public GizmosElement() { name = "Gizmos"; tooltip = L10n.Tr("Toggle visibility of all Gizmos in the Scene view"); dropdownClicked += () => AnnotationWindow.ShowAtPosition(worldBound, false); this.RegisterValueChangedCallback(delegate(ChangeEvent<bool> evt) { sceneView.drawGizmos = evt.newValue; }); RegisterCallback<AttachToPanelEvent>(OnAttachedToPanel); RegisterCallback<DetachFromPanelEvent>(OnDetachFromPanel); SceneViewToolbarStyles.AddStyleSheets(this); } void OnAttachedToPanel(AttachToPanelEvent evt) { value = sceneView.drawGizmos; sceneView.drawGizmosChanged += SceneViewOndrawGizmosChanged; } void OnDetachFromPanel(DetachFromPanelEvent evt) { sceneView.drawGizmosChanged -= SceneViewOndrawGizmosChanged; } void SceneViewOndrawGizmosChanged(bool enabled) { value = enabled; } } [EditorToolbarElement("SceneView/Search", typeof(SceneView))] sealed class SceneViewSearchElement : VisualElement, IAccessContainerWindow { public EditorWindow containerWindow { get; set; } public SceneViewSearchElement() { name = "Search"; tooltip = "Search the Hierarchy / Scene View"; SceneViewToolbarStyles.AddStyleSheets(this); Add(new IMGUIContainer { onGUIHandler = OnGUI }); } void OnGUI() { EditorGUILayout.BeginHorizontal(); if (containerWindow is SceneView sceneView) sceneView.ToolbarSearchFieldGUI(); EditorGUILayout.EndHorizontal(); } } }
UnityCsReference/Modules/SceneView/SceneViewToolbarElements.cs/0
{ "file_path": "UnityCsReference/Modules/SceneView/SceneViewToolbarElements.cs", "repo_id": "UnityCsReference", "token_count": 9551 }
450
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License namespace UnityEditor.ShaderFoundry { internal sealed partial class ShaderContainer { static void AddDefaultTypes(ShaderContainer container) { ShaderType.Void(container); string[] scalarTypes = { "bool", "int", "uint", "half", "float", "double" }; foreach (var s in scalarTypes) { var scalarType = ShaderType.Scalar(container, s); for (int dim = 1; dim <= 4; dim++) ShaderType.Vector(container, scalarType, dim); for (int rows = 1; rows <= 4; rows++) for (int cols = 1; cols <= 4; cols++) ShaderType.Matrix(container, scalarType, rows, cols); } ShaderType.Texture(container, "Texture1D"); ShaderType.Texture(container, "Texture1DArray"); ShaderType.Texture(container, "Texture2D"); ShaderType.Texture(container, "Texture2DArray"); ShaderType.Texture(container, "Texture3D"); ShaderType.Texture(container, "TextureCube"); ShaderType.Texture(container, "TextureCubeArray"); ShaderType.Texture(container, "Texture2DMS"); ShaderType.Texture(container, "Texture2DMSArray"); ShaderType.SamplerState(container, "SamplerState"); // Unity wrapped resource types ShaderType BuildExternallyDeclaredType(ShaderContainer container, string typeName) { var builder = new ShaderType.StructBuilder(container, typeName); builder.DeclaredExternally(); return builder.Build(); } container._UnityTexture2D = BuildExternallyDeclaredType(container, "UnityTexture2D"); container._UnityTexture2DArray = BuildExternallyDeclaredType(container, "UnityTexture2DArray"); container._UnityTextureCube = BuildExternallyDeclaredType(container, "UnityTextureCube"); container._UnityTexture3D = BuildExternallyDeclaredType(container, "UnityTexture3D"); container._UnitySamplerState = BuildExternallyDeclaredType(container, "UnitySamplerState"); } } }
UnityCsReference/Modules/ShaderFoundry/ScriptBindings/DefaultContainer.cs/0
{ "file_path": "UnityCsReference/Modules/ShaderFoundry/ScriptBindings/DefaultContainer.cs", "repo_id": "UnityCsReference", "token_count": 1043 }
451
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; using UnityEngine.Bindings; namespace UnityEditor.ShaderFoundry { [NativeHeader("Modules/ShaderFoundry/Public/PragmaDescriptor.h")] internal struct PragmaDescriptorInternal : IInternalType<PragmaDescriptorInternal> { internal FoundryHandle m_ListHandle; internal extern static PragmaDescriptorInternal Invalid(); internal extern void Setup(ShaderContainer container, string name, string[] ops); internal extern bool IsValid(); internal extern string GetName(ShaderContainer container); internal extern int GetOpCount(ShaderContainer container); internal extern string GetOp(ShaderContainer container, int index); // IInternalType PragmaDescriptorInternal IInternalType<PragmaDescriptorInternal>.ConstructInvalid() => Invalid(); } [FoundryAPI] internal readonly struct PragmaDescriptor : IEquatable<PragmaDescriptor>, IPublicType<PragmaDescriptor> { // data members readonly ShaderContainer container; readonly PragmaDescriptorInternal descriptor; internal readonly FoundryHandle handle; // IPublicType ShaderContainer IPublicType.Container => Container; bool IPublicType.IsValid => IsValid; FoundryHandle IPublicType.Handle => handle; PragmaDescriptor IPublicType<PragmaDescriptor>.ConstructFromHandle(ShaderContainer container, FoundryHandle handle) => new PragmaDescriptor(container, handle); // public API public ShaderContainer Container => container; public bool IsValid => (container != null && descriptor.IsValid()); public string Name => descriptor.GetName(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 PragmaDescriptor(ShaderContainer container, FoundryHandle handle) { this.container = container; this.handle = handle; ShaderContainer.Get(container, handle, out descriptor); } public static PragmaDescriptor Invalid => new PragmaDescriptor(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 PragmaDescriptor other && this.Equals(other); public bool Equals(PragmaDescriptor other) => EqualityChecks.ReferenceEquals(this.handle, this.container, other.handle, other.container); public override int GetHashCode() => (container, handle).GetHashCode(); public static bool operator==(PragmaDescriptor lhs, PragmaDescriptor rhs) => lhs.Equals(rhs); public static bool operator!=(PragmaDescriptor lhs, PragmaDescriptor rhs) => !lhs.Equals(rhs); public class Builder { ShaderContainer container; string name; List<string> ops = new List<string>(); public ShaderContainer Container => container; public Builder(ShaderContainer container, string name, IEnumerable<string> ops) { this.container = container; this.name = name; this.ops.AddRange(ops); } public PragmaDescriptor Build() { var descriptor = new PragmaDescriptorInternal(); descriptor.Setup(container, name, ops.ToArray()); var resultHandle = container.Add(descriptor); return new PragmaDescriptor(container, resultHandle); } } } }
UnityCsReference/Modules/ShaderFoundry/ScriptBindings/PragmaDescriptor.bindings.cs/0
{ "file_path": "UnityCsReference/Modules/ShaderFoundry/ScriptBindings/PragmaDescriptor.bindings.cs", "repo_id": "UnityCsReference", "token_count": 1568 }
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 System.Text; using UnityEngine.Bindings; using System.Runtime.InteropServices; namespace UnityEditor.ShaderFoundry { [NativeHeader("Modules/ShaderFoundry/Public/TemplateInstance.h")] internal struct TemplateInstanceInternal : IInternalType<TemplateInstanceInternal> { internal FoundryHandle m_TemplateHandle; internal FoundryHandle m_CustomizationPointImplementationListHandle; internal FoundryHandle m_TagDescriptorListHandle; internal extern static TemplateInstanceInternal Invalid(); internal extern bool IsValid(); // IInternalType TemplateInstanceInternal IInternalType<TemplateInstanceInternal>.ConstructInvalid() => Invalid(); } [FoundryAPI] internal readonly struct TemplateInstance : IEquatable<TemplateInstance>, IPublicType<TemplateInstance> { // data members readonly ShaderContainer container; readonly internal FoundryHandle handle; readonly TemplateInstanceInternal templateInstance; // IPublicType ShaderContainer IPublicType.Container => Container; bool IPublicType.IsValid => IsValid; FoundryHandle IPublicType.Handle => handle; TemplateInstance IPublicType<TemplateInstance>.ConstructFromHandle(ShaderContainer container, FoundryHandle handle) => new TemplateInstance(container, handle); // public API public ShaderContainer Container => container; public bool IsValid => (container != null && handle.IsValid); public Template Template { get { var localContainer = container; return new Template(localContainer, templateInstance.m_TemplateHandle); } } public IEnumerable<CustomizationPointImplementation> CustomizationPointImplementations => templateInstance.m_CustomizationPointImplementationListHandle.AsListEnumerable<CustomizationPointImplementation>(container, (container, handle) => (new CustomizationPointImplementation(container, handle))); public IEnumerable<TagDescriptor> TagDescriptors { get { var localContainer = Container; var list = new HandleListInternal(templateInstance.m_TagDescriptorListHandle); return list.Select(localContainer, (handle) => (new TagDescriptor(localContainer, handle))); } } // private internal TemplateInstance(ShaderContainer container, FoundryHandle handle) { this.container = container; this.handle = handle; ShaderContainer.Get(container, handle, out templateInstance); } public static TemplateInstance Invalid => new TemplateInstance(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 TemplateInstance other && this.Equals(other); public bool Equals(TemplateInstance other) => EqualityChecks.ReferenceEquals(this.handle, this.container, other.handle, other.container); public override int GetHashCode() => (container, handle).GetHashCode(); public static bool operator==(TemplateInstance lhs, TemplateInstance rhs) => lhs.Equals(rhs); public static bool operator!=(TemplateInstance lhs, TemplateInstance rhs) => !lhs.Equals(rhs); public class Builder { ShaderContainer container; Template template = Template.Invalid; public List<CustomizationPointImplementation> customizationPointImplementations; List<TagDescriptor> tagDescriptors = new List<TagDescriptor>(); public ShaderContainer Container => container; public Builder(ShaderContainer container, Template template) { this.container = container; this.template = template; } public void AddCustomizationPointImplementation(CustomizationPointImplementation customizationPointImplementation) { Utilities.AddToList(ref customizationPointImplementations, customizationPointImplementation); } public void AddTagDescriptor(TagDescriptor tagDescriptor) { tagDescriptors.Add(tagDescriptor); } public TemplateInstance Build() { var templateInstanceInternal = new TemplateInstanceInternal(); templateInstanceInternal.m_TemplateHandle = template.handle; templateInstanceInternal.m_CustomizationPointImplementationListHandle = HandleListInternal.Build(container, customizationPointImplementations, (o) => (o.handle)); templateInstanceInternal.m_TagDescriptorListHandle = HandleListInternal.Build(container, tagDescriptors, (o) => (o.handle)); var returnTypeHandle = container.Add(templateInstanceInternal); return new TemplateInstance(container, returnTypeHandle); } } } }
UnityCsReference/Modules/ShaderFoundry/ScriptBindings/TemplateInstance.bindings.cs/0
{ "file_path": "UnityCsReference/Modules/ShaderFoundry/ScriptBindings/TemplateInstance.bindings.cs", "repo_id": "UnityCsReference", "token_count": 1916 }
453
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; using System.IO; using System.Linq; using UnityEditor; using UnityEditor.UIElements; using UnityEngine; using UnityEngine.UIElements; namespace UnityEditor.ShortcutManagement { internal class HelperWindow : EditorWindow { internal const int kHelperBarMinWidth = 300; // HelperWindow is not ready for use yet //[MenuItem("Window/General/Helper _%H")] static void ShowWindow() => GetWindow<HelperWindow>().Show(); static Dictionary<KeyCode, GUIContent> keyIcons; static bool s_Initialized; static void Init() { if (s_Initialized) return; EditorApplication.globalEventHandler += UpdateContext; ContextManager.onTagChange += UpdateContext; Selection.selectionChanged += UpdateContext; windowFocusChanged += UpdateContext; UpdateContext(); s_Initialized = true; } void OnEnable() { Init(); } static bool HandleKey(Event evt) { if (evt == null) return false; var keyCode = evt.keyCode; if (keyCode == KeyCode.None) { Enum.TryParse(typeof(KeyCode), Event.current?.character.ToString() ?? string.Empty, true, out var charCode); keyCode = (KeyCode)(charCode ?? KeyCode.None); } if (keyCode == KeyCode.None) { keyCodes.Clear(); return true; } else { switch (evt.type) { case EventType.MouseDown: case EventType.KeyDown: case EventType.TouchDown: keyCodes.Add(keyCode); filterAction = EditorGUI.actionKey; filterShift = evt.shift; filterAlt = evt.alt; break; case EventType.MouseUp: case EventType.KeyUp: case EventType.TouchUp: keyCodes.Remove(keyCode); filterAction = false; filterShift = false; filterAlt = false; break; default: keyCodes.Clear(); break; } } bool changed = keyHash != keyCodes.GetHashCode(); keyHash = keyCode.GetHashCode(); return changed; } static void UpdateContext() { HandleKey(Event.current); shortcuts.Clear(); ShortcutIntegration.instance.directory.FindPotentialShortcutEntries(ShortcutIntegration.instance.contextManager, shortcuts); shortcuts = shortcuts.Where(s => s.combinations.Count > 0).OrderBy(s => s.priority).ThenBy(s => Path.GetFileName(s.displayName)).ToList(); if (filterAction) shortcuts = shortcuts.Where(s => s.combinations.Any(c => c.action)).ToList(); if (filterShift) shortcuts = shortcuts.Where(s => s.combinations.Any(c => c.shift)).ToList(); if (filterAlt) shortcuts = shortcuts.Where(s => s.combinations.Any(c => c.alt)).ToList(); if (HasOpenInstances<HelperWindow>()) { if (activeContexts != null) activeContexts.value = string.Join(", ", ShortcutIntegration.instance.contextManager.GetActiveContexts().Select(t => t.Name)); if (activeTags != null) activeTags.value = string.Join(", ", ShortcutIntegration.instance.contextManager.GetActiveTags()); if (input != null) input.value = string.Join(" + ", keyCodes); if (shortcutList != null) { shortcutList.itemsSource = shortcuts; shortcutList.Rebuild(); } } if (EditorPrefs.GetBool("EnableHelperBar", true)) AppStatusBar.StatusChanged(); } static TextField activeContexts; static TextField activeTags; static HashSet<KeyCode> keyCodes = new HashSet<KeyCode>(); static TextField input; static ListView shortcutList; static List<ShortcutEntry> shortcuts = new List<ShortcutEntry>(); static int keyHash; static bool filterAction = false; static bool filterShift = false; static bool filterAlt = false; private void CreateGUI() { var container = new VisualElement(); activeContexts = new TextField("Contexts"); activeTags = new TextField("Tags"); input = new TextField("Input"); shortcutList = new ListView(shortcuts, 30, () => { var container = new VisualElement(); container.style.backgroundColor = new Color(0, 0, 0, 0.5f); container.style.borderBottomLeftRadius = container.style.borderBottomRightRadius = container.style.borderTopLeftRadius = container.style.borderTopRightRadius = 3; container.style.marginBottom = container.style.marginLeft = container.style.marginRight = container.style.marginTop = 2; container.style.flexDirection = FlexDirection.Row; var combination = new Label(); combination.style.fontSize = 20; combination.style.minWidth = 150; combination.style.marginRight = 15; container.Add(combination); var infoContainer = new VisualElement(); container.Add(infoContainer); var name = new Label(); name.style.fontSize = 12; infoContainer.Add(name); var context = new Label(); context.style.fontSize = 8; infoContainer.Add(context); return container; }, (e, i) => { if (i >= shortcuts.Count) return; var combination = e.Children().First() as Label; var infoContainer = e.Children().Skip(1).First(); var name = infoContainer.Children().First() as Label; var context = infoContainer.Children().Skip(1).First() as Label; combination.text = shortcuts[i].combinations.First().ToString(); name.text = Path.GetFileName(shortcuts[i].displayName); context.text = shortcuts[i].context.Name + " " + shortcuts[i].tag; }); container.Add(activeContexts); container.Add(activeTags); container.Add(input); container.Add(shortcutList); rootVisualElement.Add(container); } const int k_HorizontalEntryPadding = 4; const int space = 2; internal static void StatusBarShortcuts() { Init(); if (keyIcons == null) { keyIcons = new Dictionary<KeyCode, GUIContent>(); keyIcons[KeyCode.Mouse0] = new GUIContent(EditorGUIUtility.LoadIconRequired($"Icons/HelperBar/{KeyCode.Mouse0}.png")); keyIcons[KeyCode.Mouse1] = new GUIContent(EditorGUIUtility.LoadIconRequired($"Icons/HelperBar/{KeyCode.Mouse1}.png")); keyIcons[KeyCode.Mouse2] = new GUIContent(EditorGUIUtility.LoadIconRequired($"Icons/HelperBar/{KeyCode.Mouse2}.png")); keyIcons[KeyCode.Mouse3] = new GUIContent(EditorGUIUtility.LoadIconRequired($"Icons/HelperBar/{KeyCode.Mouse3}.png")); keyIcons[KeyCode.Mouse4] = new GUIContent(EditorGUIUtility.LoadIconRequired($"Icons/HelperBar/{KeyCode.Mouse4}.png")); } GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true), GUILayout.MaxWidth(8192), GUILayout.MinWidth(kHelperBarMinWidth)); var r = EditorGUILayout.GetControlRect(false); r.y -= space; r.height += 1; foreach (var shortcut in shortcuts) { var name = Path.GetFileName(shortcut.displayName); var nameContent = new GUIContent(name); var combination = shortcut.combinations.First(); var combinationText = combination.ToString(); keyIcons.TryGetValue(combination.keyCode, out var icon); int iconWidth = 0; if (icon != null) { iconWidth = (int)r.height; combinationText = combinationText.Substring(0, combinationText.LastIndexOf("+") + 1); } var combinationContent = new GUIContent(combinationText); var nameWidth = EditorStyles.label.CalcSize(nameContent).x; var combinationWidth = EditorStyles.boldLabel.CalcSize(combinationContent).x; var width = k_HorizontalEntryPadding + combinationWidth + iconWidth + space + nameWidth + k_HorizontalEntryPadding + 1; if (r.width < width) break; var shortcutBox = new Rect(r.x, r.y, width, r.height); GUI.Box(shortcutBox, GUIContent.none, EditorStyles.miniButton); GUI.Label(new Rect(r.x + k_HorizontalEntryPadding, r.y - 1, combinationWidth, r.height), combinationContent, EditorStyles.boldLabel); if (iconWidth > 0) GUI.Box(new Rect(r.x + k_HorizontalEntryPadding + combinationWidth, r.y + 1, iconWidth, r.height), icon, GUIStyle.none); GUI.Label(new Rect(r.x + k_HorizontalEntryPadding + combinationWidth + iconWidth + space, r.y - 1, nameWidth, r.height), nameContent, EditorStyles.label); r.xMin += width + space * 3; var evt = Event.current; if (evt.type == EventType.MouseDown && shortcutBox.Contains(evt.mousePosition)) { if (evt.button == 0) { ShortcutManagerWindow shortcutManager; if (HasOpenInstances<ShortcutManagerWindow>()) { shortcutManager = GetWindow<ShortcutManagerWindow>(); } else { shortcutManager = CreateInstance<ShortcutManagerWindow>(); shortcutManager.ShowUtility(); } shortcutManager.rootVisualElement.Q<ToolbarPopupSearchField>().value = shortcut.displayName; GUIUtility.ExitGUI(); } else if (evt.button == 1) { GenericMenu contextMenu = new GenericMenu(); // HelperWindow is not ready for use yet //contextMenu.AddItem(new GUIContent("Show Helper Window"), false, () => ShowWindow()); contextMenu.AddItem(new GUIContent("Disable Helper Bar"), false, () => EditorPrefs.SetBool("EnableHelperBar", false)); contextMenu.ShowAsContext(); } } } GUILayout.EndHorizontal(); } } }
UnityCsReference/Modules/ShortcutManagerEditor/HelperWindow.cs/0
{ "file_path": "UnityCsReference/Modules/ShortcutManagerEditor/HelperWindow.cs", "repo_id": "UnityCsReference", "token_count": 5563 }
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 UnityEditorInternal; using UnityEngine; namespace UnityEditor.ShortcutManagement { class ShortcutManagerWindowViewController : IShortcutManagerWindowViewController, IKeyBindingStateProvider { static readonly string k_AllUnityCommands = L10n.Tr("All Unity Commands"); static readonly string k_CommandsWithConflicts = L10n.Tr("Binding Conflicts"); internal static readonly string k_MainMenu = L10n.Tr("Main Menu"); static readonly string k_ProfileNameEmpty = L10n.Tr("Profile name is empty"); static readonly string k_ProfileNameUnsupported = L10n.Tr("Profile name is unsupported"); static readonly string k_ProfileExists = L10n.Tr("Profile already exists"); static readonly string k_DefaultRename = L10n.Tr("Default profile cannot be renamed"); static readonly string k_ProfileNotFound = L10n.Tr("Couldn't find active profile"); const int k_AllUnityCommandsIndex = 0; const int k_ConflictsIndex = 1; const int k_MainMenuIndex = 2; SerializedShortcutManagerWindowState m_SerializedState; IShortcutProfileManager m_ShortcutProfileManager; IDirectory m_Directory; IContextManager m_ContextManager; IShortcutManagerWindowView m_ShortcutManagerWindowView; IBindingValidator m_BindingValidator; IAvailableShortcutsChangedNotifier m_AvailableShortcutsChangedNotifier; List<ShortcutEntry> m_AllEntries = new List<ShortcutEntry>(); Dictionary<string, List<ShortcutEntry>> m_CategoryToEntriesList = new Dictionary<string, List<ShortcutEntry>>(); Dictionary<KeyCombination, List<ShortcutEntry>> m_KeyBindingRootToBoundEntries; List<string> m_Categories = new List<string>(); int m_SelectedCategoryIndex; List<ShortcutEntry> m_SelectedCategoryShortcutList = new List<ShortcutEntry>(); List<string> m_SelectedCategoryShortcutPathList = new List<string>(); ShortcutEntry m_SelectedEntry; int m_SelectedEntryIndex; List<ShortcutEntry> m_ShortcutsBoundToSelectedKey = new List<ShortcutEntry>(); public ShortcutManagerWindowViewController(SerializedShortcutManagerWindowState state, IDirectory directory, IBindingValidator bindingValidator, IShortcutProfileManager profileManager, IContextManager contextManager, IAvailableShortcutsChangedNotifier availableShortcutsChangedNotifier) { m_SerializedState = state; m_ShortcutProfileManager = profileManager; m_Directory = directory; m_ContextManager = contextManager; m_BindingValidator = bindingValidator; m_AvailableShortcutsChangedNotifier = availableShortcutsChangedNotifier; InitializeCategoryList(); BuildKeyMapBindingStateData(); PopulateShortcutsBoundToSelectedKey(); } void InitializeCategoryList() { BuildCategoryList(); selectedCategory = m_SerializedState.selectedCategory; selectedEntry = m_Directory.FindShortcutEntry(m_SerializedState.selectedEntryIdentifier); } public void OnEnable() { m_ShortcutProfileManager.activeProfileChanged += OnActiveProfileChanged; m_ShortcutProfileManager.loadedProfilesChanged += OnLoadedProfilesChanged; m_AvailableShortcutsChangedNotifier.availableShortcutsChanged += OnAvailableShortcutsChanged; } public void OnDisable() { m_ShortcutProfileManager.activeProfileChanged -= OnActiveProfileChanged; m_ShortcutProfileManager.loadedProfilesChanged -= OnLoadedProfilesChanged; m_AvailableShortcutsChangedNotifier.availableShortcutsChanged -= OnAvailableShortcutsChanged; } void OnActiveProfileChanged(IShortcutProfileManager shortcutProfileManager, ShortcutProfile previousActiveProfile, ShortcutProfile currentActiveProfile) { UpdateInternalCache(); } void OnAvailableShortcutsChanged() { InitializeCategoryList(); UpdateInternalCache(); } void UpdateInternalCache() { UpdateCommandsWithConflicts(); BuildKeyMapBindingStateData(); PopulateShortcutList(); m_ShortcutManagerWindowView.RefreshAll(); } void OnLoadedProfilesChanged(IShortcutProfileManager shortcutProfileManager) { m_ShortcutManagerWindowView.RefreshProfiles(); } //There is a mutual dependecy between the view and the viewcontroller, //Ideally we would inject dependecies via the constructor, but since we have a circular dependecy //that is not possible, so until I find a better solution, we inject the dependency here vie this method. public void SetView(IShortcutManagerWindowView view) { m_ShortcutManagerWindowView = view; } public IShortcutManagerWindowView GetView() { return m_ShortcutManagerWindowView; } public void ResetToDefault(ShortcutEntry entry) { var newBinding = entry.GetDefaultCombinations(); var conflicts = FindConflictsIfRebound(entry, newBinding); if (conflicts.Count == 0) { m_ShortcutProfileManager.ResetToDefault(entry); } else { var howToHandle = m_ShortcutManagerWindowView.HandleRebindWillCreateConflict(entry, newBinding, conflicts); switch (howToHandle) { case RebindResolution.DoNotRebind: break; case RebindResolution.CreateConflict: m_ShortcutProfileManager.ResetToDefault(entry); break; case RebindResolution.UnassignExistingAndBind: foreach (var conflictEntry in conflicts) RebindEntry(conflictEntry, new List<KeyCombination>()); m_ShortcutProfileManager.ResetToDefault(entry); break; default: throw new Exception("Unhandled enum case"); } } m_ShortcutManagerWindowView.RefreshShortcutList(); } public void RemoveBinding(ShortcutEntry entry) { RebindEntry(entry, new List<KeyCombination>()); } void BuildCategoryList() { const string separator = "/"; var entries = new List<ShortcutEntry>(); m_Directory.GetAllShortcuts(entries); m_AllEntries.Clear(); m_AllEntries.Capacity = entries.Count; HashSet<string> categories = new HashSet<string>(); var menuItems = new List<ShortcutEntry>(); m_CategoryToEntriesList.Clear(); foreach (var entry in entries) { var identifier = entry.displayName; m_AllEntries.Add(entry); if (entry.type == ShortcutType.Menu && entry.displayName.StartsWith(k_MainMenu)) { menuItems.Add(entry); } else { var index = identifier.IndexOf(separator); if (index > -1) { var category = identifier.Substring(0, index); categories.Add(category); if (!m_CategoryToEntriesList.ContainsKey(category)) { m_CategoryToEntriesList.Add(category, new List<ShortcutEntry>()); } m_CategoryToEntriesList[category].Add(entry); } } } var shortcutNameComparer = new ShortcutNameComparer(); m_AllEntries.Sort(shortcutNameComparer); m_CategoryToEntriesList.Add(k_AllUnityCommands, m_AllEntries); m_CategoryToEntriesList.Add(k_CommandsWithConflicts, new List<ShortcutEntry>()); UpdateCommandsWithConflicts(); menuItems.Sort(shortcutNameComparer); m_CategoryToEntriesList.Add(k_MainMenu, menuItems); m_Categories = categories.ToList(); m_Categories.Sort(); m_Categories.Insert(k_AllUnityCommandsIndex, k_AllUnityCommands); m_Categories.Insert(k_ConflictsIndex, k_CommandsWithConflicts); m_Categories.Insert(k_MainMenuIndex, k_MainMenu); } void UpdateCommandsWithConflicts() { GetAllCommandsWithConflicts(m_CategoryToEntriesList[k_CommandsWithConflicts]); } void GetAllCommandsWithConflicts(List<ShortcutEntry> output) { output.Clear(); m_Directory.FindShortcutsWithConflicts(output, m_ContextManager); output.Sort(new ConflictComparer()); } public List<string> GetAvailableProfiles() { return m_ShortcutProfileManager.GetProfiles() .Select(p => p.id) .Concat(new[] { "Default" }) .ToList(); } public string activeProfile { get { var profile = m_ShortcutProfileManager.activeProfile; return profile == null ? "Default" : profile.id; } set { if (value == "Default") m_ShortcutProfileManager.activeProfile = null; else { var profile = m_ShortcutProfileManager.GetProfileById(value); m_ShortcutProfileManager.activeProfile = profile; } } } public string CanCreateProfile(string newProfileId) { var canCreateProfileResult = m_ShortcutProfileManager.CanCreateProfile(newProfileId); switch (canCreateProfileResult) { case CanCreateProfileResult.InvalidProfileId: return string.IsNullOrWhiteSpace(newProfileId) ? k_ProfileNameEmpty : k_ProfileNameUnsupported; case CanCreateProfileResult.DuplicateProfileId: return k_ProfileExists; default: return null; } } public void CreateProfile(string newProfileId) { var newProfile = m_ShortcutProfileManager.CreateProfile(newProfileId); m_ShortcutProfileManager.activeProfile = newProfile; } public bool CanRenameActiveProfile() { return CanDeleteActiveProfile(); } public string CanRenameActiveProfile(string newProfileId) { if (m_ShortcutProfileManager.activeProfile == null) return k_DefaultRename; switch (m_ShortcutProfileManager.CanRenameProfile(m_ShortcutProfileManager.activeProfile, newProfileId)) { case CanRenameProfileResult.ProfileNotFound: return k_ProfileNotFound; case CanRenameProfileResult.InvalidProfileId: return string.IsNullOrWhiteSpace(newProfileId) ? k_ProfileNameEmpty : k_ProfileNameUnsupported; case CanRenameProfileResult.DuplicateProfileId: return k_ProfileExists; default: return null; } } public void RenameActiveProfile(string newProfileId) { if (m_ShortcutProfileManager.activeProfile == null) return; m_ShortcutProfileManager.RenameProfile(m_ShortcutProfileManager.activeProfile, newProfileId); } public bool CanDeleteActiveProfile() { if (m_ShortcutProfileManager.activeProfile == null) return false; return m_ShortcutProfileManager.CanDeleteProfile(m_ShortcutProfileManager.activeProfile) == CanDeleteProfileResult.Success; } public void DeleteActiveProfile() { if (m_ShortcutProfileManager.activeProfile == null) return; m_ShortcutProfileManager.DeleteProfile(m_ShortcutProfileManager.activeProfile); } public IList<string> GetCategories() { return m_Categories; } public int categorySeparatorIndex { get; } = k_MainMenuIndex; public void SetCategorySelected(string category) { selectedCategory = category; m_ShortcutManagerWindowView.UpdateSearchFilterOptions(); m_ShortcutManagerWindowView.RefreshShortcutList(); } string selectedCategory { get { return m_SerializedState.selectedCategory; } set { var newCategoryIndex = 0; if (!string.IsNullOrEmpty(value)) newCategoryIndex = m_Categories.IndexOf(value); m_SelectedCategoryIndex = Math.Max(0, newCategoryIndex); m_SerializedState.selectedCategory = m_Categories[m_SelectedCategoryIndex]; PopulateShortcutList(); } } public int selectedKeyDetail => - 1; public SearchOption searchMode { get { return m_SerializedState.searchMode; } set { m_SerializedState.searchMode = value; } } public void SetSearch(string newSearch) { m_SerializedState.search = newSearch; PopulateShortcutList(); m_ShortcutManagerWindowView.UpdateSearchFilterOptions(); m_ShortcutManagerWindowView.RefreshShortcutList(); } public string GetSearch() { return m_SerializedState.search; } public List<KeyCombination> GetBindingSearch() { return m_SerializedState.bindingsSearch; } public void SetBindingSearch(List<KeyCombination> newBindingSearch) { m_SerializedState.bindingsSearch = newBindingSearch; PopulateShortcutList(); m_ShortcutManagerWindowView.UpdateSearchFilterOptions(); m_ShortcutManagerWindowView.RefreshShortcutList(); } public bool ShouldShowSearchFilters() { if (!IsSearching()) return false; return m_SelectedCategoryIndex != k_AllUnityCommandsIndex; } public void GetSearchFilters(List<string> filters) { if (m_SelectedCategoryIndex != k_AllUnityCommandsIndex) filters.Add(m_Categories[m_SelectedCategoryIndex]); filters.Add(k_AllUnityCommands); } public string GetSelectedSearchFilter() { switch (m_SerializedState.searchCategoryFilter) { case SearchCategoryFilter.IgnoreCategory: return k_AllUnityCommands; case SearchCategoryFilter.SearchWithinSelectedCategory: return m_Categories[m_SelectedCategoryIndex]; default: throw new ArgumentOutOfRangeException(); } } public void SetSelectedSearchFilter(string filter) { if (filter == k_AllUnityCommands) m_SerializedState.searchCategoryFilter = SearchCategoryFilter.IgnoreCategory; else if (filter == m_Categories[m_SelectedCategoryIndex]) m_SerializedState.searchCategoryFilter = SearchCategoryFilter.SearchWithinSelectedCategory; else throw new ArgumentException("invalid filter", nameof(filter)); PopulateShortcutList(); m_ShortcutManagerWindowView.UpdateSearchFilterOptions(); m_ShortcutManagerWindowView.RefreshShortcutList(); } public int selectedCategoryIndex => m_SelectedCategoryIndex; void PopulateShortcutList() { m_SelectedCategoryShortcutList.Clear(); m_SelectedCategoryShortcutPathList.Clear(); var category = selectedCategory; if (IsSearching() && m_SerializedState.searchCategoryFilter == SearchCategoryFilter.IgnoreCategory) category = k_AllUnityCommands; var identifierList = m_CategoryToEntriesList[category]; foreach (var indentifier in identifierList) { var entry = indentifier; if (BelongsToSearch(entry)) { m_SelectedCategoryShortcutList.Add(entry); m_SelectedCategoryShortcutPathList.Add(entry.displayName.StartsWith(category) ? entry.displayName.Substring(category.Length + 1) : entry.displayName); } } } bool BelongsToSearch(ShortcutEntry entry) { if (!IsSearching()) return true; switch (searchMode) { case SearchOption.Name: return entry.displayName.IndexOf(m_SerializedState.search, StringComparison.InvariantCultureIgnoreCase) >= 0; case SearchOption.Binding: return entry.StartsWith(m_SerializedState.bindingsSearch); } return false; } public IList<ShortcutEntry> GetShortcutList() { return m_SelectedCategoryShortcutList; } public IList<string> GetShortcutPathList() { return m_SelectedCategoryShortcutPathList; } public ShortcutEntry selectedEntry { get { return m_SelectedEntry; } private set { m_SelectedEntry = value; if (m_SelectedEntry != null) { m_SerializedState.selectedEntryIdentifier = m_SelectedEntry.identifier; m_SelectedEntryIndex = m_SelectedCategoryShortcutList.FindIndex(entry => entry == m_SelectedEntry); } else { m_SerializedState.selectedEntryIdentifier = new Identifier(); m_SelectedEntryIndex = -1; } } } public void ShortcutEntrySelected(ShortcutEntry entry) { selectedEntry = entry; } public int selectedEntryIndex => m_SelectedEntryIndex; public void DragEntryAndDropIntoKey(KeyCode keyCode, EventModifiers eventModifier, ShortcutEntry entry) { if (!CanEntryBeAssignedToKey(keyCode, eventModifier, entry)) throw new InvalidOperationException("This would create a conflict"); var keyCombination = new List<KeyCombination>(); keyCombination.Add(KeyCombination.FromKeyboardInput(keyCode, eventModifier)); RebindEntry(entry, keyCombination); } string GetUniqueProfileId() { var desiredId = "Default copy"; const string desiredIdTemplate = "Default copy ({0})"; var existingProfileIds = GetAvailableProfiles(); int index; for (index = 1; existingProfileIds.Contains(desiredId) && index != int.MaxValue; index++) { desiredId = string.Format(desiredIdTemplate, index); } return index == int.MaxValue ? null : desiredId; } void RebindEntry(ShortcutEntry entry, List<KeyCombination> keyCombination) { // Ensure we have an active profile, if not create a new one if (m_ShortcutProfileManager.activeProfile == null) { var uniqueProfileId = GetUniqueProfileId(); if (uniqueProfileId == null) { Debug.LogWarning("Could not create unique profile id."); return; } m_ShortcutProfileManager.activeProfile = m_ShortcutProfileManager.CreateProfile(uniqueProfileId); } m_ShortcutProfileManager.ModifyShortcutEntry(entry.identifier, keyCombination); UpdateCommandsWithConflicts(); BuildKeyMapBindingStateData(); PopulateShortcutList(); m_ShortcutManagerWindowView.RefreshAll(); } public bool CanEntryBeAssignedToKey(KeyCode keyCode, EventModifiers eventModifier, ShortcutEntry entry) { if (!m_BindingValidator.IsKeyValid(keyCode, out _)) { return false; } var keycombination = KeyCombination.FromKeyboardInput(keyCode, eventModifier); List<ShortcutEntry> entries; if (m_KeyBindingRootToBoundEntries.TryGetValue(keycombination, out entries)) { foreach (var boundEntry in entries) { if (IsGlobalContext(entry)) return false; if (boundEntry.context.IsAssignableFrom(entry.context) || entry.context.IsAssignableFrom(boundEntry.context)) return false; } } return true; } void PopulateShortcutsBoundToSelectedKey() { m_ShortcutsBoundToSelectedKey.Clear(); var keycombination = KeyCombination.FromKeyboardInput(m_SerializedState.selectedKey, m_SerializedState.selectedModifiers); List<ShortcutEntry> entries; if (m_KeyBindingRootToBoundEntries.TryGetValue(keycombination, out entries)) { m_ShortcutsBoundToSelectedKey.AddRange(entries); } } public IList<ShortcutEntry> GetSelectedKeyShortcuts() { return m_ShortcutsBoundToSelectedKey; } public void NavigateTo(ShortcutEntry shortcutEntry) { SetCategorySelected(FindCategoryFor(shortcutEntry)); selectedEntry = shortcutEntry; m_ShortcutManagerWindowView.RefreshCategoryList(); m_ShortcutManagerWindowView.RefreshShortcutList(); } string FindCategoryFor(ShortcutEntry shortcutEntry) { foreach (var pair in m_CategoryToEntriesList) { var foundId = pair.Value.Find(entry => entry == shortcutEntry); if (foundId != null) return pair.Key; } return k_AllUnityCommands; } public void SetKeySelected(KeyCode keyCode, EventModifiers eventModifier) { m_SerializedState.selectedKey = keyCode; m_SerializedState.selectedModifiers = eventModifier; PopulateShortcutsBoundToSelectedKey(); } public KeyCode GetSelectedKey() { return m_SerializedState.selectedKey; } public EventModifiers GetSelectedEventModifiers() { return m_SerializedState.selectedModifiers; } public void RequestRebindOfSelectedEntry(List<KeyCombination> newbinding) { var conflicts = FindConflictsIfRebound(selectedEntry, newbinding); if (conflicts.Count == 0) { RebindEntry(selectedEntry, newbinding); } else { var howToHandle = m_ShortcutManagerWindowView.HandleRebindWillCreateConflict(selectedEntry, newbinding, conflicts); switch (howToHandle) { case RebindResolution.DoNotRebind: break; case RebindResolution.CreateConflict: RebindEntry(selectedEntry, newbinding); break; case RebindResolution.UnassignExistingAndBind: foreach (var conflictEntry in conflicts) RebindEntry(conflictEntry, new List<KeyCombination>()); RebindEntry(selectedEntry, newbinding); break; default: throw new Exception("Unhandled enum case"); } } } public void BindSelectedEntryTo(List<KeyCombination> keyCombination) { RebindEntry(selectedEntry, keyCombination); } public IList<ShortcutEntry> GetSelectedEntryConflictsForGivenKeyCombination(List<KeyCombination> temporaryCombination) { if (temporaryCombination.Count == 0) return null; return FindConflictsIfRebound(selectedEntry, temporaryCombination); } public IList<ShortcutEntry> GetShortcutsBoundTo(KeyCode keyCode, EventModifiers modifiers) { var keyCombination = KeyCombination.FromKeyboardInput(keyCode, modifiers); List<ShortcutEntry> entries; if (m_KeyBindingRootToBoundEntries.TryGetValue(keyCombination, out entries)) { return entries; } return null; } public bool IsEntryPartOfConflict(ShortcutEntry shortcutEntry) { return m_CategoryToEntriesList[k_CommandsWithConflicts].Contains(shortcutEntry); } //TODO: find a better place for this logic, Directory maybe? IList<ShortcutEntry> FindConflictsIfRebound(ShortcutEntry entry, List<KeyCombination> newCombination) { var conflictingShortcuts = new List<ShortcutEntry>(); m_Directory.FindPotentialConflicts(entry.context, entry.tag, newCombination, conflictingShortcuts, m_ContextManager); conflictingShortcuts.Remove(entry); return conflictingShortcuts; } bool IsSearching() { switch (searchMode) { case SearchOption.Name: return !string.IsNullOrEmpty(m_SerializedState.search); case SearchOption.Binding: return m_SerializedState.bindingsSearch.Any(); } return false; } void BuildKeyMapBindingStateData() { m_KeyBindingRootToBoundEntries = new Dictionary<KeyCombination, List<ShortcutEntry>>(); foreach (var entry in m_AllEntries) { var binding = entry.combinations; if (binding != null && binding.Any()) { var firstKeyBinding = binding.First(); if (!m_KeyBindingRootToBoundEntries.ContainsKey(firstKeyBinding)) { m_KeyBindingRootToBoundEntries[firstKeyBinding] = new List<ShortcutEntry>(); } m_KeyBindingRootToBoundEntries[firstKeyBinding].Add(entry); } } } public BindingState GetBindingStateForKeyWithModifiers(KeyCode keyCode, EventModifiers modifiers) { var keycombination = KeyCombination.FromKeyboardInput(keyCode, modifiers); List<ShortcutEntry> entries; bool foundEntries = m_KeyBindingRootToBoundEntries.TryGetValue(keycombination, out entries); if (Application.platform != RuntimePlatform.OSXEditor && (keycombination.modifiers & ShortcutModifiers.Action) != 0) { var altkeycombination = new KeyCombination(keycombination.keyCode, (keycombination.modifiers & ~ShortcutModifiers.Action) | ShortcutModifiers.Control); if (m_KeyBindingRootToBoundEntries.TryGetValue(altkeycombination, out List<ShortcutEntry> additionalEntries)) { foundEntries = true; if (entries == null) entries = new List<ShortcutEntry>(); entries.AddRange(additionalEntries); } } if (foundEntries) { var state = BindingState.NotBound; foreach (var entry in entries) state |= IsGlobalContext(entry) ? BindingState.BoundGlobally : BindingState.BoundToContext; return state; } return BindingState.NotBound; } public bool CanBeSelected(KeyCode code) { return !IsModifier(code) && !IsReservedKey(code); } public static bool IsModifier(KeyCode code) { return ModifierFromKeyCode(code) != EventModifiers.None; } bool IKeyBindingStateProvider.IsModifier(KeyCode code) { return IsModifier(code); } public bool IsReservedKey(KeyCode code) { return !IsModifier(code) && !m_BindingValidator.IsKeyValid(code, out _); } EventModifiers IKeyBindingStateProvider.ModifierFromKeyCode(KeyCode k) { return ModifierFromKeyCode(k); } public static EventModifiers ModifierFromKeyCode(KeyCode k) { switch (k) { case KeyCode.LeftShift: case KeyCode.RightShift: return EventModifiers.Shift; case KeyCode.LeftAlt: case KeyCode.RightAlt: return EventModifiers.Alt; case KeyCode.LeftControl: case KeyCode.RightControl: return EventModifiers.Control; case KeyCode.LeftCommand: case KeyCode.RightCommand: return SystemInfo.operatingSystemFamily == OperatingSystemFamily.MacOSX ? EventModifiers.Command : EventModifiers.None; default: return EventModifiers.None; } } static bool IsGlobalContext(ShortcutEntry entry) { return entry.context == ContextManager.globalContextType; } public void SelectConflictCategory() { SetCategorySelected(k_CommandsWithConflicts); GetView().RefreshCategoryList(); } public bool CanImportProfile(string path, bool letUserDecide = true) { if (string.IsNullOrWhiteSpace(path)) return false; var profileId = m_ShortcutProfileManager.GetProfileId(path); // This is mainly intended to disable modal dialogs when running tests letUserDecide = letUserDecide && InternalEditorUtility.isHumanControllingUs && !InternalEditorUtility.inBatchMode; if (m_ShortcutProfileManager.GetProfileById(profileId) != null && (!letUserDecide || !EditorUtility.DisplayDialog(L10n.Tr("Profile already exists"), L10n.Tr($"A profile with the \"{profileId}\" id already exists.\nDo you want to overwrite the existing profile with values from the selected file?"), L10n.Tr("Yes"), L10n.Tr("No")))) return false; return true; } public void ImportProfile(string path) { m_ShortcutProfileManager.ImportProfile(path); activeProfile = m_ShortcutProfileManager.GetProfileId(path); } public bool CanExportProfile() => m_ShortcutProfileManager.activeProfile != null; public void ExportProfile(string path) => m_ShortcutProfileManager.ExportProfile(path); } class ConflictComparer : IComparer<ShortcutEntry> { IComparer<IEnumerable<KeyCombination>> m_KeyCombinationSequenceComprarer; public ConflictComparer() { m_KeyCombinationSequenceComprarer = new KeyCombinationSequenceComparer(); } public int Compare(ShortcutEntry x, ShortcutEntry y) { return m_KeyCombinationSequenceComprarer.Compare(x?.combinations, y?.combinations); } } class KeyCombinationSequenceComparer : IComparer<IEnumerable<KeyCombination>> { IComparer<KeyCombination> m_KeyCombinationComparer; public KeyCombinationSequenceComparer() { m_KeyCombinationComparer = new KeyCombinationComparer(); } public int Compare(IEnumerable<KeyCombination> x, IEnumerable<KeyCombination> y) { if (x == null && y != null) return -1; if (x != null && y == null) return 1; if (x == null && y == null) return 0; var xEnum = x.GetEnumerator(); var yEnum = y.GetEnumerator(); var xValid = xEnum.MoveNext(); var yValid = yEnum.MoveNext(); while (xValid && yValid) { var elementCompare = m_KeyCombinationComparer.Compare(xEnum.Current, yEnum.Current); if (elementCompare != 0) { xEnum.Dispose(); yEnum.Dispose(); return elementCompare; } xValid = xEnum.MoveNext(); yValid = xEnum.MoveNext(); } xEnum.Dispose(); yEnum.Dispose(); if (xValid == yValid) return 0; if (xValid && !yValid) return 1; return -1; } } class KeyCombinationComparer : IComparer<KeyCombination> { public int Compare(KeyCombination x, KeyCombination y) { var modifierCompare = x.modifiers.CompareTo(y.modifiers); if (modifierCompare != 0) return modifierCompare; return x.keyCode.CompareTo(y.keyCode); } } class ShortcutNameComparer : IComparer<ShortcutEntry> { public int Compare(ShortcutEntry x, ShortcutEntry y) { return string.Compare(x?.displayName, y?.displayName); } } }
UnityCsReference/Modules/ShortcutManagerEditor/ShortcutManagerWindowViewController.cs/0
{ "file_path": "UnityCsReference/Modules/ShortcutManagerEditor/ShortcutManagerWindowViewController.cs", "repo_id": "UnityCsReference", "token_count": 16173 }
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 System.Linq; using UnityEngine; namespace UnityEditor.StyleSheets { internal static class GUISkinCompare { public static bool CompareTo(Color lhs, Color rhs) { return StyleSheetToUss.ToUssString(lhs) == StyleSheetToUss.ToUssString(rhs); } public static bool CompareTo(float lhs, float rhs) { return Math.Abs(lhs - rhs) <= 0.0001f; } public static bool CompareTo(this RectOffset lhs, RectOffset rhs) { // Returns false in the presence of NaN values. return rhs != null && (lhs != null && (lhs.left == rhs.left && lhs.right == rhs.right && lhs.top == rhs.top && lhs.bottom == rhs.bottom)); } public static bool CompareTo(this GUIStyleState self, GUIStyleState otherState, List<string> diffs = null, string prefix = "") { // Compare USS color notation to avoid rounding errors. if (!CompareTo(self.textColor, otherState.textColor)) { if (diffs == null) return false; diffs.Add(prefix + "textColor"); } if (self.background != otherState.background) { if (diffs == null) return false; diffs.Add(prefix + "background"); } if (!self.scaledBackgrounds.SequenceEqual(otherState.scaledBackgrounds)) { if (diffs == null) return false; diffs.Add(prefix + "scaledBackgrounds"); } return diffs == null || diffs.Count == 0; } public static bool CompareTo(this GUISettings self, GUISettings otherSettings, List<string> diffs = null) { if (!CompareTo(self.cursorColor, otherSettings.cursorColor)) { if (diffs == null) return false; diffs.Add("settings[cursorColor]"); } if (!CompareTo(self.selectionColor, otherSettings.selectionColor)) { if (diffs == null) return false; diffs.Add("settings[selectionColor]"); } if (!CompareTo(self.cursorFlashSpeed, otherSettings.cursorFlashSpeed)) { if (diffs == null) return false; diffs.Add("settings[cursorFlashSpeed]"); } if (self.doubleClickSelectsWord != otherSettings.doubleClickSelectsWord) { if (diffs == null) return false; diffs.Add("settings[doubleClickSelectsWord]"); } if (self.tripleClickSelectsLine != otherSettings.tripleClickSelectsLine) { if (diffs == null) return false; diffs.Add("settings[tripleClickSelectsLine]"); } return diffs == null || diffs.Count == 0; } public static bool CompareTo(this GUIStyle self, GUIStyle otherStyle, List<string> diffs = null, int index = -1) { var name = !String.IsNullOrEmpty(self.name) ? self.name : index.ToString(); var prefix = $"style[{name}]:"; if (self.imagePosition != otherStyle.imagePosition) { if (diffs == null) return false; diffs.Add(prefix + "imagePosition"); } if (self.alignment != otherStyle.alignment) { if (diffs == null) return false; diffs.Add(prefix + "alignment"); } if (self.wordWrap != otherStyle.wordWrap) { if (diffs == null) return false; diffs.Add(prefix + "wordWrap"); } if (self.clipping != otherStyle.clipping) { if (diffs == null) return false; diffs.Add(prefix + "clipping"); } if (self.contentOffset != otherStyle.contentOffset) { if (diffs == null) return false; diffs.Add(prefix + "contentOffset"); } if (!CompareTo(self.fixedWidth, otherStyle.fixedWidth)) { if (diffs == null) return false; diffs.Add(prefix + "fixedWidth"); } if (!CompareTo(self.fixedHeight, otherStyle.fixedHeight)) { if (diffs == null) return false; diffs.Add(prefix + "fixedHeight"); } if (self.stretchWidth != otherStyle.stretchWidth) { if (diffs == null) return false; diffs.Add(prefix + "stretchWidth"); } if (self.stretchHeight != otherStyle.stretchHeight) { if (diffs == null) return false; diffs.Add(prefix + "stretchHeight"); } if (self.fontSize != otherStyle.fontSize) { if (diffs == null) return false; diffs.Add(prefix + "fontSize"); } if (self.fontStyle != otherStyle.fontStyle) { if (diffs == null) return false; diffs.Add(prefix + "fontStyle"); } if (self.richText != otherStyle.richText) { if (diffs == null) return false; diffs.Add(prefix + "richText"); } if (!self.normal.CompareTo(otherStyle.normal, diffs, prefix + "state[normal]:")) { if (diffs == null) return false; } if (!self.hover.CompareTo(otherStyle.hover, diffs, prefix + "state[hover]:")) { if (diffs == null) return false; } if (!self.active.CompareTo(otherStyle.active, diffs, prefix + "state[active]:")) { if (diffs == null) return false; } if (!self.focused.CompareTo(otherStyle.focused, diffs, prefix + "state[focused]:")) { if (diffs == null) return false; } if (!self.onNormal.CompareTo(otherStyle.onNormal, diffs, prefix + "state[onNormal]:")) { if (diffs == null) return false; } if (!self.onHover.CompareTo(otherStyle.onHover, diffs, prefix + "state[onHover]:")) { if (diffs == null) return false; } if (!self.onActive.CompareTo(otherStyle.onActive, diffs, prefix + "state[onActive]:")) { if (diffs == null) return false; } if (!self.onFocused.CompareTo(otherStyle.onFocused, diffs, prefix + "state[onFocused]:")) { if (diffs == null) return false; } if (!self.border.CompareTo(otherStyle.border)) { if (diffs == null) return false; diffs.Add(prefix + "border"); } if (!self.margin.CompareTo(otherStyle.margin)) { if (diffs == null) return false; diffs.Add(prefix + "margin"); } if (!self.padding.CompareTo(otherStyle.padding)) { if (diffs == null) return false; diffs.Add(prefix + "padding"); } if (!self.overflow.CompareTo(otherStyle.overflow)) { if (diffs == null) return false; diffs.Add(prefix + "overflow"); } if (self.font != otherStyle.font) { if (diffs == null) return false; diffs.Add(prefix + "font"); } if (!CompareTo(self.lineHeight, otherStyle.lineHeight)) { if (diffs == null) return false; diffs.Add(prefix + "lineHeight"); } if (self.isHeightDependantOnWidth != otherStyle.isHeightDependantOnWidth) { if (diffs == null) return false; diffs.Add(prefix + "isHeightDependantOnWidth"); } return diffs == null || diffs.Count == 0; } public static bool CompareTo(this GUISkin self, GUISkin otherSkin, List<string> diffs = null) { if (self.font != otherSkin.font) { if (diffs == null) return false; diffs.Add("font"); } if (!self.box.CompareTo(otherSkin.box, diffs) && diffs == null) return false; if (!self.label.CompareTo(otherSkin.label, diffs) && diffs == null) return false; if (!self.textField.CompareTo(otherSkin.textField, diffs) && diffs == null) return false; if (!self.textArea.CompareTo(otherSkin.textArea, diffs) && diffs == null) return false; if (!self.button.CompareTo(otherSkin.button, diffs) && diffs == null) return false; if (!self.toggle.CompareTo(otherSkin.toggle, diffs) && diffs == null) return false; if (!self.window.CompareTo(otherSkin.window, diffs) && diffs == null) return false; if (!self.horizontalSlider.CompareTo(otherSkin.horizontalSlider, diffs) && diffs == null) return false; if (!self.horizontalSliderThumb.CompareTo(otherSkin.horizontalSliderThumb, diffs) && diffs == null) return false; if (!self.verticalSlider.CompareTo(otherSkin.verticalSlider, diffs) && diffs == null) return false; if (!self.verticalSliderThumb.CompareTo(otherSkin.verticalSliderThumb, diffs) && diffs == null) return false; if (!self.horizontalScrollbar.CompareTo(otherSkin.horizontalScrollbar, diffs) && diffs == null) return false; if (!self.horizontalScrollbarThumb.CompareTo(otherSkin.horizontalScrollbarThumb, diffs) && diffs == null) return false; if (!self.horizontalScrollbarLeftButton.CompareTo(otherSkin.horizontalScrollbarLeftButton, diffs) && diffs == null) return false; if (!self.horizontalScrollbarRightButton.CompareTo(otherSkin.horizontalScrollbarRightButton, diffs) && diffs == null) return false; if (!self.verticalScrollbar.CompareTo(otherSkin.verticalScrollbar, diffs) && diffs == null) return false; if (!self.verticalScrollbarThumb.CompareTo(otherSkin.verticalScrollbarThumb, diffs) && diffs == null) return false; if (!self.verticalScrollbarUpButton.CompareTo(otherSkin.verticalScrollbarUpButton, diffs) && diffs == null) return false; if (!self.verticalScrollbarDownButton.CompareTo(otherSkin.verticalScrollbarDownButton, diffs) && diffs == null) return false; if (!self.scrollView.CompareTo(otherSkin.scrollView, diffs) && diffs == null) return false; // Check custom styles int i = 0; bool areCustomStylesDifferent = self.customStyles.Length != otherSkin.customStyles.Length; foreach (var customStyle in self.customStyles) { var matchedStyle = String.IsNullOrEmpty(customStyle.name) ? otherSkin.customStyles.ElementAtOrDefault(i) : otherSkin.customStyles.FirstOrDefault(style => style.name == customStyle.name); if (matchedStyle == null) { if (diffs == null) return false; diffs.Add("customStyles"); areCustomStylesDifferent = true; } else { if (!customStyle.CompareTo(matchedStyle, diffs, i)) { if (diffs == null) return false; areCustomStylesDifferent = true; } } i++; } if (areCustomStylesDifferent) { if (diffs == null) return false; diffs.Add("customStyles"); } if (!self.settings.CompareTo(otherSkin.settings, diffs) && diffs == null) return false; return diffs == null || diffs.Count == 0; } } }
UnityCsReference/Modules/StyleSheetsEditor/Converters/GUISkinCompare.cs/0
{ "file_path": "UnityCsReference/Modules/StyleSheetsEditor/Converters/GUISkinCompare.cs", "repo_id": "UnityCsReference", "token_count": 7240 }
456
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License namespace UnityEngine { public interface ISubsystem { bool running { get; } void Start(); void Stop(); void Destroy(); } }
UnityCsReference/Modules/Subsystems/ISubsystem.cs/0
{ "file_path": "UnityCsReference/Modules/Subsystems/ISubsystem.cs", "repo_id": "UnityCsReference", "token_count": 120 }
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.SubsystemsImplementation { public abstract class SubsystemWithProvider : ISubsystem { public void Start() { if (running) return; OnStart(); providerBase.m_Running = true; running = true; } protected abstract void OnStart(); public void Stop() { if (!running) return; OnStop(); providerBase.m_Running = false; running = false; } protected abstract void OnStop(); public void Destroy() { Stop(); if (SubsystemManager.RemoveStandaloneSubsystem(this)) OnDestroy(); } protected abstract void OnDestroy(); public bool running { get; private set; } internal SubsystemProvider providerBase { get; set; } internal abstract void Initialize(SubsystemDescriptorWithProvider descriptor, SubsystemProvider subsystemProvider); internal abstract SubsystemDescriptorWithProvider descriptor { get; } } public abstract class SubsystemWithProvider<TSubsystem, TSubsystemDescriptor, TProvider> : SubsystemWithProvider where TSubsystem : SubsystemWithProvider, new() where TSubsystemDescriptor : SubsystemDescriptorWithProvider where TProvider : SubsystemProvider<TSubsystem> { public TSubsystemDescriptor subsystemDescriptor { get; private set; } protected internal TProvider provider { get; private set; } protected virtual void OnCreate() {} protected override void OnStart() => provider.Start(); protected override void OnStop() => provider.Stop(); protected override void OnDestroy() => provider.Destroy(); internal override sealed void Initialize(SubsystemDescriptorWithProvider descriptor, SubsystemProvider provider) { providerBase = provider; this.provider = (TProvider)provider; subsystemDescriptor = (TSubsystemDescriptor)descriptor; OnCreate(); } internal override sealed SubsystemDescriptorWithProvider descriptor => subsystemDescriptor; } namespace Extensions { public static class SubsystemExtensions { public static TProvider GetProvider<TSubsystem, TDescriptor, TProvider>( this SubsystemWithProvider<TSubsystem, TDescriptor, TProvider> subsystem) where TSubsystem : SubsystemWithProvider, new() where TDescriptor : SubsystemDescriptorWithProvider<TSubsystem, TProvider> where TProvider : SubsystemProvider<TSubsystem> { return subsystem.provider; } } } }
UnityCsReference/Modules/Subsystems/SubsystemWithProvider.cs/0
{ "file_path": "UnityCsReference/Modules/Subsystems/SubsystemWithProvider.cs", "repo_id": "UnityCsReference", "token_count": 1174 }
458
// 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 { internal class HeightmapFilters { public static void Smooth(float[,] heights, TerrainData terrain) { float[,] oldHeights = heights.Clone() as float[, ]; int width = heights.GetLength(1); int height = heights.GetLength(0); for (int y = 1; y < height - 1; y++) { for (int x = 1; x < width - 1; x++) { float h = 0.0F; h += oldHeights[y, x]; h += oldHeights[y, x - 1]; h += oldHeights[y, x + 1]; h += oldHeights[y - 1, x]; h += oldHeights[y + 1, x]; h /= 5.0F; heights[y, x] = h; } } } public static void Smooth(TerrainData terrain) { int r = terrain.heightmapResolution; float[,] heights = terrain.GetHeights(0, 0, r, r); Smooth(heights, terrain); terrain.SetHeights(0, 0, heights); } public static void Flatten(TerrainData terrain, float height) { int r = terrain.heightmapResolution; float[,] heights = new float[r, r]; for (int y = 0; y < r; y++) { for (int x = 0; x < r; x++) { heights[y, x] = height; } } terrain.SetHeights(0, 0, heights); } } } //namespace
UnityCsReference/Modules/TerrainEditor/HeightmapFilters.cs/0
{ "file_path": "UnityCsReference/Modules/TerrainEditor/HeightmapFilters.cs", "repo_id": "UnityCsReference", "token_count": 947 }
459
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections; using System.Collections.Generic; using UnityEditor; using UnityEngine; using UnityEngine.Scripting.APIUpdating; using UnityEngine.TerrainTools; namespace UnityEditor.TerrainTools { [MovedFrom("UnityEditor.Experimental.TerrainAPI")] [Flags] public enum BrushGUIEditFlags { None = 0, Select = 1, Inspect = 2, Size = 4, Opacity = 8, SelectAndInspect = 3, All = 15, } [MovedFrom("UnityEditor.Experimental.TerrainAPI")] [Flags] public enum RepaintFlags { UI = 1, Scene = 2, } [MovedFrom("UnityEditor.Experimental.TerrainAPI")] public interface IOnPaint { Texture brushTexture { get; } Vector2 uv { get; } float brushStrength { get; } float brushSize { get; } bool hitValidTerrain { get; } RaycastHit raycastHit { get; } [Obsolete("IOnPaint.RepaintAllInspectors has been deprecated. Use IOnPaint.Repaint instead")] void RepaintAllInspectors(); void Repaint(RepaintFlags flags = RepaintFlags.UI); } [MovedFrom("UnityEditor.Experimental.TerrainAPI")] public interface IOnSceneGUI { SceneView sceneView { get; } Texture brushTexture { get; } float brushStrength { get; } float brushSize { get; } bool hitValidTerrain { get; } RaycastHit raycastHit { get; } int controlId { get; } void Repaint(RepaintFlags flags = RepaintFlags.UI); } [MovedFrom("UnityEditor.Experimental.TerrainAPI")] public interface IOnInspectorGUI { void ShowBrushesGUI(int spacing = 5, BrushGUIEditFlags flags = BrushGUIEditFlags.All, int textureResolutionPerTile = 0); void Repaint(RepaintFlags flags = RepaintFlags.UI); } internal interface ITerrainPaintTool { string GetName(); string GetDescription(); void OnEnable(); void OnDisable(); void OnEnterToolMode(); void OnExitToolMode(); void OnSceneGUI(Terrain terrain, IOnSceneGUI editContext); void OnRenderBrushPreview(Terrain terrain, IOnSceneGUI editContext); void OnInspectorGUI(Terrain terrain, IOnInspectorGUI editContext); bool OnPaint(Terrain terrain, IOnPaint editContext); } [MovedFrom("UnityEditor.Experimental.TerrainAPI")] public abstract class TerrainPaintTool<T> : ScriptableSingleton<T>, ITerrainPaintTool where T : TerrainPaintTool<T> { public abstract string GetName(); public abstract string GetDescription(); public virtual void OnEnable() {} public virtual void OnDisable() {} public virtual void OnEnterToolMode() {} public virtual void OnExitToolMode() {} public virtual void OnSceneGUI(Terrain terrain, IOnSceneGUI editContext) {} public virtual void OnRenderBrushPreview(Terrain terrain, IOnSceneGUI editContext) {} public virtual void OnInspectorGUI(Terrain terrain, IOnInspectorGUI editContext) {} public virtual bool OnPaint(Terrain terrain, IOnPaint editContext) { return false; } } internal interface ITerrainPaintToolWithOverlays : ITerrainPaintTool { string OnIcon { get; } string OffIcon { get; } int IconIndex { get { return 0;} } TerrainCategory Category { get { return TerrainCategory.CustomBrushes; } } bool HasBrushMask => false; bool HasBrushAttributes => false; bool HasToolSettings => false; [Obsolete("Use OnToolSettingsGUI without the overlays boolean")] void OnToolSettingsGUI(Terrain terrain, IOnInspectorGUI editContext, bool overlays); void OnToolSettingsGUI(Terrain terrain, IOnInspectorGUI editorContext); [Obsolete("Use OnInspectorGUI without the overlays boolean")] void OnInspectorGUI(Terrain terrain, IOnInspectorGUI editContext, bool overlays); } public enum TerrainCategory { Sculpt, Materials, Foliage, NeighborTerrains, CustomBrushes, } // the indices are incremented by 10 so that customTools/terrainTools can have values that slip in between them public enum SculptIndex { PaintHeight = 100, SetHeight = 101, Holes = 103, Stamp = 201, Smooth = 305, } public enum MaterialIndex { PaintTexture = 10, } public enum FoliageIndex { PaintDetails = 10, PaintTrees = 20, } public enum NeighborTerrainsIndex { CreateTerrain = 10, } public abstract class TerrainPaintToolWithOverlays<T> : TerrainPaintToolWithOverlaysBase where T : TerrainPaintToolWithOverlays<T> { } // TerrainPaintTool is the old paint tool type which inherits from ScriptableSingleton // TerrainPaintToolWithOverlays is a new type of paint tool which inherits from EditorTools and is used in Overlays // there are additional variables that come with this new type, such as TerrainCategory and HasToolSettings public abstract class TerrainPaintToolWithOverlaysBase : EditorTools.EditorTool, ITerrainPaintToolWithOverlays { static OnSceneGUIContext s_OnSceneGUIContext = new OnSceneGUIContext(null, new RaycastHit(), null, 0.0f, 0.0f, 0); static OnPaintContext s_OnPaintContext = new OnPaintContext(new RaycastHit(), null, Vector2.zero, 0.0f, 0.0f); static Terrain s_LastActiveTerrain; public virtual string OnIcon => "TerrainOverlays/CustomBrushes_On.png"; public virtual string OffIcon => "TerrainOverlays/CustomBrushes.png"; public virtual int IconIndex { get { return 0; } } public virtual TerrainCategory Category { get { return TerrainCategory.CustomBrushes; } } // the categories that exist so far // Sculpt // Materials // Foliage // NeighborTerrains // CustomBrushes public virtual bool HasToolSettings => false; public virtual bool HasBrushMask => false; public virtual bool HasBrushAttributes => false; [Obsolete("Use OnToolSettingsGUI without the overlays boolean")] public virtual void OnToolSettingsGUI(Terrain terrain, IOnInspectorGUI editContext, bool overlays) { } public virtual void OnToolSettingsGUI(Terrain terrain, IOnInspectorGUI editContext) { } public Terrain Terrain { get; set; } public abstract string GetName(); public abstract string GetDescription(); public virtual void OnEnable() {} public virtual void OnDisable() {} public virtual void OnEnterToolMode() { } public virtual void OnExitToolMode() { } public virtual void OnInspectorGUI(Terrain terrain, IOnInspectorGUI editContext) { } [Obsolete("Use OnInspectorGUI without the overlays boolean")] public virtual void OnInspectorGUI(Terrain terrain, IOnInspectorGUI editContext, bool overlays) { } public virtual void OnSceneGUI(Terrain terrain, IOnSceneGUI editContext) { } public virtual void OnRenderBrushPreview(Terrain terrain, IOnSceneGUI editContext) { } public virtual bool OnPaint(Terrain terrain, IOnPaint editContext) { return false; } public override void OnActivated() { OnEnterToolMode(); } public override void OnWillBeDeactivated() { PaintContext.ApplyDelayedActions(); OnExitToolMode(); } public override void OnToolGUI(EditorWindow window) { Terrain = null; // currently this is always true but assert in case it changes in the future var sceneView = (SceneView)window; Debug.Assert(sceneView != null, $"TerrainTool::OnToolGUI - SceneView window is null. This is being called from a different type of window: {window.GetType()}"); var editor = TerrainInspector.s_activeTerrainInspectorInstance; // this can happen if the user selects the terrain tool from the tool history without // having a terrain object selected if(editor == null) { return; } // this happens for one frame after terrain is deselected or when the // user is using box selection in the sceneview. // target might also be null if the user has selected the terrain tool // from the editor tool history and doesn't have a terrain selected if (target == null) { return; } // there's a chance target could be a GameObject or a Terrain depending on // what we do with Selection.activeObject. Might be GameObject at first but // then we set activeObject to Terrain sometimes during painting. if(target.GetType() == typeof(GameObject)) { Terrain = ((GameObject)target).GetComponent<Terrain>(); } else if(target.GetType() == typeof(Terrain)) { Terrain = (Terrain)target; } Event e = Event.current; TerrainInspector.RaycastAllTerrains(out var hitTerrain, out var raycastHit); Texture brushTexture = this.GetType() == typeof(PaintTreesTool) ? editor.brushList.GetCircleBrush().texture : editor.brushList.GetActiveBrush().texture; Vector2 uv = raycastHit.textureCoord; bool hitValidTerrain = (hitTerrain != null && hitTerrain.terrainData != null); if (hitValidTerrain) { editor.HotkeyApply(raycastHit.distance); } int id = GUIUtility.GetControlID(TerrainInspector.s_TerrainEditorHash, FocusType.Passive); // last active terrain is used in case user is in the middle of a painting operation but the mouse is no longer hovering over a terrain tile, // in which case hitTerrain will be null. we want to permit the continuation of the current painting op in this situation // if m_terrain is null then try to get the activeGameobject if it is a terrain if (!Terrain && Selection.activeGameObject && Selection.activeGameObject.GetComponent<Terrain>()) { Terrain = Selection.activeGameObject.GetComponent<Terrain>(); } // set the last hit terrain Terrain lastActiveTerrain = hitValidTerrain ? hitTerrain : s_LastActiveTerrain; if (lastActiveTerrain) { OnSceneGUI(lastActiveTerrain, s_OnSceneGUIContext.Set(sceneView, hitValidTerrain, raycastHit, brushTexture, editor.brushStrength, editor.brushSize, id)); if (e.type == EventType.Repaint) { var mousePos = Event.current.mousePosition; var cameraRect = sceneView.cameraViewport; cameraRect.y = 0; var isMouseInSceneView = cameraRect.Contains(mousePos); if (EditorGUIUtility.hotControl == id || (isMouseInSceneView && EditorGUIUtility.hotControl == 0)) { OnRenderBrushPreview(lastActiveTerrain, s_OnSceneGUIContext); } } } var eventType = e.GetTypeForControl(id); if (!hitValidTerrain) { // if we release the mouse button outside the terrain we still need to update the terrains if (eventType == EventType.MouseUp) PaintContext.ApplyDelayedActions(); return; } s_LastActiveTerrain = hitTerrain; // user might start painting on one Terrain but end painting on another, and that Terrain needs to be the new selection bool changeSelection = false; switch (eventType) { case EventType.Layout: HandleUtility.AddDefaultControl(id); break; case EventType.MouseMove: if (hitTerrain) { HandleUtility.Repaint(); } break; case EventType.MouseDown: case EventType.MouseDrag: { if(EditorGUIUtility.hotControl != id) { if(EditorGUIUtility.hotControl != 0 || eventType == EventType.MouseDrag) { return; } } // If user is ALT-dragging, we want to return to main routine if (e.alt) return; // allow painting with LMB only if (e.button != 0) { return; } HandleUtility.AddDefaultControl(id); if (HandleUtility.nearestControl != id) { return; } if (e.type == EventType.MouseDown) { EditorGUIUtility.hotControl = id; } if (OnPaint(hitTerrain, s_OnPaintContext.Set(hitValidTerrain, raycastHit, brushTexture, uv, editor.brushStrength, editor.brushSize))) { hitTerrain.editorRenderFlags = TerrainRenderFlags.Heightmap; } if (Terrain != hitTerrain && e.type == EventType.MouseDown) { changeSelection = true; } e.Use(); } break; case EventType.MouseUp: { if (GUIUtility.hotControl != id) return; GUIUtility.hotControl = 0; if (Terrain != hitTerrain) changeSelection = true; PaintContext.ApplyDelayedActions(); e.Use(); } break; } if (changeSelection) Selection.activeObject = hitTerrain; } } internal class OnPaintContext : IOnPaint { internal Texture m_BrushTexture = null; internal Vector2 m_UV = Vector2.zero; internal float m_BrushStrength = 0.0f; internal float m_BrushSize = 0; internal bool m_HitValidTerrain = false; internal RaycastHit m_RaycastHit; public OnPaintContext(RaycastHit raycastHit, Texture brushTexture, Vector2 uv, float brushStrength, float brushSize) { Set(false, raycastHit, brushTexture, uv, brushStrength, brushSize); } public OnPaintContext Set(bool hitValidTerrain, RaycastHit raycastHit, Texture brushTexture, Vector2 uv, float brushStrength, float brushSize) { m_BrushTexture = brushTexture; m_UV = uv; m_BrushStrength = brushStrength; m_BrushSize = brushSize; m_HitValidTerrain = hitValidTerrain; m_RaycastHit = raycastHit; return this; } public Texture brushTexture { get { return m_BrushTexture; } } public Vector2 uv { get { return m_UV; } } public float brushStrength { get { return m_BrushStrength; } } public float brushSize { get { return m_BrushSize; } } public bool hitValidTerrain { get { return m_HitValidTerrain; } } public RaycastHit raycastHit { get { return m_RaycastHit; } } public void RepaintAllInspectors() { Repaint(RepaintFlags.UI); } public void Repaint(RepaintFlags flags) { if ((flags & RepaintFlags.UI) != 0) { InspectorWindow.RepaintAllInspectors(); } if ((flags & RepaintFlags.Scene) != 0) { EditorApplication.SetSceneRepaintDirty(); } } } internal class OnSceneGUIContext : IOnSceneGUI { internal SceneView m_SceneView = null; internal Texture m_BrushTexture = null; internal float m_BrushStrength = 0.0f; internal float m_BrushSize = 0; internal bool m_HitValidTerrain = false; internal RaycastHit m_RaycastHit; internal int m_ControlId; public OnSceneGUIContext(SceneView sceneView, RaycastHit raycastHit, Texture brushTexture, float brushStrength, float brushSize, int controlId) { Set(sceneView, false, raycastHit, brushTexture, brushStrength, brushSize, controlId); } public OnSceneGUIContext Set(SceneView sceneView, bool hitValidTerrain, RaycastHit raycastHit, Texture brushTexture, float brushStrength, float brushSize, int controlId) { m_SceneView = sceneView; m_BrushTexture = brushTexture; m_BrushStrength = brushStrength; m_BrushSize = brushSize; m_HitValidTerrain = hitValidTerrain; m_RaycastHit = raycastHit; m_ControlId = controlId; return this; } public SceneView sceneView { get { return m_SceneView; } } public Texture brushTexture { get { return m_BrushTexture; } } public float brushStrength { get { return m_BrushStrength; } } public float brushSize { get { return m_BrushSize; } } public bool hitValidTerrain { get { return m_HitValidTerrain; } } public RaycastHit raycastHit { get { return m_RaycastHit; } } public int controlId { get { return m_ControlId; } } public void Repaint(RepaintFlags flags) { if ((flags & RepaintFlags.UI) != 0) { InspectorWindow.RepaintAllInspectors(); } if ((flags & RepaintFlags.Scene) != 0) { EditorApplication.SetSceneRepaintDirty(); } } } public class OnInspectorGUIContext : IOnInspectorGUI { public OnInspectorGUIContext() {} public void ShowBrushesGUI(int spacing = 5, BrushGUIEditFlags flags = BrushGUIEditFlags.All, int textureResolutionPerTile = 0) { if (flags == BrushGUIEditFlags.None || TerrainInspector.s_activeTerrainInspectorInstance == null) // null check for adding and removing package { return; } TerrainInspector.s_activeTerrainInspectorInstance.ShowBrushes( spacing, (flags & BrushGUIEditFlags.Select) != 0, (flags & BrushGUIEditFlags.Inspect) != 0, (flags & BrushGUIEditFlags.Size) != 0, (flags & BrushGUIEditFlags.Opacity) != 0, textureResolutionPerTile); } public void Repaint(RepaintFlags flags) { if ((flags & RepaintFlags.UI) != 0) { InspectorWindow.RepaintAllInspectors(); } if ((flags & RepaintFlags.Scene) != 0) { EditorApplication.SetSceneRepaintDirty(); } } } }
UnityCsReference/Modules/TerrainEditor/PaintTools/TerrainPaintTool.cs/0
{ "file_path": "UnityCsReference/Modules/TerrainEditor/PaintTools/TerrainPaintTool.cs", "repo_id": "UnityCsReference", "token_count": 8911 }
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.Runtime.InteropServices; using UnityEngine.Bindings; using UnityEngine.Scripting; namespace UnityEngine.TextCore.LowLevel { /// <summary> /// A GlyphAnchorPoint defines the position of an anchor point relative to the origin of a glyph. /// This data structure is used by the Mark-to-Base, Mark-to-Mark and Mark-to-Ligature OpenType font features. /// </summary> [Serializable] [UsedByNativeCode] [StructLayout(LayoutKind.Sequential)] [VisibleToOtherModules("UnityEngine.TextCoreTextEngineModule")] internal struct GlyphAnchorPoint { /// <summary> /// The x coordinate of the anchor point relative to the glyph. /// </summary> public float xCoordinate { get { return m_XCoordinate; } set { m_XCoordinate = value; } } /// <summary> /// The y coordinate of the anchor point relative to the glyph. /// </summary> public float yCoordinate { get { return m_YCoordinate; } set { m_YCoordinate = value; } } // ============================================= // Private backing fields for public properties. // ============================================= [SerializeField] [NativeName("xPositionAdjustment")] private float m_XCoordinate; [SerializeField] [NativeName("yPositionAdjustment")] private float m_YCoordinate; } /// <summary> /// A MarkPositionAdjustment defines the positional adjustment of a glyph relative to the anchor point of base glyph. /// This data structure is used by the Mark-to-Base, Mark-to-Mark and Mark-to-Ligature OpenType font features. /// </summary> [Serializable] [UsedByNativeCode] [StructLayout(LayoutKind.Sequential)] [VisibleToOtherModules("UnityEngine.TextCoreTextEngineModule")] internal struct MarkPositionAdjustment { /// <summary> /// The horizontal positional adjustment of the glyph relative to the anchor point of its parent base glyph. /// </summary> public float xPositionAdjustment { get { return m_XPositionAdjustment; } set { m_XPositionAdjustment = value; } } /// <summary> /// The vertical positional adjustment of the glyph relative to the anchor point of its parent base glyph. /// </summary> public float yPositionAdjustment { get { return m_YPositionAdjustment; } set { m_YPositionAdjustment = value; } } /// <summary> /// Constructor for a new MarkPositionAdjustment. /// </summary> /// <param name="x">The horizontal positional adjustment.</param> /// <param name="y">The vertical positional adjustment.</param> public MarkPositionAdjustment(float x, float y) { m_XPositionAdjustment = x; m_YPositionAdjustment = y; } // ============================================= // Private backing fields for public properties. // ============================================= [SerializeField] [NativeName("xCoordinate")] private float m_XPositionAdjustment; [SerializeField] [NativeName("yCoordinate")] private float m_YPositionAdjustment; }; /// <summary> /// A MarkToBaseAdjustmentRecord defines the positional adjustment between a base glyph and mark glyph. /// </summary> [Serializable] [UsedByNativeCode] [StructLayout(LayoutKind.Sequential)] [VisibleToOtherModules("UnityEngine.TextCoreTextEngineModule")] internal struct MarkToBaseAdjustmentRecord { /// <summary> /// The index of the base glyph. /// </summary> public uint baseGlyphID { get { return m_BaseGlyphID; } set { m_BaseGlyphID = value; } } /// <summary> /// The position of the anchor point of the base glyph. /// </summary> public GlyphAnchorPoint baseGlyphAnchorPoint { get { return m_BaseGlyphAnchorPoint; } set { m_BaseGlyphAnchorPoint = value; } } /// <summary> /// The index of the mark glyph. /// </summary> public uint markGlyphID { get { return m_MarkGlyphID; } set { m_MarkGlyphID = value; } } /// <summary> /// The positional adjustment of the mark glyph relative to the anchor point of the base glyph. /// </summary> public MarkPositionAdjustment markPositionAdjustment { get { return m_MarkPositionAdjustment; } set { m_MarkPositionAdjustment = value; } } // ============================================= // Private backing fields for public properties. // ============================================= [SerializeField] [NativeName("baseGlyphID")] private uint m_BaseGlyphID; [SerializeField] [NativeName("baseAnchor")] private GlyphAnchorPoint m_BaseGlyphAnchorPoint; [SerializeField] [NativeName("markGlyphID")] private uint m_MarkGlyphID; [SerializeField] [NativeName("markPositionAdjustment")] private MarkPositionAdjustment m_MarkPositionAdjustment; } /// <summary> /// A MarkToMarkAdjustmentRecord defines the positional adjustment between two mark glyphs. /// </summary> [Serializable] [UsedByNativeCode] [StructLayout(LayoutKind.Sequential)] [VisibleToOtherModules("UnityEngine.TextCoreTextEngineModule")] internal struct MarkToMarkAdjustmentRecord { /// <summary> /// The index of the base glyph. /// </summary> public uint baseMarkGlyphID { get { return m_BaseMarkGlyphID; } set { m_BaseMarkGlyphID = value; } } /// <summary> /// The position of the anchor point of the base mark glyph. /// </summary> public GlyphAnchorPoint baseMarkGlyphAnchorPoint { get { return m_BaseMarkGlyphAnchorPoint; } set { m_BaseMarkGlyphAnchorPoint = value; } } /// <summary> /// The index of the mark glyph. /// </summary> public uint combiningMarkGlyphID { get { return m_CombiningMarkGlyphID; } set { m_CombiningMarkGlyphID = value; } } /// <summary> /// The positional adjustment of the combining mark glyph relative to the anchor point of the base mark glyph. /// </summary> public MarkPositionAdjustment combiningMarkPositionAdjustment { get { return m_CombiningMarkPositionAdjustment; } set { m_CombiningMarkPositionAdjustment = value; } } // ============================================= // Private backing fields for public properties. // ============================================= [SerializeField] [NativeName("baseMarkGlyphID")] private uint m_BaseMarkGlyphID; [SerializeField] [NativeName("baseMarkAnchor")] private GlyphAnchorPoint m_BaseMarkGlyphAnchorPoint; [SerializeField] [NativeName("combiningMarkGlyphID")] private uint m_CombiningMarkGlyphID; [SerializeField] [NativeName("combiningMarkPositionAdjustment")] private MarkPositionAdjustment m_CombiningMarkPositionAdjustment; } }
UnityCsReference/Modules/TextCoreFontEngine/Managed/FontFeatureCommonGPOS.cs/0
{ "file_path": "UnityCsReference/Modules/TextCoreFontEngine/Managed/FontFeatureCommonGPOS.cs", "repo_id": "UnityCsReference", "token_count": 2636 }
461
// 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; namespace UnityEngine.TextCore.Text { /// <summary> /// Copy of MeshInfo, where we pass only the parameters necessary for rendering on the Native side /// </summary> [StructLayout(LayoutKind.Sequential)] [NativeHeader("Modules/TextCoreTextEngine/Native/MeshInfo.h")] [UsedByNativeCode("MeshInfo")] [VisibleToOtherModules("UnityEngine.IMGUIModule")] internal struct MeshInfoBindings { public TextCoreVertex[] vertexData; public Material material; public int vertexCount; } }
UnityCsReference/Modules/TextCoreTextEngine/Managed/MeshInfo.bindings.cs/0
{ "file_path": "UnityCsReference/Modules/TextCoreTextEngine/Managed/MeshInfo.bindings.cs", "repo_id": "UnityCsReference", "token_count": 265 }
462
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; namespace UnityEngine.TextCore.Text { [Serializable][ExcludeFromPresetAttribute][ExcludeFromObjectFactory] public class TextStyleSheet : ScriptableObject { /// <summary> /// /// </summary> internal List<TextStyle> styles { get { return m_StyleList; } } [SerializeField] private List<TextStyle> m_StyleList = new List<TextStyle>(1); private Dictionary<int, TextStyle> m_StyleLookupDictionary; private void Reset() { LoadStyleDictionaryInternal(); } object styleLookupLock = new object(); /// <summary> /// Get the Style for the given hash code value. /// </summary> /// <param name="hashCode">Hash code of the style.</param> /// <returns>The style matching the hash code.</returns> public TextStyle GetStyle(int hashCode) { if (m_StyleLookupDictionary == null) { lock (styleLookupLock) { if (m_StyleLookupDictionary == null) LoadStyleDictionaryInternal(); } } TextStyle style; if (m_StyleLookupDictionary.TryGetValue(hashCode, out style)) return style; return null; } /// <summary> /// Get the Style for the given name. /// </summary> /// <param name="name">The name of the style.</param> /// <returns>The style if found.</returns> public TextStyle GetStyle(string name) { if (m_StyleLookupDictionary == null) LoadStyleDictionaryInternal(); int hashCode = TextUtilities.GetHashCodeCaseInSensitive(name); TextStyle style; if (m_StyleLookupDictionary.TryGetValue(hashCode, out style)) return style; return null; } /// <summary> /// Function to refresh the Style Dictionary. /// </summary> public void RefreshStyles() { LoadStyleDictionaryInternal(); } /// <summary> /// /// </summary> private void LoadStyleDictionaryInternal() { Dictionary<int, TextStyle> styleLookup = m_StyleLookupDictionary; if (styleLookup == null) styleLookup = new Dictionary<int, TextStyle>(); else styleLookup.Clear(); // Read Styles from style list and store them into dictionary for faster access. for (int i = 0; i < m_StyleList.Count; i++) { m_StyleList[i].RefreshStyle(); if (!styleLookup.ContainsKey(m_StyleList[i].hashCode)) styleLookup.Add(m_StyleList[i].hashCode, m_StyleList[i]); } // Add Normal Style if it does not already exists int normalStyleHashCode = TextUtilities.GetHashCodeCaseInSensitive("Normal"); if (!styleLookup.ContainsKey(normalStyleHashCode)) { TextStyle style = new TextStyle("Normal", string.Empty, string.Empty); m_StyleList.Add(style); styleLookup.Add(normalStyleHashCode, style); } m_StyleLookupDictionary = styleLookup; //// Event to update objects when styles are changed in the editor. TextEventManager.ON_TEXT_STYLE_PROPERTY_CHANGED(true); } } }
UnityCsReference/Modules/TextCoreTextEngine/Managed/TextAssets/TextStyleSheet.cs/0
{ "file_path": "UnityCsReference/Modules/TextCoreTextEngine/Managed/TextAssets/TextStyleSheet.cs", "repo_id": "UnityCsReference", "token_count": 1729 }
463
// 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; namespace UnityEngine.TextCore.Text { [StructLayout(LayoutKind.Sequential)] [NativeHeader("Modules/TextCoreTextEngine/Native/TextLib.h")] [VisibleToOtherModules("UnityEngine.UIElementsModule","Unity.UIElements.PlayModeTests")] internal class TextLib { private readonly IntPtr m_Ptr; [VisibleToOtherModules("UnityEngine.UIElementsModule")] internal TextLib() { m_Ptr = GetInstance(); } private static extern IntPtr GetInstance(); [VisibleToOtherModules("UnityEngine.UIElementsModule")] internal NativeTextInfo GenerateText(NativeTextGenerationSettings settings) { var textInfo = GenerateTextInternal(settings); var textElementInfos = textInfo.textElementInfos; textInfo.fontAssets = new FontAsset[textInfo.fontAssetIds.Length]; int previousLastGlyphIndex = 0; for (int i = 0; i < textInfo.fontAssetIds.Length; i++) { var fa = FontAsset.GetFontAssetByID(textInfo.fontAssetIds[i]); textInfo.fontAssets[i] = fa; for (int j = previousLastGlyphIndex; j < textInfo.fontAssetLastGlyphIndex[i]; j++) { var glyphID = textElementInfos[j].glyphID; bool success = fa.TryAddGlyphInternal((uint)glyphID, out var glyph); if (!success) continue; var glyphRect = glyph.glyphRect; Vector2 uv0; uv0.x = (float)glyphRect.x / fa.atlasWidth; uv0.y = (float)glyphRect.y / fa.atlasHeight; Vector2 uv1; uv1.x = uv0.x; uv1.y = (float)(glyphRect.y + glyphRect.height) / fa.atlasHeight; Vector2 uv2; uv2.x = (float)(glyphRect.x + glyphRect.width) / fa.atlasWidth; uv2.y = uv1.y; Vector2 uv3; uv3.x = uv2.x; uv3.y = uv0.y; textElementInfos[j].bottomLeft.uv0 = uv0; textElementInfos[j].topLeft.uv0 = uv1; textElementInfos[j].topRight.uv0 = uv2; textElementInfos[j].bottomRight.uv0 = uv3; } previousLastGlyphIndex = textInfo.fontAssetLastGlyphIndex[i]; } return textInfo; } [NativeMethod(Name = "TextLib::GenerateText")] private extern NativeTextInfo GenerateTextInternal(NativeTextGenerationSettings settings); internal static class BindingsMarshaller { public static IntPtr ConvertToNative(TextLib textLib) => textLib.m_Ptr; } static byte[] s_ICUData = null; internal static Func<UnityEngine.TextAsset> GetICUAssetEditorDelegate; private static UnityEngine.TextAsset GetICUAsset() { if (GetICUAssetEditorDelegate != null) { //Editor will load the ICU library before the scene, so we need to check in the asset database as the asset may not be loaded yet. var asset = GetICUAssetEditorDelegate(); if (asset != null) return asset; } else { Debug.LogError("GetICUAssetEditorDelegate is null"); } // Dont know about the panelSettings class existence here so we must filter by name foreach( var t in Resources.FindObjectsOfTypeAll<UnityEngine.TextAsset>()) { if (t.name == "icudt73l") return t; } return null; } [RequiredByNativeCode] internal static int LoadAndCountICUdata() { s_ICUData = GetICUAsset()?.bytes; return s_ICUData?.Length ?? 0; } [VisibleToOtherModules("Unity.UIElements.PlayModeTests")] [RequiredByNativeCode] internal static bool GetICUdata(Span<byte> data, int maxSize) { if (s_ICUData == null) LoadAndCountICUdata(); Debug.Assert(s_ICUData != null, "s_ICUData not initialized"); Debug.Assert(maxSize == s_ICUData.Length); s_ICUData.CopyTo(data); s_ICUData = null; return true; } } }
UnityCsReference/Modules/TextCoreTextEngine/Managed/TextGenerator/TextLib.bindings.cs/0
{ "file_path": "UnityCsReference/Modules/TextCoreTextEngine/Managed/TextGenerator/TextLib.bindings.cs", "repo_id": "UnityCsReference", "token_count": 2374 }
464
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEditor; using System.IO; using Unity.Collections; namespace UnityEngine.TextCore.Text { [InitializeOnLoad] internal class ICUDataAssetUtilities { private static string k_ICUDataAssetPath = "Assets/UI Toolkit/icudt73l.bytes"; internal static void CreateAsset() { var directory = Path.GetDirectoryName(k_ICUDataAssetPath); if (!Directory.Exists(directory)) { Directory.CreateDirectory(directory); } var filePath = Path.Combine(EditorApplication.applicationContentsPath, "Resources/icudt73l.dat"); File.Copy(filePath, k_ICUDataAssetPath, true); AssetDatabase.ImportAsset(k_ICUDataAssetPath, ImportAssetOptions.ForceSynchronousImport); } static ICUDataAssetUtilities() { TextLib.GetICUAssetEditorDelegate = GetICUAsset; } internal static UnityEngine.TextAsset GetICUAsset() { return AssetDatabase.LoadAssetAtPath<UnityEngine.TextAsset>(k_ICUDataAssetPath); } } }
UnityCsReference/Modules/TextCoreTextEngineEditor/Managed/ICUDataAssetUtilities.cs/0
{ "file_path": "UnityCsReference/Modules/TextCoreTextEngineEditor/Managed/ICUDataAssetUtilities.cs", "repo_id": "UnityCsReference", "token_count": 514 }
465
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System.IO; using System.Collections.Generic; using UnityEngine; using UnityEngine.TextCore.Text; using TextAsset = UnityEngine.TextAsset; using GlyphRect = UnityEngine.TextCore.GlyphRect; using GlyphMetrics = UnityEngine.TextCore.GlyphMetrics; namespace UnityEditor.TextCore.Text { internal class SpriteAssetImporter : EditorWindow { // Create Sprite Asset Editor Window [MenuItem("Window/Text/Sprite Importer", false, 2026)] internal static void ShowFontAtlasCreatorWindow() { var window = GetWindow<SpriteAssetImporter>(); window.titleContent = new GUIContent("Sprite Importer"); window.Focus(); } Texture2D m_SpriteAtlas; SpriteAssetImportFormats m_SpriteDataFormat = SpriteAssetImportFormats.TexturePackerJsonArray; TextAsset m_JsonFile; string m_CreationFeedback; SpriteAsset m_SpriteAsset; static readonly GUIContent k_ConvertSpriteNameToUnicodeLabel = new GUIContent("Use sprite filename as Unicode", "Should sprite filenames be converted and assigned as Unicode code points for each sprite? This conversion assumes the sprite filenames represent valid Unicode code points."); static bool k_SpriteNameIsUnicodeValue; /// <summary> /// /// </summary> void OnEnable() { // Set Editor Window Size SetEditorWindowSize(); } /// <summary> /// /// </summary> public void OnGUI() { DrawEditorPanel(); } /// <summary> /// /// </summary> private void OnDisable() { // Clean up sprite asset object that may have been created and not saved. if (m_SpriteAsset != null && !EditorUtility.IsPersistent(m_SpriteAsset)) DestroyImmediate(m_SpriteAsset); } /// <summary> /// /// </summary> void DrawEditorPanel() { // label GUILayout.Label("Import Settings", EditorStyles.boldLabel); EditorGUI.BeginChangeCheck(); // Sprite Texture Selection m_JsonFile = EditorGUILayout.ObjectField("Sprite Data Source", m_JsonFile, typeof(TextAsset), false) as TextAsset; m_SpriteDataFormat = (SpriteAssetImportFormats)EditorGUILayout.EnumPopup("Import Format", m_SpriteDataFormat); k_SpriteNameIsUnicodeValue = EditorGUILayout.Toggle(k_ConvertSpriteNameToUnicodeLabel, k_SpriteNameIsUnicodeValue); // Sprite Texture Selection m_SpriteAtlas = EditorGUILayout.ObjectField("Sprite Texture Atlas", m_SpriteAtlas, typeof(Texture2D), false) as Texture2D; if (EditorGUI.EndChangeCheck()) { m_CreationFeedback = string.Empty; } GUILayout.Space(10); GUI.enabled = m_JsonFile != null && m_SpriteAtlas != null && m_SpriteDataFormat != SpriteAssetImportFormats.None; // Create Sprite Asset if (GUILayout.Button("Create Sprite Asset")) { m_CreationFeedback = string.Empty; // Clean up sprite asset object that may have been previously created. if (m_SpriteAsset != null && !EditorUtility.IsPersistent(m_SpriteAsset)) DestroyImmediate(m_SpriteAsset); // Read json data file if (m_JsonFile != null) { switch (m_SpriteDataFormat) { case SpriteAssetImportFormats.TexturePackerJsonArray: TexturePacker_JsonArray.SpriteDataObject jsonData = null; try { jsonData = JsonUtility.FromJson<TexturePacker_JsonArray.SpriteDataObject>(m_JsonFile.text); } catch { m_CreationFeedback = "The Sprite Data Source file [" + m_JsonFile.name + "] appears to be invalid or incorrectly formatted."; } if (jsonData != null && jsonData.frames != null && jsonData.frames.Count > 0) { int spriteCount = jsonData.frames.Count; // Update import results m_CreationFeedback = "<b>Import Results</b>\n--------------------\n"; m_CreationFeedback += "<color=#C0ffff><b>" + spriteCount + "</b></color> Sprites were imported from file."; // Create new Sprite Asset m_SpriteAsset = CreateInstance<SpriteAsset>(); // Assign sprite sheet / atlas texture to sprite asset m_SpriteAsset.spriteSheet = m_SpriteAtlas; List<SpriteGlyph> spriteGlyphTable = new List<SpriteGlyph>(); List<SpriteCharacter> spriteCharacterTable = new List<SpriteCharacter>(); PopulateSpriteTables(jsonData, spriteCharacterTable, spriteGlyphTable); m_SpriteAsset.spriteCharacterTable = spriteCharacterTable; m_SpriteAsset.spriteGlyphTable = spriteGlyphTable; } break; } } } GUI.enabled = true; // Creation Feedback GUILayout.Space(5); GUILayout.BeginVertical(EditorStyles.helpBox, GUILayout.Height(60)); { EditorGUILayout.TextArea(m_CreationFeedback, TM_EditorStyles.label); } GUILayout.EndVertical(); GUILayout.Space(5); GUI.enabled = m_JsonFile != null && m_SpriteAtlas && m_SpriteAsset != null; if (GUILayout.Button("Save Sprite Asset") && m_JsonFile != null) { string filePath = EditorUtility.SaveFilePanel("Save Sprite Asset File", new FileInfo(AssetDatabase.GetAssetPath(m_JsonFile)).DirectoryName, m_JsonFile.name, "asset"); if (filePath.Length == 0) return; SaveSpriteAsset(filePath); } GUI.enabled = true; } /// <summary> /// /// </summary> /// <param name="spriteDataObject"></param> /// <param name="spriteCharacterTable"></param> /// <param name="spriteGlyphTable"></param> private static void PopulateSpriteTables(TexturePacker_JsonArray.SpriteDataObject spriteDataObject, List<SpriteCharacter> spriteCharacterTable, List<SpriteGlyph> spriteGlyphTable) { List<TexturePacker_JsonArray.Frame> importedSprites = spriteDataObject.frames; float atlasHeight = spriteDataObject.meta.size.h; for (int i = 0; i < importedSprites.Count; i++) { TexturePacker_JsonArray.Frame spriteData = importedSprites[i]; SpriteGlyph spriteGlyph = new SpriteGlyph(); spriteGlyph.index = (uint)i; spriteGlyph.metrics = new GlyphMetrics((int)spriteData.frame.w, (int)spriteData.frame.h, -spriteData.frame.w * spriteData.pivot.x, spriteData.frame.h * spriteData.pivot.y, (int)spriteData.frame.w); spriteGlyph.glyphRect = new GlyphRect((int)spriteData.frame.x, (int)(atlasHeight - spriteData.frame.h - spriteData.frame.y), (int)spriteData.frame.w, (int)spriteData.frame.h); spriteGlyph.scale = 1.0f; spriteGlyphTable.Add(spriteGlyph); SpriteCharacter spriteCharacter = new SpriteCharacter(0xFFFE, spriteGlyph); // Special handling for .notdef sprite name string fileNameToLowerInvariant = spriteData.filename.ToLowerInvariant(); if (fileNameToLowerInvariant == ".notdef" || fileNameToLowerInvariant == "notdef") { spriteCharacter.name = fileNameToLowerInvariant; spriteCharacter.unicode = 0; } else { string spriteName = spriteData.filename.Split('.')[0]; spriteCharacter.name = spriteName; if (k_SpriteNameIsUnicodeValue) spriteCharacter.unicode = TextUtilities.StringHexToInt(spriteName); } spriteCharacter.scale = 1.0f; spriteCharacterTable.Add(spriteCharacter); } } /// <summary> /// /// </summary> /// <param name="filePath"></param> void SaveSpriteAsset(string filePath) { filePath = filePath.Substring(0, filePath.Length - 6); // Trim file extension from filePath. string dataPath = Application.dataPath; if (filePath.IndexOf(dataPath, System.StringComparison.InvariantCultureIgnoreCase) == -1) { Debug.LogError("You're saving the font asset in a directory outside of this project folder. This is not supported. Please select a directory under \"" + dataPath + "\""); return; } string relativeAssetPath = filePath.Substring(dataPath.Length - 6); string dirName = Path.GetDirectoryName(relativeAssetPath); string fileName = Path.GetFileNameWithoutExtension(relativeAssetPath); string pathNoExt = dirName + "/" + fileName; // Save Sprite Asset AssetDatabase.CreateAsset(m_SpriteAsset, pathNoExt + ".asset"); // Set version number m_SpriteAsset.version = "1.1.0"; // Compute the hash code for the sprite asset. m_SpriteAsset.hashCode = TextUtilities.GetSimpleHashCode(m_SpriteAsset.name); // Add new default material for sprite asset. AddDefaultMaterial(m_SpriteAsset); } /// <summary> /// Create and add new default material to sprite asset. /// </summary> /// <param name="spriteAsset"></param> static void AddDefaultMaterial(SpriteAsset spriteAsset) { Shader shader = TextShaderUtilities.ShaderRef_Sprite; Material material = new Material(shader); material.SetTexture(TextShaderUtilities.ID_MainTex, spriteAsset.spriteSheet); spriteAsset.material = material; material.hideFlags = HideFlags.HideInHierarchy; material.name = spriteAsset.name + " Material"; AssetDatabase.AddObjectToAsset(material, spriteAsset); } /// <summary> /// Limits the minimum size of the editor window. /// </summary> void SetEditorWindowSize() { EditorWindow editorWindow = this; Vector2 currentWindowSize = editorWindow.minSize; editorWindow.minSize = new Vector2(Mathf.Max(230, currentWindowSize.x), Mathf.Max(300, currentWindowSize.y)); } } }
UnityCsReference/Modules/TextCoreTextEngineEditor/Managed/SpriteAssetImporter.cs/0
{ "file_path": "UnityCsReference/Modules/TextCoreTextEngineEditor/Managed/SpriteAssetImporter.cs", "repo_id": "UnityCsReference", "token_count": 5424 }
466
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; namespace UnityEngine { // Font Style applied to GUI Texts, Text Meshes or GUIStyles. public enum FontStyle { // No special style is applied. Normal = 0, // Bold style applied to your texts. Bold = 1, // Italic style applied to your texts. Italic = 2, // Bold and Italic styles applied to your texts. BoldAndItalic = 3, } }
UnityCsReference/Modules/TextRendering/FontStyle.cs/0
{ "file_path": "UnityCsReference/Modules/TextRendering/FontStyle.cs", "repo_id": "UnityCsReference", "token_count": 219 }
467
// 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.Tilemaps; namespace UnityEditor { [CustomEditor(typeof(TileBase), true)] [CanEditMultipleObjects] public class TileBaseEditor : Editor { private TileBase tile { get { return (target as TileBase); } } public override Texture2D RenderStaticPreview(string assetPath, Object[] subAssets, int width, int height) { Texture2D preview = null; GameObject tilemapGameObject = null; try { TileData tileData = default; tilemapGameObject = new GameObject("Preview", typeof(Grid), typeof(Tilemap), typeof(TilemapRenderer)); var tilemap = tilemapGameObject.GetComponent<Tilemap>(); tile.GetTileData(Vector3Int.zero, tilemap, ref tileData); preview = SpriteUtility.RenderStaticPreview(tileData.sprite, tileData.color, width, height, tileData.transform); } finally { if (tilemapGameObject != null) DestroyImmediate(tilemapGameObject); } return preview; } } }
UnityCsReference/Modules/TilemapEditor/Editor/Managed/TileBaseEditor.cs/0
{ "file_path": "UnityCsReference/Modules/TilemapEditor/Editor/Managed/TileBaseEditor.cs", "repo_id": "UnityCsReference", "token_count": 589 }
468
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEngine; namespace TreeEditor { [System.Serializable] public class TreeNode { public TreeSpline spline = null; public int seed; public float animSeed; public bool visible; public int triStart; public int triEnd; public int vertStart; public int vertEnd; // Branches only.. public float capRange; public float breakOffset; // Generic.. public float size; // size or radius public float scale; // scale according to public float offset; public float baseAngle; public float angle; public float pitch; public Quaternion rotation; public Matrix4x4 matrix; public int parentID; public int groupID; // Only for internal use! [System.NonSerialized] internal TreeNode parent; [System.NonSerialized] internal TreeGroup group; [SerializeField] private int _uniqueID = -1; public int uniqueID { get { return _uniqueID; } set { // only allow setting if un-initialized if (_uniqueID == -1) { _uniqueID = value; } } } public TreeNode() { spline = null; parentID = 0; groupID = 0; parent = null; group = null; seed = 1234; breakOffset = 1.0f; visible = true; animSeed = 0.0f; scale = 1.0f; rotation = Quaternion.identity; matrix = Matrix4x4.identity; } public float GetScale() { float sp = 1.0f; if (parent != null) { sp = parent.GetScale(); } return scale * sp; } // // Computes the surface angle deviation, from the splines orientation.. Funky stuff! // ! In degrees ! public float GetSurfaceAngleAtTime(float time) { if (spline == null) { return 0.0f; } float angle = 0.0f; Vector3 pos0 = spline.GetPositionAtTime(time); float rad0 = group.GetRadiusAtTime(this, time, false); if (time < 0.5f) { float difPos = (spline.GetPositionAtTime(time + 0.01f) - pos0).magnitude; float difRad = group.GetRadiusAtTime(this, time + 0.01f, false) - rad0; angle = Mathf.Atan2(difRad, difPos); } else { float disPos = (pos0 - spline.GetPositionAtTime(time - 0.01f)).magnitude; float difRad = rad0 - group.GetRadiusAtTime(this, time - 0.01f, false); angle = Mathf.Atan2(difRad, disPos); } return (angle * Mathf.Rad2Deg); } public float GetRadiusAtTime(float time) { return group.GetRadiusAtTime(this, time, false); } public void GetPropertiesAtTime(float time, out Vector3 pos, out Quaternion rot, out float rad) { if (spline == null) { pos = Vector3.zero; rot = Quaternion.identity; } else { pos = spline.GetPositionAtTime(time); rot = spline.GetRotationAtTime(time); } rad = group.GetRadiusAtTime(this, time, false); } public Matrix4x4 GetLocalMatrixAtTime(float time) { Vector3 pos = Vector3.zero; Quaternion rot = Quaternion.identity; float rad = 0.0f; GetPropertiesAtTime(time, out pos, out rot, out rad); return Matrix4x4.TRS(pos, rot, Vector3.one); } } }
UnityCsReference/Modules/TreeEditor/Includes/TreeNode.cs/0
{ "file_path": "UnityCsReference/Modules/TreeEditor/Includes/TreeNode.cs", "repo_id": "UnityCsReference", "token_count": 2181 }
469
// 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 UnityEditor; using UnityEditor.IMGUI.Controls; using UnityEngine; namespace UnityEditor.UIAutomation { class FakeCursor { public enum CursorType { Normal } public Vector2 position { get; set; } public CursorType currentCursorType = CursorType.Normal; struct CursorData { public Texture2D cursor; public Vector2 hotspotOffset; } static CursorData[] s_MouseCursors; static Vector2 s_CursorSize = new Vector2(32, 32); bool shouldDrawFakeMouseCursor { get { return position.x > 0f; } } public virtual void Draw() { if (shouldDrawFakeMouseCursor) { var cursor = GetCursor(currentCursorType); if (cursor != null) GUI.DrawTexture(GetCursorDrawRect(currentCursorType), cursor); else EditorGUI.DrawRect(new Rect(position.x, position.y, 5, 5), Color.white); // fallback rendering } } Texture2D GetCursor(CursorType cursorType) { InitIfNeeded(); return s_MouseCursors[(int)cursorType].cursor; } Rect GetCursorDrawRect(CursorType cursorType) { InitIfNeeded(); Vector2 offset = s_MouseCursors[(int)cursorType].hotspotOffset; return new Rect(position.x + offset.x, position.y + offset.y, s_CursorSize.x, s_CursorSize.y); } void InitIfNeeded() { if (s_MouseCursors == null) { s_MouseCursors = new[] { new CursorData() { cursor = EditorGUIUtility.Load("Cursors/CursorAI.psd") as Texture2D, hotspotOffset = new Vector2(-13, -10) } }; } } } }
UnityCsReference/Modules/UIAutomationEditor/FakeCursor.cs/0
{ "file_path": "UnityCsReference/Modules/UIAutomationEditor/FakeCursor.cs", "repo_id": "UnityCsReference", "token_count": 1123 }
470
// 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; namespace Unity.UI.Builder { internal class BuilderDragger { protected enum DestinationPane { Hierarchy, Viewport, Stylesheet }; static readonly string s_DraggerPreviewClassName = "unity-builder-dragger-preview"; static readonly string s_DraggedPreviewClassName = "unity-builder-dragger-preview--dragged"; static readonly string s_TreeItemHoverHoverClassName = "unity-builder-explorer__item--dragger-hover"; static readonly string s_TreeItemHoverWithDragBetweenElementsSupportClassName = "unity-builder-explorer__between-element-item--dragger-hover"; static readonly string s_TreeViewItemName = "unity-tree-view__item"; static readonly int s_DistanceToActivation = 5; // It's possible to have multiple BuilderDraggers on the same element. This ensures // a kind of capture without using the capture system and just between BuilderDraggers. internal static BuilderDragger s_CurrentlyActiveBuilderDragger = null; Vector2 m_Start; bool m_Active; bool m_WeStartedTheDrag; BuilderPaneWindow m_PaneWindow; VisualElement m_Root; VisualElement m_Canvas; BuilderSelection m_Selection; VisualElement m_DraggedElement; VisualElement m_LastHoverElement; int m_LastHoverElementChildIndex; VisualElement m_LastRowHoverElement; BuilderParentTracker m_ParentTracker; BuilderPlacementIndicator m_PlacementIndicator; public VisualElement builderHierarchyRoot { get; set; } public VisualElement builderStylesheetRoot { get; set; } public bool active => m_Active; protected BuilderPaneWindow paneWindow { get { return m_PaneWindow; } } protected BuilderSelection selection { get { return m_Selection; } } protected VisualElement documentRootElement => m_Canvas; protected BuilderViewport viewport { get; private set; } protected BuilderPlacementIndicator placementIndicator => m_PlacementIndicator; List<ManipulatorActivationFilter> activators { get; set; } ManipulatorActivationFilter m_CurrentActivator; public event Action onEndDrag; public BuilderDragger( BuilderPaneWindow paneWindow, VisualElement root, BuilderSelection selection, BuilderViewport viewport = null, BuilderParentTracker parentTracker = null) { m_PaneWindow = paneWindow; m_Root = root; this.viewport = viewport; m_Canvas = viewport?.documentRootElement; m_Selection = selection; m_ParentTracker = parentTracker; m_PlacementIndicator = viewport?.placementIndicator; if (m_PlacementIndicator != null) m_PlacementIndicator.documentRootElement = m_Canvas; activators = new List<ManipulatorActivationFilter>(); activators.Add(new ManipulatorActivationFilter { button = MouseButton.LeftMouse }); m_Active = false; m_WeStartedTheDrag = false; m_DraggedElement = CreateDraggedElement(); m_DraggedElement.AddToClassList(s_DraggerPreviewClassName); m_Root.Add(m_DraggedElement); } internal void Reset() { m_Active = false; m_WeStartedTheDrag = false; m_Start = default; m_LastHoverElement = default; m_LastRowHoverElement = default; m_LastHoverElementChildIndex = default; s_CurrentlyActiveBuilderDragger = default; } protected virtual VisualElement CreateDraggedElement() { return new VisualElement(); } protected virtual void FillDragElement(VisualElement pill) { } protected virtual bool StartDrag(VisualElement target, Vector2 mousePosition, VisualElement pill) { return true; } protected virtual void PerformDrag(VisualElement target, VisualElement pickedElement, int index = -1) { } protected virtual void PerformAction(VisualElement destination, DestinationPane pane, Vector2 localMousePosition, int index = -1) { } protected virtual void FailAction(VisualElement target) { } protected virtual void EndDrag() { } protected virtual bool IsPickedElementValid(VisualElement element) { return true; } protected virtual bool SupportsDragBetweenElements(VisualElement element) { return false; } protected virtual bool SupportsDragInEmptySpace(VisualElement element) { return true; } protected virtual bool SupportsPlacementIndicator() { return true; } protected virtual VisualElement GetDefaultTargetElement() { return m_Canvas.Query().Where(e => e.GetVisualTreeAsset() == m_PaneWindow.document.visualTreeAsset).First(); } private StyleLength m_targetInitialMinWidth; private StyleLength m_targetInitialMinHeight; protected void FixElementSizeAndPosition(VisualElement target) { m_targetInitialMinWidth = target.style.minWidth; m_targetInitialMinHeight = target.style.minHeight; target.style.minWidth = target.resolvedStyle.width; target.style.minHeight = target.resolvedStyle.height; } protected void UnfixElementSizeAndPosition(VisualElement target) { target.style.minWidth = m_targetInitialMinWidth; target.style.minHeight = m_targetInitialMinHeight; selection.ForceVisualAssetUpdateWithoutSave(target, BuilderHierarchyChangeType.InlineStyle); } public void RegisterCallbacksOnTarget(VisualElement target) { target.RegisterCallback<MouseDownEvent>(OnMouseDown); target.RegisterCallback<MouseMoveEvent>(OnMouseMove); target.RegisterCallback<MouseUpEvent>(OnMouseUp); target.RegisterCallback<KeyUpEvent>(OnEsc); target.RegisterCallback<DetachFromPanelEvent>(UnregisterCallbacksFromTarget); } void UnregisterCallbacksFromTarget(DetachFromPanelEvent evt) { var target = evt.elementTarget; target.UnregisterCallback<MouseDownEvent>(OnMouseDown); target.UnregisterCallback<MouseMoveEvent>(OnMouseMove); target.UnregisterCallback<MouseUpEvent>(OnMouseUp); target.UnregisterCallback<KeyUpEvent>(OnEsc); target.UnregisterCallback<DetachFromPanelEvent>(UnregisterCallbacksFromTarget); } bool StartDrag(VisualElement target, Vector2 mousePosition) { var startSuccess = StartDrag(target, mousePosition, m_DraggedElement); if (!startSuccess) return startSuccess; if (s_CurrentlyActiveBuilderDragger == this) { FillDragElement(m_DraggedElement); m_DraggedElement.BringToFront(); m_DraggedElement.AddToClassList(s_DraggedPreviewClassName); } // So we don't have a flashing element at the top left corner // at the very start of the drag. PerformDragInner(target, mousePosition); return startSuccess; } bool TryToPickInCanvas(Vector2 mousePosition) { if (viewport == null) return false; var localMouse = m_Canvas.WorldToLocal(mousePosition); if (!m_Canvas.ContainsPoint(localMouse)) { m_ParentTracker?.Deactivate(); m_PlacementIndicator?.Deactivate(); return false; } var pickedElement = Panel.PickAllWithoutValidatingLayout(m_Canvas, mousePosition); // Don't allow selection of elements inside template instances or outside current active document. pickedElement = pickedElement.GetClosestElementPartOfCurrentDocument(); if (pickedElement != null && !pickedElement.IsPartOfActiveVisualTreeAsset(m_PaneWindow.document)) pickedElement = null; // Get Closest valid element. pickedElement = pickedElement.GetClosestElementThatIsValid(IsPickedElementValid); if (pickedElement == null) { m_ParentTracker?.Deactivate(); m_PlacementIndicator?.Deactivate(); m_LastHoverElement = null; return false; } // The placement indicator might decide to change the parent. if (SupportsPlacementIndicator() && m_PlacementIndicator != null) { m_PlacementIndicator.Activate(pickedElement, mousePosition); pickedElement = m_PlacementIndicator.parentElement; } m_ParentTracker.Activate(pickedElement); m_LastHoverElement = pickedElement; if (SupportsPlacementIndicator() && m_PlacementIndicator != null) m_LastHoverElementChildIndex = m_PlacementIndicator.indexWithinParent; return true; } bool IsElementTheScrollView(VisualElement pickedElement) { if (!SupportsDragInEmptySpace(pickedElement)) return false; if (pickedElement == null) return false; if (pickedElement is ScrollView) return true; if (pickedElement.ClassListContains(ScrollView.viewportUssClassName)) return true; return false; } static bool CanPickInExplorerRoot(Vector2 mousePosition, VisualElement explorerRoot) { return explorerRoot != null && explorerRoot.ContainsPoint(explorerRoot.WorldToLocal(mousePosition)); } bool TryToPickInExplorer(Vector2 mousePosition, VisualElement explorerRoot) { if (!CanPickInExplorerRoot(mousePosition, explorerRoot)) return false; // Pick element under mouse. var pickedElement = Panel.PickAllWithoutValidatingLayout(explorerRoot, mousePosition); // Pick the first valid element by walking up the tree. VisualElement pickedDocumentElement = null; VisualElement explorerItemReorderZone = null; while (true) { if (pickedElement == null) break; if (IsElementTheScrollView(pickedElement)) break; if (pickedElement.ClassListContains(BuilderConstants.ExplorerItemReorderZoneClassName)) explorerItemReorderZone = pickedElement; pickedDocumentElement = pickedElement.GetProperty(BuilderConstants.ExplorerItemElementLinkVEPropertyName) as VisualElement; if (pickedDocumentElement != null) break; pickedElement = pickedElement.parent; } // Check if reordering on top of current pickedElement is supported. var supportsDragBetweenElements = false; if (explorerItemReorderZone != null && SupportsDragBetweenElements(pickedDocumentElement)) { pickedElement = explorerItemReorderZone; supportsDragBetweenElements = true; } // Don't allow selection of elements inside template instances. VisualElement linkedCanvasPickedElement = null; if (pickedElement != null && pickedElement.ClassListContains(BuilderConstants.ExplorerItemReorderZoneClassName)) { linkedCanvasPickedElement = GetLinkedElementFromReorderZone(pickedElement); } else if (pickedElement != null) { linkedCanvasPickedElement = pickedElement.GetProperty(BuilderConstants.ExplorerItemElementLinkVEPropertyName) as VisualElement; } // Validate element with implementation. var hoverElementIsValid = pickedElement != null && (IsElementTheScrollView(pickedElement) || IsPickedElementValid(linkedCanvasPickedElement)); if (!hoverElementIsValid && !supportsDragBetweenElements) pickedElement = null; m_LastHoverElement = pickedElement; if (pickedElement == null) { m_LastRowHoverElement = null; return false; } // The hover style class may not be applied to the hover element itself. We need // to find the correct parent. m_LastRowHoverElement = m_LastHoverElement; if (!IsElementTheScrollView(pickedElement)) { while (m_LastRowHoverElement != null && m_LastRowHoverElement.name != s_TreeViewItemName) m_LastRowHoverElement = m_LastRowHoverElement.parent; } if (hoverElementIsValid && m_LastRowHoverElement != null) m_LastRowHoverElement.AddToClassList(s_TreeItemHoverHoverClassName); if (supportsDragBetweenElements) explorerItemReorderZone.AddToClassList(s_TreeItemHoverWithDragBetweenElementsSupportClassName); return true; } void PerformDragInner(VisualElement target, Vector2 mousePosition) { // Move dragged element. m_DraggedElement.style.left = mousePosition.x; m_DraggedElement.style.top = mousePosition.y; m_LastRowHoverElement?.RemoveFromClassList(s_TreeItemHoverHoverClassName); m_LastRowHoverElement?.Query(className: BuilderConstants.ExplorerItemReorderZoneClassName).ForEach(e => e.RemoveFromClassList(s_TreeItemHoverWithDragBetweenElementsSupportClassName)); // Note: It's important for the Hierarchy/Stylesheet panes to be checked first because // this check does not account for which element is on top of which other element // so if the Viewport is panned such that the Canvas is behind the Hierarchy, // the TryToPickIn..() call will return true for the Canvas. var isCanvasBlocked = CanPickInExplorerRoot(mousePosition, builderHierarchyRoot) || CanPickInExplorerRoot(mousePosition, builderStylesheetRoot); if (isCanvasBlocked) { var validHover = TryToPickInExplorer(mousePosition, builderHierarchyRoot) || TryToPickInExplorer(mousePosition, builderStylesheetRoot); if (validHover) { VisualElement pickedElement; int index; GetPickedElementFromHoverElement(out pickedElement, out index); if (pickedElement == null) return; var revisedPlacementIndex = index; var modifiedPickedElement = BuilderHierarchyUtilities.GetToggleButtonGroupContentContainer(pickedElement); // Because we are treating a contentContainer, we are telling it to add to the end of the list if // let say an user drags and drops an accepted control into the main control as opposed to a // specific index within the contentContainer. if (modifiedPickedElement != null) revisedPlacementIndex = index == -1 ? modifiedPickedElement.childCount : index; // Mirror final drag destination in the viewport using the placement indicator. m_PlacementIndicator?.Activate(modifiedPickedElement ?? pickedElement, revisedPlacementIndex); m_Active = true; PerformDrag(target, modifiedPickedElement ?? pickedElement, index); return; } } else { var validHover = TryToPickInCanvas(mousePosition); if (validHover) { m_Active = true; PerformDrag(target, m_LastHoverElement, m_LastHoverElementChildIndex); return; } } m_PlacementIndicator?.Deactivate(); PerformDrag(target, null); } void EndDragInner() { EndDrag(); onEndDrag?.Invoke(); m_LastRowHoverElement?.RemoveFromClassList(s_TreeItemHoverHoverClassName); m_LastRowHoverElement?.Query(className: BuilderConstants.ExplorerItemReorderZoneClassName).ForEach(e => e.RemoveFromClassList(s_TreeItemHoverWithDragBetweenElementsSupportClassName)); m_DraggedElement.RemoveFromClassList(s_DraggedPreviewClassName); m_ParentTracker?.Deactivate(); m_PlacementIndicator?.Deactivate(); } void OnMouseDown(MouseDownEvent evt) { if (s_CurrentlyActiveBuilderDragger != null && s_CurrentlyActiveBuilderDragger != this) { return; } var target = evt.currentTarget as VisualElement; if (m_WeStartedTheDrag && target.HasMouseCapture()) { evt.StopImmediatePropagation(); return; } if (!CanStartManipulation(evt)) return; if (target.HasMouseCapture()) return; s_CurrentlyActiveBuilderDragger ??= this; m_Start = evt.mousePosition; m_WeStartedTheDrag = true; target.CaptureMouse(); } void OnMouseMove(MouseMoveEvent evt) { var target = evt.currentTarget as VisualElement; if (!target.HasMouseCapture()) return; if (!m_Active) { if (Mathf.Abs(m_Start.x - evt.mousePosition.x) > s_DistanceToActivation || Mathf.Abs(m_Start.y - evt.mousePosition.y) > s_DistanceToActivation) { var startSuccess = StartDrag(target, evt.mousePosition); if (startSuccess) { evt.StopPropagation(); m_Active = true; } else { target.ReleaseMouse(); s_CurrentlyActiveBuilderDragger = null; } } return; } PerformDragInner(target, evt.mousePosition); evt.StopPropagation(); } VisualElement GetLinkedElementFromReorderZone(VisualElement hoverZone) { var reorderZone = hoverZone; var explorerItem = reorderZone.userData as BuilderExplorerItem; var sibling = explorerItem.GetProperty(BuilderConstants.ExplorerItemElementLinkVEPropertyName) as VisualElement; return sibling; } void SelectItemOnSingleClick(MouseUpEvent evt) { // TODO: ListView right now does not allow selecting a single // item that is already part of multi-selection, and having // only that item selected. Clicking on any already-selected // item in ListView does nothing. This needs to be fixed in trunk. // // In the meantime, we use this leaked mouse click hack, which // also accounts for another bug in ListView, to catch these // unhandled selection events and do the single-item selection // ourselves. // // See: https://unity3d.atlassian.net/browse/UIT-1011 if (m_Selection.selectionCount <= 1) return; if (evt.modifiers.HasFlag(EventModifiers.Control) || evt.modifiers.HasFlag(EventModifiers.Shift) || evt.modifiers.HasFlag(EventModifiers.Command)) return; var element = evt.elementTarget; var ancestor = element is BuilderExplorerItem ? element as BuilderExplorerItem : element?.GetFirstAncestorOfType<BuilderExplorerItem>(); if (ancestor == null) return; var documentElement = ancestor.GetProperty(BuilderConstants.ElementLinkedDocumentVisualElementVEPropertyName) as VisualElement; if (documentElement == null) return; m_Selection.Select(null, documentElement); } void OnMouseUp(MouseUpEvent evt) { if (evt.button != (int)MouseButton.LeftMouse) { evt.StopPropagation(); return; } var target = evt.currentTarget as VisualElement; if (!CanStopManipulation(evt)) return; target.ReleaseMouse(); m_WeStartedTheDrag = false; if (s_CurrentlyActiveBuilderDragger == this) s_CurrentlyActiveBuilderDragger = null; if (!m_Active) { SelectItemOnSingleClick(evt); return; } var currentMouse = evt.mousePosition; if (m_LastHoverElement != null) { var localCanvasMouse = viewport != null ? m_Canvas.WorldToLocal(currentMouse) : Vector2.zero; var localHierarchyMouse = builderHierarchyRoot?.WorldToLocal(currentMouse) ?? Vector2.zero; var localStylesheetMouse = builderStylesheetRoot?.WorldToLocal(currentMouse) ?? Vector2.zero; if (builderHierarchyRoot != null && builderHierarchyRoot.ContainsPoint(localHierarchyMouse)) { VisualElement newParent; int index; GetPickedElementFromHoverElement(out newParent, out index); if (newParent != null) PerformAction(newParent, DestinationPane.Hierarchy, localHierarchyMouse, index); } else if (builderStylesheetRoot != null && builderStylesheetRoot.ContainsPoint(localStylesheetMouse)) { VisualElement newParent; int index; GetPickedElementFromHoverElement(out newParent, out index); if (newParent != null) PerformAction(newParent, DestinationPane.Stylesheet, localStylesheetMouse, index); } else if (viewport != null && m_Canvas.ContainsPoint(localCanvasMouse)) { PerformAction(m_LastHoverElement, DestinationPane.Viewport, localCanvasMouse, m_LastHoverElementChildIndex); } } m_Active = false; evt.StopPropagation(); EndDragInner(); } void GetPickedElementFromHoverElement(out VisualElement pickedElement, out int index) { index = -1; if (IsElementTheScrollView(m_LastRowHoverElement)) { pickedElement = GetDefaultTargetElement(); } else if (m_LastHoverElement.ClassListContains(BuilderConstants.ExplorerItemReorderZoneClassName)) { var reorderZone = m_LastHoverElement; var sibling = GetLinkedElementFromReorderZone(reorderZone); pickedElement = sibling.parent; var siblingParentElement = BuilderHierarchyUtilities.GetToggleButtonGroupContentContainer(sibling.parent) ?? pickedElement; var siblingIndex = siblingParentElement.IndexOf(sibling); index = siblingParentElement.childCount; if (reorderZone.ClassListContains(BuilderConstants.ExplorerItemReorderZoneAboveClassName)) { index = siblingIndex; } else if (reorderZone.ClassListContains(BuilderConstants.ExplorerItemReorderZoneBelowClassName)) { index = siblingIndex + 1; } } else { pickedElement = m_LastHoverElement.GetProperty(BuilderConstants.ExplorerItemElementLinkVEPropertyName) as VisualElement; } } void OnEsc(KeyUpEvent evt) { if (evt.keyCode != KeyCode.Escape) return; var target = evt.currentTarget as VisualElement; if (!m_Active) return; if (s_CurrentlyActiveBuilderDragger == this) s_CurrentlyActiveBuilderDragger = null; m_Active = false; if (!target.HasMouseCapture()) return; target.ReleaseMouse(); evt.StopPropagation(); EndDragInner(); FailAction(target); } bool CanStartManipulation(IMouseEvent evt) { foreach (var activator in activators) { if (activator.Matches(evt)) { m_CurrentActivator = activator; return true; } } return false; } bool CanStopManipulation(IMouseEvent evt) { if (evt == null) { return false; } return ((MouseButton)evt.button == m_CurrentActivator.button); } } }
UnityCsReference/Modules/UIBuilder/Editor/Builder/Draggers/BuilderDragger.cs/0
{ "file_path": "UnityCsReference/Modules/UIBuilder/Editor/Builder/Draggers/BuilderDragger.cs", "repo_id": "UnityCsReference", "token_count": 11795 }
471
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License namespace Unity.UI.Builder { /// <summary> /// Used to indicate whether the source and target properties of a binding can be converted. /// </summary> enum BindingCompatibilityStatus { /// <summary> /// Used when a converter group is not registered. /// </summary> Unknown, /// <summary> /// Used when a converter group is registered and can convert the source and target properties of a binding. /// </summary> Compatible, /// <summary> /// Used when a converter group is registered but cannot convert the source and target properties a binding. /// </summary> Incompatible } }
UnityCsReference/Modules/UIBuilder/Editor/Builder/Inspector/Binding/BindingCompatibilityStatus.cs/0
{ "file_path": "UnityCsReference/Modules/UIBuilder/Editor/Builder/Inspector/Binding/BindingCompatibilityStatus.cs", "repo_id": "UnityCsReference", "token_count": 289 }
472
// 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 UnityEditor.UIElements; using UnityEngine; using UnityEngine.UIElements; using Object = UnityEngine.Object; namespace Unity.UI.Builder { internal class BuilderInspectorCanvas : IBuilderInspectorSection { static readonly int s_CameraRefreshDelayMS = 100; internal const string ContainerName = "canvas-inspector"; internal const string EditorExtensionsModeToggleName = "editor-extensions-mode-toggle"; public VisualElement root => m_CanvasInspector; BuilderInspector m_Inspector; BuilderDocument m_Document; BuilderCanvas m_Canvas; VisualElement m_CanvasInspector; BuilderDocumentSettings settings => m_Document.settings; VisualElement customBackgroundElement => m_Canvas.customBackgroundElement; FoldoutWithCheckbox m_BackgroundOptionsFoldout; // Fields IntegerField m_CanvasWidth; IntegerField m_CanvasHeight; Toggle m_MatchGameViewToggle; HelpBox m_MatchGameViewHelpBox; PercentSlider m_ColorOpacityField; PercentSlider m_ImageOpacityField; PercentSlider m_CameraOpacityField; ToggleButtonGroup m_BackgroundMode; ColorField m_ColorField; ObjectField m_ImageField; ToggleButtonGroup m_ImageScaleModeField; Button m_FitCanvasToImageButton; ObjectField m_CameraField; bool m_CameraModeEnabled; RenderTexture m_InGamePreviewRenderTexture; Rect m_InGamePreviewRect; Texture2D m_InGamePreviewTexture2D; IVisualElementScheduledItem m_InGamePreviewScheduledItem; Toggle m_EditorExtensionsModeToggle; Camera backgroundCamera { get { var fieldValue = m_CameraField.value; var camera = fieldValue as Camera; return camera; } } // Internal for tests. // ReSharper disable once ConvertToAutoPropertyWithPrivateSetter internal Texture2D inGamePreviewTexture2D => m_InGamePreviewTexture2D; // Background Control Containers VisualElement m_BackgroundColorModeControls; VisualElement m_BackgroundImageModeControls; VisualElement m_BackgroundCameraModeControls; public BuilderInspectorCanvas(BuilderInspector inspector) { m_Inspector = inspector; m_Document = inspector.document; m_CanvasInspector = m_Inspector.Q(ContainerName); var builderWindow = inspector.paneWindow as Builder; if (builderWindow == null) return; m_Canvas = builderWindow.canvas; m_CameraModeEnabled = false; // Size Fields m_CanvasWidth = root.Q<IntegerField>("canvas-width"); m_CanvasWidth.RegisterValueChangedCallback(OnWidthChange); m_CanvasHeight = root.Q<IntegerField>("canvas-height"); m_CanvasHeight.RegisterValueChangedCallback(OnHeightChange); m_Canvas.RegisterCallback<GeometryChangedEvent>(OnCanvasSizeChange); // This allows user to temporarily type values below the minimum canvas size SetDelayOnSizeFieldsEnabled(true); // To update the canvas size as user mouse drags the width or height labels DisableDelayOnActiveLabelMouseDraggers(); m_MatchGameViewToggle = root.Q<Toggle>("match-game-view"); m_MatchGameViewToggle.RegisterValueChangedCallback(OnMatchGameViewModeChanged); m_MatchGameViewHelpBox = root.Q<HelpBox>("match-game-view-hint"); // Background Opacity m_ColorOpacityField = root.Q<PercentSlider>("background-color-opacity-field"); m_ColorOpacityField.RegisterValueChangedCallback(e => { settings.ColorModeBackgroundOpacity = e.newValue; OnBackgroundOpacityChange(e.newValue); }); m_ImageOpacityField = root.Q<PercentSlider>("background-image-opacity-field"); m_ImageOpacityField.RegisterValueChangedCallback(e => { settings.ImageModeCanvasBackgroundOpacity = e.newValue; OnBackgroundOpacityChange(e.newValue); }); m_CameraOpacityField = root.Q<PercentSlider>("background-camera-opacity-field"); m_CameraOpacityField.RegisterValueChangedCallback(e => { settings.CameraModeCanvasBackgroundOpacity = e.newValue; OnBackgroundOpacityChange(e.newValue); }); // Setup Background State m_BackgroundOptionsFoldout = root.Q<FoldoutWithCheckbox>("canvas-background-foldout"); m_BackgroundOptionsFoldout.RegisterCheckboxValueChangedCallback(e => { settings.EnableCanvasBackground = e.newValue; PostSettingsChange(); ApplyBackgroundOptions(); }); // Setup Background Mode var backgroundModeType = typeof(BuilderCanvasBackgroundMode); m_BackgroundMode = root.Q<ToggleButtonGroup>("background-mode-field"); m_BackgroundMode.userData = backgroundModeType; m_BackgroundMode.Add(new Button() { name="Color", iconImage = BuilderInspectorUtilities.LoadIcon("color_picker", "Canvas/"), tooltip = "color" }); m_BackgroundMode.Add(new Button() { name="Image", iconImage = BuilderInspectorUtilities.LoadIcon("RawImage", "Canvas/"), tooltip = "image" }); m_BackgroundMode.Add(new Button() { name="Camera", iconImage = EditorGUIUtility.FindTexture("d_SceneViewCamera"), tooltip = "camera" }); m_BackgroundMode.RegisterValueChangedCallback(OnBackgroundModeChange); // Color field. m_ColorField = root.Q<ColorField>("background-color-field"); m_ColorField.RegisterValueChangedCallback(OnBackgroundColorChange); // Set Image field. m_ImageField = root.Q<ObjectField>("background-image-field"); m_ImageField.objectType = typeof(Texture2D); m_ImageField.RegisterValueChangedCallback(OnBackgroundImageChange); m_ImageScaleModeField = root.Q<ToggleButtonGroup>("background-image-scale-mode-field"); m_ImageScaleModeField.userData = typeof(ScaleMode); var backgroundScaleModeValues = Enum.GetValues(typeof(ScaleMode)) .OfType<ScaleMode>().Select((v) => BuilderNameUtilities.ConvertCamelToDash(v.ToString())).ToList(); foreach (var value in backgroundScaleModeValues) { m_ImageScaleModeField.Add(new Button() { iconImage = BuilderInspectorUtilities.LoadIcon(BuilderNameUtilities.ConvertDashToHuman(value), "Background/"), tooltip = value }); } m_ImageScaleModeField.RegisterValueChangedCallback(OnBackgroundImageScaleModeChange); m_FitCanvasToImageButton = root.Q<Button>("background-image-fit-canvas-button"); m_FitCanvasToImageButton.clickable.clicked += FitCanvasToImage; // Set Camera field. m_CameraField = root.Q<ObjectField>("background-camera-field"); m_CameraField.objectType = typeof(Camera); m_CameraField.RegisterValueChangedCallback(OnBackgroundCameraChange); SetupEditorExtensionsModeToggle(); // Control Containers m_BackgroundColorModeControls = root.Q("canvas-background-color-mode-controls"); m_BackgroundImageModeControls = root.Q("canvas-background-image-mode-controls"); m_BackgroundCameraModeControls = root.Q("canvas-background-camera-mode-controls"); root.RegisterCallback<AttachToPanelEvent>(AttachToPanelCallback); root.RegisterCallback<DetachFromPanelEvent>(DetachFromPanelCallback); } void AttachToPanelCallback(AttachToPanelEvent e) { EditorApplication.playModeStateChanged += PlayModeStateChange; } void DetachFromPanelCallback(DetachFromPanelEvent e) { EditorApplication.playModeStateChanged -= PlayModeStateChange; } // This is for temporarily disable delay on the width and height fields void DisableDelayOnActiveLabelMouseDraggers() { DisableDelayOnActiveLabelMouseDragger(m_CanvasWidth); DisableDelayOnActiveLabelMouseDragger(m_CanvasHeight); } void DisableDelayOnActiveLabelMouseDragger(IntegerField field) { // Use the Move event instead of the Down event because the Down event is intercepted (with Event.StopImmediatePropagation) // by the FieldMouseDragger manipulator attached to the label field.labelElement.RegisterCallback<PointerMoveEvent>(e => { if (e.pressedButtons != 0) SetDelayOnSizeFieldsEnabled(false); }); field.labelElement.RegisterCallback<PointerUpEvent>(e => SetDelayOnSizeFieldsEnabled(true)); } void SetDelayOnSizeFieldsEnabled(bool enabled) { m_CanvasWidth.isDelayed = enabled; m_CanvasHeight.isDelayed = enabled; } void SetupEditorExtensionsModeToggle() { m_EditorExtensionsModeToggle = root.Q<Toggle>(EditorExtensionsModeToggleName); m_EditorExtensionsModeToggle.RegisterValueChangedCallback(e => { m_Document.fileSettings.editorExtensionMode = e.newValue; m_Inspector.selection.NotifyOfStylingChangePostStylingUpdate(); if (e.newValue) { Builder.ShowWarning(BuilderConstants.InspectorEditorExtensionAuthoringActivated); } }); } void RemoveDocumentSettings() { root.Q("document-settings").RemoveFromHierarchy(); } public void Disable() { throw new NotImplementedException(); } public void Enable() { throw new NotImplementedException(); } public void Refresh() { if (m_Document != m_Inspector.document) m_Document = m_Inspector.document; // HACK until fix goes in: SetDelayOnSizeFieldsEnabled(false); m_CanvasWidth.SetValueWithoutNotify(settings.CanvasWidth); m_CanvasHeight.SetValueWithoutNotify(settings.CanvasHeight); SetDelayOnSizeFieldsEnabled(true); m_BackgroundOptionsFoldout.SetCheckboxValueWithoutNotify(settings.EnableCanvasBackground); m_ColorOpacityField.SetValueWithoutNotify(settings.ColorModeBackgroundOpacity); m_ImageOpacityField.SetValueWithoutNotify(settings.ImageModeCanvasBackgroundOpacity); m_CameraOpacityField.SetValueWithoutNotify(settings.CameraModeCanvasBackgroundOpacity); var backgroundModeOptions = new ToggleButtonGroupState(0, Enum.GetNames(typeof(BuilderCanvasBackgroundMode)).Length); backgroundModeOptions[(int)settings.CanvasBackgroundMode] = true; m_BackgroundMode.SetValueWithoutNotify(backgroundModeOptions); m_ColorField.SetValueWithoutNotify(settings.CanvasBackgroundColor); var imageFieldOptions = new ToggleButtonGroupState(0, Enum.GetNames(typeof(ScaleMode)).Length); imageFieldOptions[(int)settings.CanvasBackgroundImageScaleMode] = true; m_ImageScaleModeField.SetValueWithoutNotify(imageFieldOptions); m_ImageField.SetValueWithoutNotify(settings.CanvasBackgroundImage); m_CameraField.SetValueWithoutNotify(FindCameraByName()); m_EditorExtensionsModeToggle?.SetValueWithoutNotify(m_Document.fileSettings.editorExtensionMode); ApplyBackgroundOptions(); RefreshMatchGameViewToggle(); bool canvasDimensionsDifferentFromSettings = (int) m_Canvas.height != settings.CanvasHeight || (int) m_Canvas.width != settings.CanvasWidth; if (canvasDimensionsDifferentFromSettings) { m_Canvas.SetSizeFromDocumentSettings(); } } void RefreshMatchGameViewToggle() { m_CanvasWidth.SetEnabled(!settings.MatchGameView); m_CanvasHeight.SetEnabled(!settings.MatchGameView); m_MatchGameViewToggle.SetValueWithoutNotify(settings.MatchGameView); m_MatchGameViewHelpBox.style.display = settings.MatchGameView ? DisplayStyle.Flex : DisplayStyle.None; } Camera FindCameraByName() { var cameraName = settings.CanvasBackgroundCameraName; if (string.IsNullOrEmpty(cameraName)) return null; var camera = Camera.allCameras.FirstOrDefault((c) => c.name == cameraName); return camera; } void PostSettingsChange() { m_Document.SaveSettingsToDisk(); } void ApplyBackgroundOptions() { DeactivateCameraMode(); customBackgroundElement.style.backgroundColor = StyleKeyword.Initial; customBackgroundElement.style.backgroundImage = StyleKeyword.Initial; customBackgroundElement.style.backgroundPositionX = StyleKeyword.Initial; customBackgroundElement.style.backgroundPositionY = StyleKeyword.Initial; customBackgroundElement.style.backgroundRepeat = StyleKeyword.Initial; customBackgroundElement.style.backgroundSize = StyleKeyword.Initial; if (settings.EnableCanvasBackground) { switch (settings.CanvasBackgroundMode) { case BuilderCanvasBackgroundMode.Color: customBackgroundElement.style.backgroundColor = settings.CanvasBackgroundColor; customBackgroundElement.style.opacity = settings.ColorModeBackgroundOpacity; break; case BuilderCanvasBackgroundMode.Image: customBackgroundElement.style.backgroundImage = settings.CanvasBackgroundImage; customBackgroundElement.style.backgroundPositionX = BackgroundPropertyHelper.ConvertScaleModeToBackgroundPosition(settings.CanvasBackgroundImageScaleMode); customBackgroundElement.style.backgroundPositionY = BackgroundPropertyHelper.ConvertScaleModeToBackgroundPosition(settings.CanvasBackgroundImageScaleMode); customBackgroundElement.style.backgroundRepeat = BackgroundPropertyHelper.ConvertScaleModeToBackgroundRepeat(settings.CanvasBackgroundImageScaleMode); customBackgroundElement.style.backgroundSize = BackgroundPropertyHelper.ConvertScaleModeToBackgroundSize(settings.CanvasBackgroundImageScaleMode); customBackgroundElement.style.opacity = settings.ImageModeCanvasBackgroundOpacity; break; case BuilderCanvasBackgroundMode.Camera: ActivateCameraMode(); customBackgroundElement.style.opacity = settings.CameraModeCanvasBackgroundOpacity; customBackgroundElement.style.backgroundPositionX = BackgroundPropertyHelper.ConvertScaleModeToBackgroundPosition(ScaleMode.ScaleAndCrop); customBackgroundElement.style.backgroundPositionY = BackgroundPropertyHelper.ConvertScaleModeToBackgroundPosition(ScaleMode.ScaleAndCrop); customBackgroundElement.style.backgroundRepeat = BackgroundPropertyHelper.ConvertScaleModeToBackgroundRepeat(ScaleMode.ScaleAndCrop); customBackgroundElement.style.backgroundSize = BackgroundPropertyHelper.ConvertScaleModeToBackgroundSize(ScaleMode.ScaleAndCrop); break; default: throw new ArgumentOutOfRangeException(); } } UpdateBackgroundControlsView(); } void UpdateBackgroundControlsView() { m_BackgroundColorModeControls.EnableInClassList(BuilderConstants.HiddenStyleClassName, settings.CanvasBackgroundMode != BuilderCanvasBackgroundMode.Color); m_BackgroundImageModeControls.EnableInClassList(BuilderConstants.HiddenStyleClassName, settings.CanvasBackgroundMode != BuilderCanvasBackgroundMode.Image); m_BackgroundCameraModeControls.EnableInClassList(BuilderConstants.HiddenStyleClassName, settings.CanvasBackgroundMode != BuilderCanvasBackgroundMode.Camera); } void ActivateCameraMode() { if (m_CameraModeEnabled || backgroundCamera == null) return; UpdateCameraRects(); m_InGamePreviewScheduledItem = customBackgroundElement.schedule.Execute(UpdateInGameBackground); m_InGamePreviewScheduledItem.Every(s_CameraRefreshDelayMS); m_CameraModeEnabled = true; } void DeactivateCameraMode() { if (!m_CameraModeEnabled) return; m_InGamePreviewScheduledItem.Pause(); m_InGamePreviewScheduledItem = null; m_InGamePreviewRenderTexture = null; m_InGamePreviewTexture2D = null; m_CameraModeEnabled = false; customBackgroundElement.style.backgroundImage = StyleKeyword.Initial; } void PlayModeStateChange(PlayModeStateChange state) { UpdateCameraRects(); } void UpdateCameraRects() { if (settings.CanvasBackgroundMode != BuilderCanvasBackgroundMode.Camera) return; int width = 2 * settings.CanvasWidth; int height = 2 * settings.CanvasHeight; m_InGamePreviewRenderTexture = new RenderTexture(width, height, 1); m_InGamePreviewRect = new Rect(0, 0, width, height); m_InGamePreviewTexture2D = new Texture2D(width, height); } void UpdateInGameBackground() { if (backgroundCamera == null) { var refCamera = FindCameraByName(); m_CameraField.value = null; m_CameraField.value = refCamera; return; } backgroundCamera.targetTexture = m_InGamePreviewRenderTexture; RenderTexture.active = m_InGamePreviewRenderTexture; backgroundCamera.Render(); m_InGamePreviewTexture2D.ReadPixels(m_InGamePreviewRect, 0, 0); m_InGamePreviewTexture2D.Apply(false); RenderTexture.active = null; backgroundCamera.targetTexture = null; customBackgroundElement.style.backgroundImage = m_InGamePreviewTexture2D; customBackgroundElement.IncrementVersion(VersionChangeType.Repaint); } void OnCanvasSizeChange(GeometryChangedEvent evt) { // HACK until fix goes in: SetDelayOnSizeFieldsEnabled(false); m_CanvasWidth.SetValueWithoutNotify((int)m_Canvas.width); m_CanvasHeight.SetValueWithoutNotify((int)m_Canvas.height); SetDelayOnSizeFieldsEnabled(true); UpdateCameraRects(); } void OnWidthChange(ChangeEvent<int> evt) { var newValue = evt.newValue; Undo.RegisterCompleteObjectUndo(m_Document, BuilderConstants.ChangeCanvasDimensionsOrMatchViewUndoMessage); if (newValue < (int)BuilderConstants.CanvasMinWidth) { newValue = (int)BuilderConstants.CanvasMinWidth; var field = evt.elementTarget as IntegerField; // HACK until fix goes in: field.isDelayed = false; field.SetValueWithoutNotify(newValue); field.isDelayed = true; } settings.CanvasWidth = newValue; m_Canvas.width = newValue; UpdateCameraRects(); PostSettingsChange(); } void OnHeightChange(ChangeEvent<int> evt) { var newValue = evt.newValue; Undo.RegisterCompleteObjectUndo(m_Document,BuilderConstants.ChangeCanvasDimensionsOrMatchViewUndoMessage); if (newValue < (int)BuilderConstants.CanvasMinHeight) { newValue = (int)BuilderConstants.CanvasMinHeight; var field = evt.elementTarget as IntegerField; // HACK until fix goes in: field.isDelayed = false; field.SetValueWithoutNotify(newValue); field.isDelayed = true; } settings.CanvasHeight = newValue; m_Canvas.height = newValue; UpdateCameraRects(); PostSettingsChange(); } void OnMatchGameViewModeChanged(ChangeEvent<bool> evt) { Undo.RegisterCompleteObjectUndo(m_Document,BuilderConstants.ChangeCanvasDimensionsOrMatchViewUndoMessage); settings.MatchGameView = evt.newValue; RefreshMatchGameViewToggle(); m_Canvas.matchGameView = settings.MatchGameView; PostSettingsChange(); } void OnBackgroundOpacityChange(float opacity) { customBackgroundElement.style.opacity = opacity; PostSettingsChange(); } void OnBackgroundModeChange(ChangeEvent<ToggleButtonGroupState> evt) { var selected = evt.newValue.GetActiveOptions(stackalloc int[evt.newValue.length]); settings.CanvasBackgroundMode = (BuilderCanvasBackgroundMode)selected[0]; PostSettingsChange(); ApplyBackgroundOptions(); } void OnBackgroundColorChange(ChangeEvent<Color> evt) { settings.CanvasBackgroundColor = evt.newValue; PostSettingsChange(); ApplyBackgroundOptions(); } void OnBackgroundImageChange(ChangeEvent<Object> evt) { settings.CanvasBackgroundImage = evt.newValue as Texture2D; PostSettingsChange(); ApplyBackgroundOptions(); } void OnBackgroundImageScaleModeChange(ChangeEvent<ToggleButtonGroupState> evt) { var selected = evt.newValue.GetActiveOptions(stackalloc int[evt.newValue.length]); settings.CanvasBackgroundImageScaleMode = (ScaleMode)selected[0]; PostSettingsChange(); ApplyBackgroundOptions(); } void FitCanvasToImage() { if (settings.CanvasBackgroundImage == null) return; m_Canvas.width = settings.CanvasBackgroundImage.width; m_Canvas.height = settings.CanvasBackgroundImage.height; } void OnBackgroundCameraChange(ChangeEvent<Object> evt) { var previousCamera = evt.previousValue as Camera; if (ReferenceEquals(previousCamera, evt.newValue)) return; var camera = evt.newValue as Camera; settings.CanvasBackgroundCameraName = camera == null ? null : camera.name; PostSettingsChange(); ApplyBackgroundOptions(); } } }
UnityCsReference/Modules/UIBuilder/Editor/Builder/Inspector/BuilderInspectorCanvas.cs/0
{ "file_path": "UnityCsReference/Modules/UIBuilder/Editor/Builder/Inspector/BuilderInspectorCanvas.cs", "repo_id": "UnityCsReference", "token_count": 10096 }
473
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Xml; using UnityEditor; using UnityEditor.PackageManager; using UnityEditor.UIElements; using UnityEditor.Utils; using UnityEngine; using UnityEngine.Pool; using UnityEngine.UIElements; using BuilderLibraryItem = UnityEngine.UIElements.TreeViewItemData<Unity.UI.Builder.BuilderLibraryTreeItem>; using PackageInfo = UnityEditor.PackageManager.PackageInfo; using TreeViewItem = UnityEngine.UIElements.TreeViewItemData<Unity.UI.Builder.BuilderLibraryTreeItem>; namespace Unity.UI.Builder { class BuilderLibraryProjectScanner { #pragma warning disable CS0618 // Type or member is obsolete class FactoryProcessingHelper { public class AttributeRecord { public XmlQualifiedName name { get; set; } public UxmlAttributeDescription desc { get; set; } } public Dictionary<string, AttributeRecord> attributeTypeNames; public SortedDictionary<string, IUxmlFactory> knownTypes; public FactoryProcessingHelper() { attributeTypeNames = new Dictionary<string, AttributeRecord>(); knownTypes = new SortedDictionary<string, IUxmlFactory>(); } public void RegisterElementType(IUxmlFactory factory) { knownTypes.Add(XmlQualifiedName.ToString(factory.uxmlName, factory.uxmlNamespace), factory); } public bool IsKnownElementType(string elementName, string elementNameSpace) { return knownTypes.ContainsKey(XmlQualifiedName.ToString(elementName, elementNameSpace)); } } static readonly List<string> s_NameSpacesToAvoid = new List<string> { "Unity", "UnityEngine", "UnityEditor" }; private static readonly HashSet<string> s_PermittedPackagesSet = new HashSet<string>() { "com.unity.dt.app-ui", }; readonly SearchFilter m_SearchFilter; private static IEnumerable<HierarchyProperty> m_Assets; private static readonly Dictionary<string, string> m_AssetIDAndPathPair = new Dictionary<string, string>(); public BuilderLibraryProjectScanner() { m_SearchFilter = new SearchFilter { searchArea = SearchFilter.SearchArea.AllAssets, classNames = new[] { "VisualTreeAsset" } }; } static bool AllowPackageType(Type type) { var packageInfo = PackageInfo.FindForAssembly(type.Assembly); return null != packageInfo && s_PermittedPackagesSet.Contains(packageInfo.name); } bool ProcessFactory(IUxmlFactory factory, FactoryProcessingHelper processingData) { if (!string.IsNullOrEmpty(factory.substituteForTypeName)) { if (!processingData.IsKnownElementType(factory.substituteForTypeName, factory.substituteForTypeNamespace)) { // substituteForTypeName is not yet known. Defer processing to later. return false; } } processingData.RegisterElementType(factory); return true; } public void ImportUxmlSerializedDataFromSource(BuilderLibraryItem sourceCategory) { var categoryStack = new List<BuilderLibraryItem>(); var emptyNamespaceControls = new List<TreeViewItem>(); if (Unsupported.IsDeveloperMode()) { var customControlsCategory = BuilderLibraryContent.CreateItem(BuilderConstants.LibraryCustomControlsSectionUxmlSerializedData, null, null, null); sourceCategory.AddChild(customControlsCategory); sourceCategory = customControlsCategory; } var shownTypes = new HashSet<Type>(); UxmlSerializedDataRegistry.Register(); var sortedEntries = UxmlSerializedDataRegistry.SerializedDataTypes.Values.OrderBy(o => o.FullName); foreach (var type in sortedEntries) { try { var elementType = type.DeclaringType; var hasNamespace = !string.IsNullOrEmpty(elementType.Namespace); // Avoid adding our own internal factories (like Package Manager templates). if (!Unsupported.IsDeveloperMode() && hasNamespace && s_NameSpacesToAvoid.Any(n => elementType.Namespace.StartsWith(n))) { if (!AllowPackageType(type)) continue; } // Avoid adding UI Builder's own types, even in internal mode. if (hasNamespace && type.Namespace.StartsWith("Unity.UI.Builder")) continue; // Ignore UxmlObjects if (!typeof(VisualElement).IsAssignableFrom(elementType)) continue; // Ignore elements with HideInInspector if (elementType.GetCustomAttribute<HideInInspector>() != null) continue; // Ignore elements with generic parameters and abstract elements if (elementType.ContainsGenericParameters || elementType.IsAbstract) continue; // UxmlElements with a custom name appear in SerializedDataTypes twice, we only need 1 item with the custom name. if (shownTypes.Contains(type)) continue; var description = UxmlSerializedDataRegistry.GetDescription(elementType.FullName); Debug.AssertFormat(description != null, "Expected to find a description for {0}", elementType.FullName); shownTypes.Add(type); string name; var elementAttribute = elementType.GetCustomAttribute<UxmlElementAttribute>(); if (elementAttribute != null && !string.IsNullOrEmpty(elementAttribute.name)) name = elementAttribute.name; else name = elementType.Name; // Generate a unique id. // We prepend the name as its possible the same Type may be displayed for both UxmlSerializedData and UxmlTraits so we need to ensure the ids do not conflict. var idCode = ("uxml-serialized-data" + elementType.FullName + elementType.FullName).GetHashCode(); var newItem = BuilderLibraryContent.CreateItem(name, "CustomCSharpElement", elementType, () => { var data = description.CreateDefaultSerializedData(); var instance = data.CreateInstance(); // Special case for the TwoPaneSplitView as we need to add two children to not get an error log. if (instance is TwoPaneSplitView splitView) { splitView.Add(new VisualElement()); splitView.Add(new VisualElement()); } data.Deserialize(instance); return instance as VisualElement; }, id: idCode); newItem.data.hasPreview = true; CheckForUxmlElementInClassHierarchy(elementType); if (!hasNamespace) { emptyNamespaceControls.Add(newItem); } else { AddCategoriesToStack(sourceCategory, categoryStack, elementType.Namespace.Split('.'), "csharp-uxml-serialized-data-"); if (categoryStack.Count == 0) sourceCategory.AddChild(newItem); else categoryStack.Last().AddChild(newItem); } } catch (Exception e) { Debug.LogException(e); } } sourceCategory.AddChildren(emptyNamespaceControls); } private void CheckForUxmlElementInClassHierarchy(Type elementType) { var uxmlElementAttribute = elementType.GetCustomAttribute<UxmlElementAttribute>(); // Skip traits classes if (uxmlElementAttribute == null) return; var baseType = elementType.BaseType; while (baseType != null) { uxmlElementAttribute = baseType.GetCustomAttribute<UxmlElementAttribute>(); if (uxmlElementAttribute == null) { var memberFilter = new MemberFilter((x,_) => x.GetCustomAttribute<UxmlAttributeAttribute>() != null); var members = baseType.FindMembers(MemberTypes.Property | MemberTypes.Field, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly, memberFilter, null); if (members.Length > 0) { Debug.LogWarning(string.Format(BuilderConstants.LibraryUxmlAttributeUsedInNonUxmlElementClassMessage, baseType.FullName)); } } baseType = baseType.BaseType; } } public void ImportFactoriesFromSource(BuilderLibraryItem sourceCategory) { var deferredFactories = new List<IUxmlFactory>(); var processingData = new FactoryProcessingHelper(); var emptyNamespaceControls = new List<TreeViewItem>(); if (Unsupported.IsDeveloperMode()) { var customControlsCategory = BuilderLibraryContent.CreateItem(BuilderConstants.LibraryCustomControlsSectionUxmTraits, null, null, null); sourceCategory.AddChild(customControlsCategory); sourceCategory = customControlsCategory; } foreach (var factories in VisualElementFactoryRegistry.factories) { if (factories.Value.Count == 0) continue; var factory = factories.Value[0]; if (!ProcessFactory(factory, processingData)) { // Could not process the factory now, because it depends on a yet unprocessed factory. // Defer its processing. deferredFactories.Add(factory); } } List<IUxmlFactory> deferredFactoriesCopy; do { deferredFactoriesCopy = new List<IUxmlFactory>(deferredFactories); foreach (var factory in deferredFactoriesCopy) { deferredFactories.Remove(factory); if (!ProcessFactory(factory, processingData)) { // Could not process the factory now, because it depends on a yet unprocessed factory. // Defer its processing again. deferredFactories.Add(factory); } } } while (deferredFactoriesCopy.Count > deferredFactories.Count); if (deferredFactories.Count > 0) { Debug.Log("Some factories could not be processed because their base type is missing."); } var categoryStack = new List<BuilderLibraryItem>(); foreach (var known in processingData.knownTypes.Values) { var split = known.uxmlNamespace.Split('.'); if (split.Length == 0) continue; // Avoid adding our own internal factories (like Package Manager templates). if (!Unsupported.IsDeveloperMode() && split.Length > 0 && s_NameSpacesToAvoid.Contains(split[0])) { if (!AllowPackageType(known.uxmlType)) continue; } // Avoid adding UI Builder's own types, even in internal mode. if (split.Length >= 3 && split[0] == "Unity" && split[1] == "UI" && split[2] == "Builder") continue; var asset = new VisualElementAsset(known.uxmlQualifiedName); var slots = new Dictionary<string, VisualElement>(); var overrides = new List<CreationContext.AttributeOverrideRange>(); var vta = ScriptableObject.CreateInstance<VisualTreeAsset>(); var context = new CreationContext(slots, overrides, vta, null); Type elementType = null; var factoryType = known.GetType(); while (factoryType != null && elementType == null) { if (factoryType.IsGenericType && factoryType.GetGenericTypeDefinition() == typeof(UxmlFactory<,>)) elementType = factoryType.GetGenericArguments()[0]; else factoryType = factoryType.BaseType; } if (elementType == typeof(TemplateContainer)) continue; // Ignore UxmlSerialized elements in non-developer mode if (!Unsupported.IsDeveloperMode() && UxmlSerializedDataRegistry.GetDescription(elementType?.FullName) != null) continue; TreeViewItemData<BuilderLibraryTreeItem> newItem = default; // Special case for the TwoPaneSplitView as we need to add two children to not get an error log. if (elementType == typeof(TwoPaneSplitView)) { newItem = BuilderLibraryContent.CreateItem(known.uxmlName, "CustomCSharpElement", elementType, () => { var splitView = known.Create(asset, context); splitView.Add(new VisualElement()); splitView.Add(new VisualElement()); return splitView; }, (treeAsset, veaParent, element) => { var visualElementAsset = treeAsset.AddElement(veaParent, element); for (var i = 0; i < element.childCount; ++i) treeAsset.AddElement(visualElementAsset, element[i]); return visualElementAsset; }); } else { newItem = BuilderLibraryContent.CreateItem( known.uxmlName, "CustomCSharpElement", elementType, () => known.Create(asset, context)); } newItem.data.hasPreview = true; if (string.IsNullOrEmpty(split[0])) { emptyNamespaceControls.Add(newItem); } else { AddCategoriesToStack(sourceCategory, categoryStack, split, "csharp-uxml-traits-"); if (categoryStack.Count == 0) sourceCategory.AddChild(newItem); else categoryStack.Last().AddChild(newItem); } vta.Destroy(); } sourceCategory.AddChildren(emptyNamespaceControls); } static void AddCategoriesToStack(BuilderLibraryItem sourceCategory, List<BuilderLibraryItem> categoryStack, string[] split, string idNamePrefix) { if (categoryStack.Count > split.Length) { categoryStack.RemoveRange(split.Length, categoryStack.Count - split.Length); } string fullName = string.Empty; for (int i = 0; i < split.Length; ++i) { var part = split[i]; if (string.IsNullOrWhiteSpace(fullName)) fullName += part; else fullName += "." + part; if (categoryStack.Count > i) { var data = categoryStack[i].data; if (data.name == part) { continue; } else if (data.name != part) { categoryStack.RemoveRange(i, categoryStack.Count - i); } } if (categoryStack.Count <= i) { var newCategory = BuilderLibraryContent.CreateItem(part, null, null, null, null, null, null, (idNamePrefix + fullName).GetHashCode()); if (categoryStack.Count == 0) sourceCategory.AddChild(newCategory); else categoryStack[i - 1].AddChild(newCategory); categoryStack.Add(newCategory); } } } public int GetAllProjectUxmlFilePathsHash() { if (m_Assets == null) return 0; var sb = new StringBuilder(); foreach (var asset in m_Assets) { m_AssetIDAndPathPair.TryGetValue(asset.guid, out var assetPath); if (!string.IsNullOrEmpty(assetPath)) sb.Append(assetPath); } var pathsStr = sb.ToString(); return pathsStr.GetHashCode(); } public void ImportUxmlFromProject(BuilderLibraryItem projectCategory, bool includePackages) { if (m_Assets == null) return; var categoryStack = new List<BuilderLibraryItem>(); foreach (var asset in m_Assets) { m_AssetIDAndPathPair.TryGetValue(asset.guid, out var assetPath); if (string.IsNullOrEmpty(assetPath)) continue; var prettyPath = assetPath; prettyPath = Path.GetDirectoryName(prettyPath); prettyPath = prettyPath.ConvertSeparatorsToUnity(); if (prettyPath.StartsWith("Packages/") && !includePackages) continue; if (prettyPath.StartsWith(BuilderConstants.UIBuilderPackageRootPath)) continue; // Check to make sure the asset is actually writable. var packageInfo = PackageInfo.FindForAssetPath(assetPath); if (packageInfo != null && packageInfo.source != PackageSource.Embedded && packageInfo.source != PackageSource.Local) continue; // Another way to check the above. Leaving it here for references in case the above stops working. //AssetDatabase.GetAssetFolderInfo(assetPath, out bool isRoot, out bool isImmutable); //if (isImmutable) //continue; var split = prettyPath.Split('/'); AddCategoriesToStack(projectCategory, categoryStack, split, "uxml-"); var vta = asset.pptrValue as VisualTreeAsset; var newItem = BuilderLibraryContent.CreateItem(asset.name + ".uxml", nameof(TemplateContainer), typeof(TemplateContainer), () => { if (vta == null) return null; var tree = vta.CloneTree(); tree.SetProperty(BuilderConstants.LibraryItemLinkedTemplateContainerPathVEPropertyName, assetPath); return tree; }, (inVta, inParent, ve) => { var vea = inVta.AddTemplateInstance(inParent, assetPath) as VisualElementAsset; ve.SetProperty(BuilderConstants.ElementLinkedInstancedVisualTreeAssetVEPropertyName, vta); return vea; }, null, vta); var data = newItem.data; if (data.icon == null) { data.SetIcon((Texture2D) EditorGUIUtility.IconContent("VisualTreeAsset Icon").image); } data.hasPreview = true; if (categoryStack.Count == 0) projectCategory.AddChild(newItem); else categoryStack.Last().AddChild(newItem); } } #pragma warning restore CS0618 // Type or member is obsolete internal void FindAssets() { m_Assets = AssetDatabase.FindAllAssets(m_SearchFilter); using var pooledHashSet = HashSetPool<string>.Get(out var assetGuids); foreach (var property in m_Assets) { m_AssetIDAndPathPair[property.guid] = AssetDatabase.GetAssetPath(property.instanceID); assetGuids.Add(property.guid); } // If an asset is deleted, we need to remove it from the cache. if (m_AssetIDAndPathPair.Count > m_Assets.Count()) { var keyToRemove = ""; var removeKey = false; foreach (var key in m_AssetIDAndPathPair.Keys) { if (assetGuids.Contains(key)) continue; keyToRemove = key; removeKey = true; break; } if (removeKey) m_AssetIDAndPathPair.Remove(keyToRemove); } } } }
UnityCsReference/Modules/UIBuilder/Editor/Builder/Library/BuilderLibraryProjectScanner.cs/0
{ "file_path": "UnityCsReference/Modules/UIBuilder/Editor/Builder/Library/BuilderLibraryProjectScanner.cs", "repo_id": "UnityCsReference", "token_count": 11061 }
474
// 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 UnityEngine; namespace Unity.UI.Builder { internal class BuilderTooltipPreview : VisualElement { static readonly string s_UssClassName = "unity-builder-tooltip-preview"; static readonly string s_EnablerClassName = "unity-builder-tooltip-preview__enabler"; static readonly string s_ContainerClassName = "unity-builder-tooltip-preview__container"; public static readonly string s_EnabledElementName = "enabler"; VisualElement m_Enabler; VisualElement m_Container; public bool isShowing => m_Enabler.resolvedStyle.display == DisplayStyle.Flex; [Serializable] public new class UxmlSerializedData : VisualElement.UxmlSerializedData { public override object CreateInstance() => new BuilderTooltipPreview(); } public override VisualElement contentContainer => m_Container == null ? this : m_Container; public event Action onShow; public event Action onHide; public BuilderTooltipPreview() { AddToClassList(s_UssClassName); m_Enabler = new VisualElement(); m_Enabler.name = s_EnabledElementName; m_Enabler.AddToClassList(s_EnablerClassName); hierarchy.Add(m_Enabler); m_Container = new VisualElement(); m_Container.name = "content-container"; m_Container.AddToClassList(s_ContainerClassName); m_Enabler.Add(m_Container); } public void Show() { onShow?.Invoke(); m_Enabler.style.display = DisplayStyle.Flex; } public void Hide() { m_Enabler.style.display = DisplayStyle.None; onHide?.Invoke(); } public void Enable() { this.style.display = DisplayStyle.Flex; } public void Disable() { this.style.display = DisplayStyle.None; } public virtual Vector2 GetAdjustedPosition() { const float PopupAndWindowEdgesMargin = 10f; return new Vector2(Mathf.Min(style.left.value.value, parent.layout.width - resolvedStyle.width - PopupAndWindowEdgesMargin), Mathf.Min(style.top.value.value, parent.layout.height - resolvedStyle.height - PopupAndWindowEdgesMargin)); } } }
UnityCsReference/Modules/UIBuilder/Editor/Builder/Previews/BuilderTooltipPreview.cs/0
{ "file_path": "UnityCsReference/Modules/UIBuilder/Editor/Builder/Previews/BuilderTooltipPreview.cs", "repo_id": "UnityCsReference", "token_count": 1087 }
475
// 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.Text; using System.Text.RegularExpressions; using UnityEngine.UIElements.StyleSheets; namespace Unity.UI.Builder { internal static class BuilderNameUtilities { static string ConvertDashToUpperNoSpace(string dash, bool firstCase, bool addSpace) { if (BuilderConstants.SpecialEnumNamesCases.TryGetValue(dash, out var replacement)) dash = replacement; var sb = new StringBuilder(); bool caseFlag = firstCase; for (int i = 0; i < dash.Length; ++i) { char c = dash[i]; if (c == '-') { if (addSpace) sb.Append(' '); caseFlag = true; } else if (caseFlag) { sb.Append(char.ToUpper(c)); caseFlag = false; } else { sb.Append(char.ToLower(c)); } } return sb.ToString(); } public static string ConvertDashToCamel(string dash) { return ConvertDashToUpperNoSpace(dash, false, false); } public static string ConvertDashToHungarian(string dash) { return ConvertDashToUpperNoSpace(dash, true, false); } public static string ConvertDashToHuman(string dash) { return ConvertDashToUpperNoSpace(dash, true, true); } public static string ConvertCamelToDash(string camel) { var split = Regex.Replace(Regex.Replace(camel, @"(\P{Ll})(\P{Ll}\p{Ll})", "$1-$2"), @"(\p{Ll})(\P{Ll})", "$1-$2"); var lowerCase = split.ToLower(); foreach (var pair in BuilderConstants.SpecialEnumNamesCases.Where(pair => pair.Value.Equals(lowerCase))) return pair.Key; return lowerCase; } public static string ConvertCamelToHuman(string camel) { return Regex.Replace(camel, "(\\B[A-Z])", " $1"); } public static string ConvertStyleCSharpNameToUssName(string csharpName) { if (StylePropertyUtil.cSharpNameToUssName.TryGetValue(csharpName, out var ussName)) return ussName; var dashCasedName = ConvertCamelToDash(csharpName); if (dashCasedName.StartsWith("unity-")) dashCasedName = "-" + dashCasedName; return dashCasedName; } public static string ConvertStyleUssNameToCSharpName(string ussName) { if (StylePropertyUtil.ussNameToCSharpName.TryGetValue(ussName, out var cSharpStyleName)) return cSharpStyleName; if (ussName.StartsWith("-unity")) ussName = ussName.Substring(1); return ConvertDashToCamel(ussName); } public static string ConvertUssNameToStyleName(string ussName) { if (ussName == "-unity-font-style") return "-unity-font-style-and-weight"; return ussName; } public static string ConvertUssNameToStyleCSharpName(string ussName) { ussName = ConvertUssNameToStyleName(ussName); if (ussName.StartsWith("-unity")) ussName = ussName.Substring(1); return ConvertDashToCamel(ussName); } public static string CapStringLengthAndAddEllipsis(string str, int maxLength) { if (str.Length < maxLength) return str; var strShortened = str.Substring(0, maxLength); strShortened += BuilderConstants.EllipsisText; return strShortened; } public static string GetNameByReflection(object obj) { if (obj == null) return null; var type = obj.GetType(); // Look for a name property var nameProperty = type.GetProperty("name"); var objName = BuilderConstants.UnnamedValue; object nameValue = null; if (nameProperty != null) { nameValue = nameProperty.GetValue(obj); } else { var nameField = type.GetField(("name")); if (nameField != null) nameValue = nameField.GetValue(obj); } if (nameValue != null) objName = nameValue.ToString(); if (string.IsNullOrEmpty(objName)) objName = BuilderConstants.UnnamedValue; return objName; } public static Regex attributeRegex { get; } = new Regex(@"^[a-zA-Z0-9\-_]+$"); public static Regex styleSelectorRegex { get; } = new Regex(@"^[a-zA-Z0-9\-_:#\*>. ]+$"); public static Regex bindingPathAttributeRegex { get; } = new Regex(@"^[a-zA-Z0-9\-_.\[\]]+$"); } }
UnityCsReference/Modules/UIBuilder/Editor/Builder/Utilities/BuilderNameUtilities.cs/0
{ "file_path": "UnityCsReference/Modules/UIBuilder/Editor/Builder/Utilities/BuilderNameUtilities.cs", "repo_id": "UnityCsReference", "token_count": 2594 }
476
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Reflection; using Unity.UI.Builder; using UnityEngine; using UnityEngine.UIElements; namespace UnityEditor.UIElements { [CustomPropertyDrawer(typeof(UxmlTypeReferenceAttribute))] class UxmlTypeReferencePropertyDrawer : PropertyDrawer { public static readonly PropertyName typeCompleterPropertyKey = new PropertyName("--unity-type-completer"); public override VisualElement CreatePropertyGUI(SerializedProperty property) { var desiredType = ((UxmlTypeReferenceAttribute)attribute).baseType ?? typeof(object); var uxmlAttribute = fieldInfo.GetCustomAttribute<UxmlAttributeAttribute>(); var label = uxmlAttribute != null ? BuilderNameUtilities.ConvertDashToHuman(uxmlAttribute.name) : property.localizedDisplayName; var field = new BuilderTypeField(label, desiredType); field.AddToClassList(BuilderTypeField.alignedFieldUssClassName); field.BindProperty(property); return field; } } [CustomPropertyDrawer(typeof(LayerDecoratorAttribute))] class LayerDecoratorPropertyDrawer : PropertyDrawer { public override VisualElement CreatePropertyGUI(SerializedProperty property) { var field = new LayerField("Value"); field.AddToClassList(LayerField.alignedFieldUssClassName); field.BindProperty(property); return field; } } [CustomPropertyDrawer(typeof(MultilineDecoratorAttribute))] class MultilineDecoratorPropertyDrawer : PropertyDrawer { private SerializedProperty m_Property; public override VisualElement CreatePropertyGUI(SerializedProperty property) { m_Property = property; var field = new Toggle(property.displayName); field.AddToClassList(Toggle.alignedFieldUssClassName); field.bindingPath = property.propertyPath; field.RegisterCallback<ChangeEvent<bool>>(evt => SetMultilineOfValueField(evt.newValue, evt.target as VisualElement)); return field; } void SetMultilineOfValueField(bool multiline, VisualElement visualElement) { var inspector = visualElement.GetFirstAncestorOfType<BuilderInspector>(); var valueFieldInInspector = inspector.Query<TextField>().Where(x => x.label is "Value").First(); if (valueFieldInInspector == null) { var propertyField = inspector.Query<PropertyField>().Where(x => x.label is "Value").First(); propertyField?.RegisterCallback<SerializedPropertyBindEvent>(_ => { EditorApplication.delayCall += () => SetMultilineOfValueField(multiline, visualElement); }); return; } valueFieldInInspector.multiline = multiline; valueFieldInInspector.EnableInClassList(BuilderConstants.InspectorMultiLineTextFieldClassName, multiline); } } [CustomPropertyDrawer(typeof(MultilineTextFieldAttribute))] class MultilineTextFieldAttributePropertyDrawer : PropertyDrawer { public override VisualElement CreatePropertyGUI(SerializedProperty property) { return new TextField { label = property.localizedDisplayName, multiline = true, bindingPath = property.propertyPath, classList = { TextField.alignedFieldUssClassName } }; } } [CustomPropertyDrawer(typeof(FixedItemHeightDecoratorAttribute))] class FixedItemHeightDecoratorPropertyDrawer : PropertyDrawer { protected SerializedProperty m_ValueProperty; public override VisualElement CreatePropertyGUI(SerializedProperty property) { m_ValueProperty = property; var uiField = new IntegerField(property.displayName) { isDelayed = true }; uiField.AddToClassList(BaseField<int>.alignedFieldUssClassName); ConfigureField(uiField, property); UpdateField(property, uiField); return uiField; } private void ConfigureField(IntegerField field, SerializedProperty property) { field.RegisterCallback<InputEvent>(OnFixedHeightValueChangedImmediately); field.labelElement.RegisterCallback<PointerMoveEvent>(OnFixedHeightValueChangedImmediately); field.TrackPropertyValue(property, a => UpdateField(a, field)); field.RegisterCallback<ChangeEvent<int>>(OnFixedItemHeightValueChanged); } private void UpdateField(SerializedProperty property, IntegerField field) { field.value = (int)property.floatValue; } void OnFixedItemHeightValueChanged(ChangeEvent<int> evt) { var field = evt.currentTarget as IntegerField; var undoMessage = $"Modified {m_ValueProperty.name}"; if (m_ValueProperty.m_SerializedObject.targetObject.name != string.Empty) undoMessage += $" in {m_ValueProperty.m_SerializedObject.targetObject.name}"; Undo.RegisterCompleteObjectUndo(m_ValueProperty.m_SerializedObject.targetObject, undoMessage); if (evt.newValue < 1) { SetNegativeFixedItemHeightHelpBoxEnabled(true, field); field.SetValueWithoutNotify(1); m_ValueProperty.floatValue = 1f; m_ValueProperty.serializedObject.ApplyModifiedPropertiesWithoutUndo(); return; } m_ValueProperty.floatValue = evt.newValue; m_ValueProperty.serializedObject.ApplyModifiedPropertiesWithoutUndo(); } void OnFixedHeightValueChangedImmediately(InputEvent evt) { var field = evt.currentTarget as BaseField<int>; if (field == null) return; var newValue = evt.newData; var valueResolved = UINumericFieldsUtils.TryConvertStringToLong(newValue, out var v); var resolvedValue = valueResolved ? Mathf.ClampToInt(v) : field.value; SetNegativeFixedItemHeightHelpBoxEnabled((newValue.Length != 0 && (resolvedValue < 1 || newValue.Equals("-"))), field); } void OnFixedHeightValueChangedImmediately(PointerMoveEvent evt) { if (evt.target is not Label labelElement) return; var field = labelElement.parent as TextInputBaseField<int>; if (field == null) return; var valueResolved = UINumericFieldsUtils.TryConvertStringToLong(field.text, out var v); var resolvedValue = valueResolved ? Mathf.ClampToInt(v) : field.value; SetNegativeFixedItemHeightHelpBoxEnabled((resolvedValue < 1 || field.text.ToCharArray()[0].Equals('-')), field); } void SetNegativeFixedItemHeightHelpBoxEnabled(bool enabled, BaseField<int> field) { var negativeWarningHelpBox = field.parent.Q<UnityEngine.UIElements.HelpBox>(); if (enabled) { if (negativeWarningHelpBox == null) { negativeWarningHelpBox = new UnityEngine.UIElements.HelpBox( L10n.Tr(BuilderConstants.HeightIntFieldValueCannotBeNegativeMessage), HelpBoxMessageType.Warning); field.parent.Add(negativeWarningHelpBox); negativeWarningHelpBox.EnableInClassList(BuilderConstants.InspectorShownNegativeWarningMessageClassName, true); } else { negativeWarningHelpBox.EnableInClassList(BuilderConstants.InspectorShownNegativeWarningMessageClassName, true); negativeWarningHelpBox.EnableInClassList(BuilderConstants.InspectorHiddenNegativeWarningMessageClassName, false); } return; } if (negativeWarningHelpBox == null) return; negativeWarningHelpBox.EnableInClassList(BuilderConstants.InspectorHiddenNegativeWarningMessageClassName, true); negativeWarningHelpBox.EnableInClassList(BuilderConstants.InspectorShownNegativeWarningMessageClassName, false); } } [CustomPropertyDrawer(typeof(EnumFieldValueDecoratorAttribute))] class EnumFieldValueDecoratorPropertyDrawer : PropertyDrawer { protected static readonly string k_TypePropertyName = nameof(EnumField.typeAsString); protected static readonly string k_ValuePropertyName = nameof(EnumField.valueAsString); protected static readonly string k_IncludeObsoleteValuesPropertyName = nameof(EnumField.includeObsoleteValues); protected SerializedProperty m_ValueProperty; public override VisualElement CreatePropertyGUI(SerializedProperty property) { m_ValueProperty = property; var enumValue = new EnumField("Value"); enumValue.AddToClassList(TextField.alignedFieldUssClassName); ConfigureField(enumValue, property); UpdateField(property, enumValue); return enumValue; } protected void ConfigureField(VisualElement element, SerializedProperty property) { var rootPath = BuilderUxmlAttributesView.GetSerializedDataRoot(property.propertyPath); var rootProperty = property.serializedObject.FindProperty(rootPath); var typeProperty = rootProperty.FindPropertyRelative(k_TypePropertyName); var obsoleteValuesProperty = rootProperty.FindPropertyRelative(k_IncludeObsoleteValuesPropertyName); element.TrackPropertyValue(obsoleteValuesProperty, a => UpdateField(a, element)); element.TrackPropertyValue(typeProperty, a => UpdateField(a, element)); element.RegisterCallback<ChangeEvent<Enum>>(EnumValueChanged); } protected void EnumValueChanged(ChangeEvent<Enum> evt) { // simplify undo message var undoMessage = $"Modified {m_ValueProperty.name}"; if (m_ValueProperty.m_SerializedObject.targetObject.name != string.Empty) undoMessage += $" in {m_ValueProperty.m_SerializedObject.targetObject.name}"; Undo.RegisterCompleteObjectUndo(m_ValueProperty.m_SerializedObject.targetObject, undoMessage); m_ValueProperty.stringValue = evt.newValue?.ToString(); // Because we are bypassing the binding system we must save the modified SerializedObject. m_ValueProperty.serializedObject.ApplyModifiedPropertiesWithoutUndo(); } protected virtual void UpdateField(SerializedProperty property, VisualElement element) { var rootPath = BuilderUxmlAttributesView.GetSerializedDataRoot(property.propertyPath); var rootProperty = property.serializedObject.FindProperty(rootPath); var typeProperty = rootProperty.FindPropertyRelative(k_TypePropertyName); var obsoleteValuesProperty = rootProperty.FindPropertyRelative(k_IncludeObsoleteValuesPropertyName); var valueProperty = rootProperty.FindPropertyRelative(k_ValuePropertyName); var enumField = element as EnumField; enumField.includeObsoleteValues = obsoleteValuesProperty.boolValue; enumField.typeAsString = typeProperty.stringValue; enumField.valueAsString = valueProperty.stringValue; enumField.SetEnabled(enumField.type != null); } } [CustomPropertyDrawer(typeof(EnumFlagsFieldValueDecoratorAttribute))] class EnumFlagsFieldValueDecoratorPropertyDrawer : EnumFieldValueDecoratorPropertyDrawer { public override VisualElement CreatePropertyGUI(SerializedProperty property) { m_ValueProperty = property; var enumFlagsValue = new EnumFlagsField("Value"); enumFlagsValue.AddToClassList(TextField.alignedFieldUssClassName); ConfigureField(enumFlagsValue, property); UpdateField(property, enumFlagsValue); return enumFlagsValue; } protected override void UpdateField(SerializedProperty property, VisualElement element) { var rootPath = BuilderUxmlAttributesView.GetSerializedDataRoot(property.propertyPath); var rootProperty = property.serializedObject.FindProperty(rootPath); var typeProperty = rootProperty.FindPropertyRelative(k_TypePropertyName); var obsoleteValuesProperty = rootProperty.FindPropertyRelative(k_IncludeObsoleteValuesPropertyName); var valueProperty = rootProperty.FindPropertyRelative(k_ValuePropertyName); var enumFlagsValue = element as EnumFlagsField; enumFlagsValue.includeObsoleteValues = obsoleteValuesProperty.boolValue; enumFlagsValue.typeAsString = typeProperty.stringValue; enumFlagsValue.valueAsString = valueProperty.stringValue; enumFlagsValue.SetEnabled(enumFlagsValue.type != null); } } [CustomPropertyDrawer(typeof(TagFieldValueDecoratorAttribute))] class TagFieldValueDecoratorAttributePropertyDrawer : PropertyDrawer { public override VisualElement CreatePropertyGUI(SerializedProperty property) { var tagField = new TagField("Value"); tagField.AddToClassList(TextField.alignedFieldUssClassName); tagField.BindProperty(property); return tagField; } } [CustomPropertyDrawer(typeof(ImageFieldValueDecoratorAttribute))] class ImageFieldValueDecoratorAttributePropertyDrawer : PropertyDrawer { public override VisualElement CreatePropertyGUI(SerializedProperty property) { var imageField = new ImageStyleField("Icon Image"); imageField.BindProperty(property); imageField.AddToClassList(ImageStyleField.alignedFieldUssClassName); return imageField; } } [CustomPropertyDrawer(typeof(AdvanceTextGeneratorDecoratorAttribute))] class AdvanceTextGeneratorDecoratorAttributePropertyDrawer : PropertyDrawer { private Toggle textNativeField; public override VisualElement CreatePropertyGUI(SerializedProperty property) { textNativeField = new Toggle("Enable Advanced Text"); textNativeField.RegisterCallback<AttachToPanelEvent>(OnAttachToPanel); textNativeField.RegisterCallback<DetachFromPanelEvent>(OnDetachFromPanel); textNativeField.BindProperty(property); textNativeField.AddToClassList(TextField.alignedFieldUssClassName); return textNativeField; } private void OnAttachToPanel(AttachToPanelEvent evt) { var target = (VisualElement)evt.currentTarget; EnableDisplay(UIToolkitProjectSettings.enableAdvancedText); UIToolkitProjectSettings.onEnableAdvancedTextChanged += EnableDisplay; } private void OnDetachFromPanel(DetachFromPanelEvent evt) { UIToolkitProjectSettings.onEnableAdvancedTextChanged -= EnableDisplay; } private void EnableDisplay(bool enable) { textNativeField.parent.parent.parent.style.display = enable ? DisplayStyle.Flex : DisplayStyle.None; } } }
UnityCsReference/Modules/UIBuilder/Editor/Builder/UxmlAttributesView/Fields/UxmlAttributeFieldPropertyDrawers.cs/0
{ "file_path": "UnityCsReference/Modules/UIBuilder/Editor/Builder/UxmlAttributesView/Fields/UxmlAttributeFieldPropertyDrawers.cs", "repo_id": "UnityCsReference", "token_count": 6224 }
477
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using Unity.Profiling; using UnityEditor; using UnityEditor.UIElements; using UnityEngine; using UnityEngine.Pool; using UnityEngine.UIElements; using TreeViewItem = UnityEngine.UIElements.TreeViewItemData<UnityEngine.UIElements.VisualElement>; namespace Unity.UI.Builder { struct PreSaveState { public List<int> expandedIndices; public List<int> selectedIndices; public Vector2 scrollOffset; } internal class ElementHierarchyView : VisualElement { public const string k_PillName = "unity-builder-tree-class-pill"; const string k_TreeItemPillClass = "unity-debugger-tree-item-pill"; public bool hierarchyHasChanged { get; set; } public bool hasUnsavedChanges { get; set; } public bool hasUssChanges { get; set; } public BuilderExplorer.BuilderElementInfoVisibilityState elementInfoVisibilityState { get; set; } VisualTreeAsset m_ClassPillTemplate; public IList<TreeViewItem> treeRootItems => m_TreeRootItems; public IEnumerable<TreeViewItemData<VisualElement>> treeItems { get { foreach (var itemId in m_TreeView.viewController.GetAllItemIds()) { yield return m_TreeViewController.GetTreeViewItemDataForId(itemId); } } } DefaultTreeViewController<VisualElement> m_TreeViewController; IList<TreeViewItem> m_TreeRootItems; TreeView m_TreeView; PreSaveState m_RegisteredState; HighlightOverlayPainter m_TreeViewHoverOverlay; VisualElement m_Container; Action<List<VisualElement>> m_SelectElementCallback; List<VisualElement> m_SearchResultsHightlights; IPanel m_CurrentPanelDebug; BuilderPaneWindow m_PaneWindow; VisualElement m_DocumentRootElement; BuilderSelection m_Selection; BuilderClassDragger m_ClassDragger; BuilderExplorerDragger m_ExplorerDragger; BuilderElementContextMenu m_ContextMenuManipulator; bool m_AllowMouseUpRenaming; IVisualElementScheduledItem m_RenamingScheduledItem; ManipulatorActivationFilter m_RenamingManipulatorFilter; List<Label> m_LabelsToResize = new(); public VisualElement container { get { return m_Container; } } internal TreeView treeView => m_TreeView; internal string rebuildMarkerName; public ElementHierarchyView( BuilderPaneWindow paneWindow, VisualElement documentRootElement, BuilderSelection selection, BuilderClassDragger classDragger, BuilderExplorerDragger explorerDragger, BuilderElementContextMenu contextMenuManipulator, Action<List<VisualElement>> selectElementCallback, HighlightOverlayPainter highlightOverlayPainter, string profilerMarkerName) { m_PaneWindow = paneWindow; rebuildMarkerName = $"ElementHierarchyView.Rebuild.{profilerMarkerName}"; m_RebuildMarker = new ProfilerMarker($"ElementHierarchyView.Rebuild.{profilerMarkerName}"); m_DocumentRootElement = documentRootElement; m_Selection = selection; m_ClassDragger = classDragger; m_ExplorerDragger = explorerDragger; m_ContextMenuManipulator = contextMenuManipulator; this.focusable = true; m_SelectElementCallback = selectElementCallback; hierarchyHasChanged = true; hasUnsavedChanges = true; hasUssChanges = false; m_SearchResultsHightlights = new List<VisualElement>(); this.RegisterCallback<FocusEvent>(e => m_TreeView?.Focus()); // HACK: ListView/TreeView need to clear their selections when clicking on nothing. this.RegisterCallback<MouseDownEvent>(e => { var target = e.elementTarget; if (target.parent is ScrollView) m_PaneWindow.primarySelection.ClearSelection(null); }); RegisterCallback<GeometryChangedEvent>(e => { foreach (var label in m_LabelsToResize) { UpdateResizableLabelWidthInSelector(label); } }); m_TreeViewHoverOverlay = highlightOverlayPainter; m_Container = new VisualElement(); m_Container.name = "explorer-container"; m_Container.style.flexGrow = 1; m_ClassDragger.builderHierarchyRoot = m_Container; m_ExplorerDragger.builderHierarchyRoot = m_Container; m_ExplorerDragger.onEndDrag += OnExplorerEndDrag; Add(m_Container); m_ClassPillTemplate = BuilderPackageUtilities.LoadAssetAtPath<VisualTreeAsset>( BuilderConstants.UIBuilderPackagePath + "/BuilderClassPill.uxml"); // Create TreeView. m_TreeRootItems = new List<TreeViewItem>(); m_TreeView = new TreeView(20, MakeItem, BindItem); m_TreeView.SetRootItems(m_TreeRootItems); m_TreeView.unbindItem += UnbindItem; m_TreeViewController = m_TreeView.viewController as DefaultTreeViewController<VisualElement>; m_TreeView.selectionType = SelectionType.Multiple; m_TreeView.viewDataKey = "unity-builder-explorer-tree"; m_TreeView.style.flexGrow = 1; m_TreeView.selectedIndicesChanged += OnSelectionChange; m_TreeView.selectionNotChanged += OnSameItemSelection; m_TreeView.horizontalScrollingEnabled = true; m_TreeView.RegisterCallback<MouseDownEvent>(OnLeakedMouseClick); m_Container.Add(m_TreeView); m_ContextMenuManipulator.RegisterCallbacksOnTarget(m_Container); RegisterCallback<KeyDownEvent>(evt => { if (selection.selectionCount != 1) { return; } var selectedElement = selection.selection.First(); var explorerItem = selectedElement.GetProperty(BuilderConstants.ElementLinkedExplorerItemVEPropertyName) as BuilderExplorerItem; if (explorerItem == null) { return; } switch (evt.keyCode) { case KeyCode.Return: case KeyCode.KeypadEnter: if (Application.platform == RuntimePlatform.OSXEditor) { explorerItem.ActivateRenameElementMode(); evt.StopPropagation(); } break; case KeyCode.F2: if (Application.platform != RuntimePlatform.OSXEditor) { explorerItem.ActivateRenameElementMode(); evt.StopPropagation(); } break; } }, TrickleDown.TrickleDown); } private void UnbindItem(VisualElement element, int index) { var explorerItem = element as BuilderExplorerItem; foreach (var label in explorerItem.elidableLabels) { m_LabelsToResize.Remove(label); } explorerItem.elidableLabels.Clear(); } private void OnExplorerEndDrag() { m_AllowMouseUpRenaming = false; } private void OnSameItemSelection() { if (m_Selection.isEmpty) { return; } var selectedElement = m_Selection.selection.First(); var explorerItem = selectedElement.GetProperty(BuilderConstants.ElementLinkedExplorerItemVEPropertyName) as BuilderExplorerItem; if (explorerItem != null && !explorerItem.IsRenamingActive() && m_TreeView.IsFocused()) { m_AllowMouseUpRenaming = true; } } public void CopyTreeViewItemStates(VisualElementAsset sourceVEA, VisualElementAsset targetVEA) { var templateTreeItem = new TreeViewItemData<VisualElement>(); var unpackedElementTreeItem = new TreeViewItemData<VisualElement>(); foreach (var item in treeItems) { if (item.data == null) continue; var elementAsset = item.data.GetVisualElementAsset(); if (elementAsset == sourceVEA) { templateTreeItem = item; } else if (elementAsset == targetVEA) { unpackedElementTreeItem = item; } } if (templateTreeItem.data != null && unpackedElementTreeItem.data != null) m_TreeView.CopyExpandedStates(templateTreeItem.id, unpackedElementTreeItem.id); } void BindItem(VisualElement element, int index) { var item = m_TreeViewController.GetTreeViewItemDataForIndex(index); var explorerItem = element as BuilderExplorerItem; explorerItem.SetReorderingZonesEnabled(true); explorerItem.Clear(); // Pre-emptive cleanup. var row = explorerItem.parent.parent; row.RemoveFromClassList(BuilderConstants.ExplorerHeaderRowClassName); row.RemoveFromClassList(BuilderConstants.ExplorerItemHiddenClassName); row.RemoveFromClassList(BuilderConstants.ExplorerActiveStyleSheetClassName); row.tooltip = string.Empty; // Get target element (in the document). var documentElement = item.data; documentElement.SetProperty(BuilderConstants.ElementLinkedExplorerItemVEPropertyName, explorerItem); explorerItem.SetProperty(BuilderConstants.ElementLinkedDocumentVisualElementVEPropertyName, documentElement); row.userData = documentElement; // If we have a FillItem callback (override), we call it and stop creating the rest of the item. var fillItemCallback = documentElement.GetProperty(BuilderConstants.ExplorerItemFillItemCallbackVEPropertyName) as Action<VisualElement, TreeViewItem, BuilderSelection>; if (fillItemCallback != null) { fillItemCallback(explorerItem, item, m_Selection); return; } // Create main label container. var labelCont = new VisualElement(); labelCont.AddToClassList(BuilderConstants.ExplorerItemLabelContClassName); explorerItem.Add(labelCont); if (BuilderSharedStyles.IsStyleSheetElement(documentElement)) { var owningUxmlPath = documentElement.GetProperty(BuilderConstants.ExplorerItemLinkedUXMLFileName) as string; var isPartOfParentDocument = !string.IsNullOrEmpty(owningUxmlPath); var styleSheetAsset = documentElement.GetStyleSheet(); var styleSheetAssetName = BuilderAssetUtilities.GetStyleSheetAssetName(styleSheetAsset, hasUnsavedChanges && !isPartOfParentDocument && hasUssChanges); var ssLabel = new Label(styleSheetAssetName); ssLabel.AddToClassList(BuilderConstants.ExplorerItemLabelClassName); ssLabel.AddToClassList("unity-debugger-tree-item-type"); row.AddToClassList(BuilderConstants.ExplorerHeaderRowClassName); labelCont.Add(ssLabel); // Register right-click events for context menu actions. m_ContextMenuManipulator.RegisterCallbacksOnTarget(explorerItem); // Register drag-and-drop events for reparenting. m_ExplorerDragger.RegisterCallbacksOnTarget(explorerItem); // Allow reparenting. explorerItem.SetProperty(BuilderConstants.ExplorerItemElementLinkVEPropertyName, documentElement); var assetIsActiveStyleSheet = styleSheetAsset == m_PaneWindow.document.activeStyleSheet; if (assetIsActiveStyleSheet) row.AddToClassList(BuilderConstants.ExplorerActiveStyleSheetClassName); if (isPartOfParentDocument) row.AddToClassList(BuilderConstants.ExplorerItemHiddenClassName); // Show name of UXML file that USS file 'belongs' to. if (!string.IsNullOrEmpty(owningUxmlPath)) { var pathStr = Path.GetFileName(owningUxmlPath); var label = new Label(BuilderConstants.TripleSpace + pathStr); label.AddToClassList(BuilderConstants.ExplorerItemLabelClassName); label.AddToClassList(BuilderConstants.ElementTypeClassName); label.AddToClassList("unity-builder-explorer-tree-item-template-path"); // Just make it look a bit shaded. labelCont.Add(label); } return; } else if (BuilderSharedStyles.IsSelectorElement(documentElement)) { var selectorParts = BuilderSharedStyles.GetSelectorParts(documentElement); var selectorLabelCont = new VisualElement(); selectorLabelCont.AddToClassList(BuilderConstants.ExplorerItemSelectorLabelContClassName); labelCont.Add(selectorLabelCont); // Register right-click events for context menu actions. m_ContextMenuManipulator.RegisterCallbacksOnTarget(explorerItem); // Register drag-and-drop events for reparenting. m_ExplorerDragger.RegisterCallbacksOnTarget(explorerItem); foreach (var partStr in selectorParts) { Label label; VisualElement pill = null; if (partStr.StartsWith(BuilderConstants.UssSelectorClassNameSymbol)) { m_ClassPillTemplate.CloneTree(selectorLabelCont); pill = selectorLabelCont.contentContainer.ElementAt(selectorLabelCont.childCount - 1); label = pill.Q<Label>("class-name-label"); pill.name = k_PillName; pill.AddToClassList(k_TreeItemPillClass); pill.SetProperty(BuilderConstants.ExplorerStyleClassPillClassNameVEPropertyName, partStr); pill.userData = documentElement; label.text = partStr; // We want class dragger first because it has priority on the pill label when drag starts. m_ClassDragger.RegisterCallbacksOnTarget(pill); m_ExplorerDragger.RegisterCallbacksOnTarget(pill); } else if (partStr.StartsWith(BuilderConstants.UssSelectorNameSymbol)) { label = new Label(partStr); label.AddToClassList(BuilderConstants.ExplorerItemLabelClassName); label.AddToClassList(BuilderConstants.ElementNameClassName); selectorLabelCont.Add(label); } else if (partStr.StartsWith(BuilderConstants.UssSelectorPseudoStateSymbol)) { label = new Label(partStr); label.AddToClassList(BuilderConstants.ExplorerItemLabelClassName); label.AddToClassList(BuilderConstants.ElementPseudoStateClassName); selectorLabelCont.Add(label); } else if (partStr == BuilderConstants.SingleSpace) { label = new Label(BuilderConstants.TripleSpace); label.AddToClassList(BuilderConstants.ExplorerItemLabelClassName); label.AddToClassList(BuilderConstants.ElementTypeClassName); selectorLabelCont.Add(label); } else { label = new Label(partStr); label.AddToClassList(BuilderConstants.ExplorerItemLabelClassName); label.AddToClassList(BuilderConstants.ElementTypeClassName); selectorLabelCont.Add(label); } var shouldElideText = !elementInfoVisibilityState.HasFlag(BuilderExplorer.BuilderElementInfoVisibilityState .FullSelectorText); label.AddToClassList(BuilderConstants.SelectorLabelClassName); if (shouldElideText) { explorerItem.elidableLabels.Add(label); if (selectorParts.Count == 1) { m_LabelsToResize.Add(label); } else { // Label has a max-width label.AddToClassList(BuilderConstants.SelectorLabelMultiplePartsClassName); } label.RegisterCallback<GeometryChangedEvent>(e => { if (selectorParts.Count == 1) { UpdateResizableLabelWidthInSelector(label); } var fullSelectorText = BuilderSharedStyles.GetSelectorString(documentElement); UpdateTooltips(label, pill, explorerItem, fullSelectorText, partStr); }); } } // Textfield to rename element in hierarchy. var renameField = explorerItem.CreateRenamingTextField(documentElement, null, m_Selection); labelCont.Add(renameField); // Allow reparenting. explorerItem.SetProperty(BuilderConstants.ExplorerItemElementLinkVEPropertyName, documentElement); // Check if selector element is inside current open StyleSheets if (documentElement.IsParentSelector()) row.AddToClassList(BuilderConstants.ExplorerItemHiddenClassName); return; } if (BuilderSharedStyles.IsDocumentElement(documentElement)) { var uxmlAsset = documentElement.GetVisualTreeAsset(); var ssLabel = new Label(BuilderAssetUtilities.GetVisualTreeAssetAssetName(uxmlAsset, hasUnsavedChanges && !hasUssChanges)); ssLabel.AddToClassList(BuilderConstants.ExplorerItemLabelClassName); ssLabel.AddToClassList("unity-debugger-tree-item-type"); row.AddToClassList(BuilderConstants.ExplorerHeaderRowClassName); labelCont.Add(ssLabel); // Allow reparenting. explorerItem.SetProperty(BuilderConstants.ExplorerItemElementLinkVEPropertyName, documentElement); // Register right-click events for context menu actions. m_ContextMenuManipulator.RegisterCallbacksOnTarget(explorerItem); return; } // Check if element is inside current document. if (!documentElement.IsPartOfActiveVisualTreeAsset(m_PaneWindow.document)) row.AddToClassList(BuilderConstants.ExplorerItemHiddenClassName); // Register drag-and-drop events for reparenting. m_ExplorerDragger.RegisterCallbacksOnTarget(explorerItem); // Allow reparenting. explorerItem.SetProperty(BuilderConstants.ExplorerItemElementLinkVEPropertyName, documentElement); // Element type label. if (string.IsNullOrEmpty(documentElement.name) || elementInfoVisibilityState.HasFlag(BuilderExplorer.BuilderElementInfoVisibilityState.TypeName)) { var uxmlTypeName = documentElement.GetUxmlTypeName(); var typeLabel = new Label(uxmlTypeName); typeLabel.AddToClassList(BuilderConstants.ExplorerItemLabelClassName); typeLabel.AddToClassList(BuilderConstants.ElementTypeClassName); labelCont.Add(typeLabel); } // Element name label. var nameLabel = new Label(); nameLabel.AddToClassList(BuilderConstants.ExplorerItemLabelClassName); nameLabel.AddToClassList("unity-debugger-tree-item-name-label"); nameLabel.AddToClassList(BuilderConstants.ExplorerItemNameLabelClassName); nameLabel.AddToClassList(BuilderConstants.ElementNameClassName); if (!string.IsNullOrEmpty(documentElement.name)) nameLabel.text = BuilderConstants.UssSelectorNameSymbol + documentElement.name; labelCont.Add(nameLabel); // Textfield to rename element in hierarchy. var renameTextfield = explorerItem.CreateRenamingTextField(documentElement, nameLabel, m_Selection); labelCont.Add(renameTextfield); // Add class list. if (documentElement.classList.Count > 0 && elementInfoVisibilityState.HasFlag(BuilderExplorer.BuilderElementInfoVisibilityState.ClassList)) { foreach (var ussClass in documentElement.GetClasses()) { var classLabelCont = new VisualElement(); classLabelCont.AddToClassList(BuilderConstants.ExplorerItemLabelContClassName); explorerItem.Add(classLabelCont); var classLabel = new Label(BuilderConstants.UssSelectorClassNameSymbol + ussClass); classLabel.AddToClassList(BuilderConstants.ExplorerItemLabelClassName); classLabel.AddToClassList(BuilderConstants.ElementClassNameClassName); classLabel.AddToClassList("unity-debugger-tree-item-classlist-label"); classLabelCont.Add(classLabel); } } // Add stylesheets. if (elementInfoVisibilityState.HasFlag(BuilderExplorer.BuilderElementInfoVisibilityState.StyleSheets)) { var vea = documentElement.GetVisualElementAsset(); if (vea != null) { foreach (var ussPath in vea.GetStyleSheetPaths()) { if (string.IsNullOrEmpty(ussPath)) continue; var classLabelCont = new VisualElement(); classLabelCont.AddToClassList(BuilderConstants.ExplorerItemLabelContClassName); explorerItem.Add(classLabelCont); var classLabel = new Label(Path.GetFileName(ussPath)); classLabel.AddToClassList(BuilderConstants.ExplorerItemLabelClassName); classLabel.AddToClassList(BuilderConstants.ElementAttachedStyleSheetClassName); classLabel.AddToClassList("unity-debugger-tree-item-classlist-label"); classLabelCont.Add(classLabel); } } else { for (int i = 0; i < documentElement.styleSheets.count; ++i) { var attachedStyleSheet = documentElement.styleSheets[i]; if (attachedStyleSheet == null) continue; var classLabelCont = new VisualElement(); classLabelCont.AddToClassList(BuilderConstants.ExplorerItemLabelContClassName); explorerItem.Add(classLabelCont); var classLabel = new Label(attachedStyleSheet.name + BuilderConstants.UssExtension); classLabel.AddToClassList(BuilderConstants.ExplorerItemLabelClassName); classLabel.AddToClassList(BuilderConstants.ElementAttachedStyleSheetClassName); classLabel.AddToClassList("unity-debugger-tree-item-classlist-label"); classLabelCont.Add(classLabel); } } } // Show name of uxml file if this element is a TemplateContainer. var path = documentElement.GetProperty(BuilderConstants.LibraryItemLinkedTemplateContainerPathVEPropertyName) as string; Texture2D itemIcon; if (documentElement is TemplateContainer && !string.IsNullOrEmpty(path)) { var pathStr = Path.GetFileName(path); var label = new Label(pathStr); label.AddToClassList(BuilderConstants.ExplorerItemLabelClassName); label.AddToClassList(BuilderConstants.ElementTypeClassName); label.AddToClassList("unity-builder-explorer-tree-item-template-path"); // Just make it look a bit shaded. labelCont.Add(label); itemIcon = BuilderLibraryContent.GetUXMLAssetIcon(path); } else { itemIcon = BuilderLibraryContent.GetTypeLibraryIcon(documentElement.GetType()); } // Element icon. var icon = new VisualElement(); icon.AddToClassList(BuilderConstants.ExplorerItemIconClassName); var styleBackgroundImage = icon.style.backgroundImage; styleBackgroundImage.value = new Background { texture = itemIcon }; icon.style.backgroundImage = styleBackgroundImage; labelCont.Insert(0, icon); // Register right-click events for context menu actions. m_ContextMenuManipulator.RegisterCallbacksOnTarget(explorerItem); } private void UpdateTooltips(Label label, VisualElement pill, BuilderExplorerItem explorerItem, string fullSelectorText, string selectorPart) { var tooltipElement = pill ?? label; var row = explorerItem.GetFirstAncestorWithClass(BaseTreeView.itemUssClassName); tooltipElement.tooltip = label.isElided ? selectorPart : string.Empty; if (label.isElided) { row.tooltip = fullSelectorText; } else { row.tooltip = explorerItem.elidableLabels.Any(x => x.isElided) ? fullSelectorText : string.Empty; } } private void UpdateResizableLabelWidthInSelector(Label label) { var padding = label.resolvedStyle.paddingRight; if (label.parent.ClassListContains(k_TreeItemPillClass)) { padding += label.parent.resolvedStyle.paddingRight; } var size = resolvedStyle.width - label.worldBound.position.x - padding; label.style.maxWidth = Mathf.Max(BuilderConstants.ClassNameInPillMinWidth, size); } void HighlightItemInTargetWindow(VisualElement documentElement) { if (m_TreeViewHoverOverlay == null) return; m_TreeViewHoverOverlay.AddOverlay(documentElement); var panel = documentElement.panel; panel?.visualTree.MarkDirtyRepaint(); } public void ClearHighlightOverlay() { if (m_TreeViewHoverOverlay == null) return; m_TreeViewHoverOverlay.ClearOverlay(); } public void ResetHighlightOverlays() { if (m_TreeViewHoverOverlay == null) return; m_TreeViewHoverOverlay.ClearOverlay(); if (m_TreeView != null) { foreach (var selectedIndex in m_TreeView.selectedIndices) { var selectedItem = m_TreeViewController.GetTreeViewItemDataForIndex(selectedIndex); var documentElement = selectedItem.data; HighlightAllRelatedDocumentElements(documentElement); } } var panel = this.panel; panel?.visualTree.MarkDirtyRepaint(); } ProfilerMarker m_RebuildMarker; public void RebuildTree(VisualElement rootVisualElement, bool includeParent = true) { using var marker = m_RebuildMarker.Auto(); if (!hierarchyHasChanged) return; // Save focus state. bool wasTreeFocused = false; if (m_TreeView != null) wasTreeFocused = m_TreeView.IsFocused(); m_CurrentPanelDebug = rootVisualElement.panel; int nextId = 1; if (includeParent) m_TreeRootItems = GetTreeItemsFromVisualTreeIncludingParent(rootVisualElement, ref nextId); else m_TreeRootItems = GetTreeItemsFromVisualTree(rootVisualElement, ref nextId); // Clear selection which would otherwise persist via view data persistence. if (m_TreeView != null) { m_TreeView.ClearSelection(); m_TreeView.SetRootItems(m_TreeRootItems); ApplyRegisteredExpandedIndices(); m_TreeView.RefreshItems(); // Restore focus state. if (wasTreeFocused) m_TreeView.Focus(); } hierarchyHasChanged = false; } public void RegisterTreeState() { if (m_TreeView != null) { var list = ListPool<int>.Get(); m_TreeView.viewController.GetExpandedItemIds(list); m_RegisteredState.expandedIndices = list.Select(id => m_TreeView.viewController.GetIndexForId(id)).Where(index => index != -1).ToList(); m_RegisteredState.expandedIndices.Sort(); m_RegisteredState.selectedIndices = m_TreeView.selectedIndices.ToList(); m_RegisteredState.scrollOffset = m_TreeView.serializedVirtualizationData.scrollOffset; ListPool<int>.Release(list); } } void ApplyRegisteredExpandedIndices() { if (m_RegisteredState.expandedIndices == null) return; m_TreeView.CollapseAll(); foreach (var index in m_RegisteredState.expandedIndices) { var id = m_TreeView.viewController.GetIdForIndex(index); if (id != BaseTreeView.invalidId) m_TreeView.ExpandItem(id); } m_RegisteredState.expandedIndices.Clear(); m_RegisteredState.expandedIndices = null; } public void ApplyRegisteredSelectionInternallyIfNeeded() { if (m_RegisteredState.selectedIndices == null) return; m_TreeView.SetSelection(m_RegisteredState.selectedIndices); m_TreeView.serializedVirtualizationData.scrollOffset = m_RegisteredState.scrollOffset; m_TreeView.RefreshItems(); m_RegisteredState.selectedIndices.Clear(); m_RegisteredState.selectedIndices = null; } public void ExpandRootItems() { // Auto-expand root items on load. if (m_TreeRootItems != null) m_TreeView.ExpandRootItems(); } public void ExpandItem(VisualElement element) { var item = FindElement(m_TreeRootItems, element); if (item.data != null) { m_TreeView.ExpandItem(item.id); } } public void ExpandAllItems() { // Auto-expand all items on load. if (m_TreeRootItems != null) m_TreeView.ExpandAll(); } void OnLeakedMouseClick(MouseDownEvent evt) { if (!(evt.elementTarget is ScrollView)) return; m_TreeView.ClearSelection(); evt.StopPropagation(); } void OnSelectionChange(IEnumerable<int> itemIndices) { if (m_SelectElementCallback == null) return; if (!itemIndices.Any()) { m_SelectElementCallback(null); return; } var elements = new List<VisualElement>(); foreach (var index in itemIndices) { var item = m_TreeViewController.GetTreeViewItemDataForIndex(index); if (item.data != null) elements.Add(item.data); } m_SelectElementCallback(elements); } void HighlightAllElementsMatchingSelectorElement(VisualElement selectorElement) { var selector = selectorElement.GetProperty(BuilderConstants.ElementLinkedStyleSelectorVEPropertyName) as StyleComplexSelector; if (selector == null) return; var selectorStr = StyleSheetToUss.ToUssSelector(selector); var matchingElements = BuilderSharedStyles.GetMatchingElementsForSelector(m_DocumentRootElement, selectorStr); if (matchingElements == null) return; foreach (var element in matchingElements) HighlightItemInTargetWindow(element); } void HighlightAllRelatedDocumentElements(VisualElement documentElement) { if (BuilderSharedStyles.IsSelectorElement(documentElement)) { HighlightAllElementsMatchingSelectorElement(documentElement); } else { HighlightItemInTargetWindow(documentElement); } } VisualElement MakeItem() { var element = new BuilderExplorerItem(); element.name = "unity-treeview-item-content"; element.RegisterCallback<MouseEnterEvent>((e) => { ClearHighlightOverlay(); var explorerItem = e.elementTarget; var documentElement = explorerItem?.GetProperty(BuilderConstants.ElementLinkedDocumentVisualElementVEPropertyName) as VisualElement; HighlightAllRelatedDocumentElements(documentElement); }); element.RegisterCallback<MouseLeaveEvent>((e) => { ClearHighlightOverlay(); }); element.RegisterCustomBuilderStyleChangeEvent(elementStyle => { var documentElement = element.GetProperty(BuilderConstants.ElementLinkedDocumentVisualElementVEPropertyName) as VisualElement; var isValidTarget = documentElement != null; if (!isValidTarget) return; var icon = element.Q(null, BuilderConstants.ExplorerItemIconClassName); if (icon == null) return; var path = documentElement.GetProperty(BuilderConstants.LibraryItemLinkedTemplateContainerPathVEPropertyName) as string; var libraryIcon = BuilderLibraryContent.GetTypeLibraryIcon(documentElement.GetType()); if (documentElement is TemplateContainer && !string.IsNullOrEmpty(path)) { libraryIcon = BuilderLibraryContent.GetUXMLAssetIcon(path); } else if (elementStyle == BuilderElementStyle.Highlighted && !EditorGUIUtility.isProSkin) { libraryIcon = BuilderLibraryContent.GetTypeDarkSkinLibraryIcon(documentElement.GetType()); } var styleBackgroundImage = icon.style.backgroundImage; styleBackgroundImage.value = new Background { texture = libraryIcon }; icon.style.backgroundImage = styleBackgroundImage; }); element.RegisterCallback<ClickEvent>(evt => { if (!m_RenamingManipulatorFilter.Matches(evt)) { return; } if (evt.clickCount > 1) { // Multiple clicks. Cancel rename m_RenamingScheduledItem?.Pause(); } if (evt.clickCount == 1 && m_AllowMouseUpRenaming) { m_RenamingScheduledItem = element.schedule.Execute(() => { if (m_Selection.selectionCount != 1 || !m_TreeView.IsFocused()) { return; } var selectedElement = m_Selection.selection.First(); if (!selectedElement.HasProperty(BuilderConstants.ElementLinkedExplorerItemVEPropertyName)) { return; } var explorerItem = selectedElement.GetProperty(BuilderConstants.ElementLinkedExplorerItemVEPropertyName) as BuilderExplorerItem; if (explorerItem == element) { element.ActivateRenameElementMode(); } }).StartingIn(500); evt.StopPropagation(); } m_AllowMouseUpRenaming = false; }, TrickleDown.TrickleDown); return element; } TreeViewItem FindElement(IEnumerable<TreeViewItem> list, VisualElement element) { if (list == null) return default; foreach (var item in list) { var treeItem = item; if (treeItem.data == element) return treeItem; var itemFoundInChildren = new TreeViewItemData<VisualElement>(); if (treeItem.hasChildren) itemFoundInChildren = FindElement(treeItem.children, element); if (itemFoundInChildren.data != null) return itemFoundInChildren; } return default; } // Used in tests internal bool IsRenamingScheduled() { return m_RenamingScheduledItem != null && m_RenamingScheduledItem.isActive; } public void ClearSelection() { m_TreeView?.ClearSelection(); } public void ClearSearchResults() { foreach (var hl in m_SearchResultsHightlights) hl.RemoveFromHierarchy(); m_SearchResultsHightlights.Clear(); } public int GetSelectedItemId() { return m_TreeView.GetIdForIndex(m_TreeView.selectedIndex); } public void SelectItemById(int id) { m_TreeView.SetSelectionById(id); } public void SelectElements(IEnumerable<VisualElement> elements) { m_TreeView.ClearSelection(); if (elements == null) return; foreach (var element in elements) { var item = FindElement(m_TreeRootItems, element); if (item.data == null) continue; m_TreeView.AddToSelectionById(item.id); m_TreeView.ScrollToItemById(item.id); } } IList<TreeViewItem> GetTreeItemsFromVisualTreeIncludingParent(VisualElement parent, ref int nextId) { if (parent == null) return null; var items = new List<TreeViewItem>(); var id = nextId; nextId++; var item = new TreeViewItem(id, parent); items.Add(item); var childItems = GetTreeItemsFromVisualTree(parent, ref nextId); if (childItems == null) return items; item.AddChildren(childItems); return items; } IList<TreeViewItem> GetTreeItemsFromVisualTree(VisualElement parent, ref int nextId) { List<TreeViewItem> items = null; if (parent == null) return null; int count = parent.hierarchy.childCount; if (count == 0) return null; for (int i = 0; i < count; i++) { var element = parent.hierarchy[i]; if (items == null) items = new List<TreeViewItem>(); var id = 0; var linkedAsset = element.GetVisualElementAsset(); if (linkedAsset != null) { id = linkedAsset.id; } else { id = nextId; nextId++; } var item = new TreeViewItem(id, element); items.Add(item); var childItems = GetTreeItemsFromVisualTree(element, ref nextId); if (childItems == null) continue; item.AddChildren(childItems); } return items; } } }
UnityCsReference/Modules/UIBuilder/Editor/Utilities/ElementHierarchyView/ElementHierarchyView.cs/0
{ "file_path": "UnityCsReference/Modules/UIBuilder/Editor/Utilities/ElementHierarchyView/ElementHierarchyView.cs", "repo_id": "UnityCsReference", "token_count": 20322 }
478
// 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 UnityEditor.UIElements; using UnityEngine; using UnityEngine.UIElements; using Object = UnityEngine.Object; namespace Unity.UI.Builder { abstract class MultiTypeField : BaseField<Object> { [Serializable] public new abstract class UxmlSerializedData : BaseField<Object>.UxmlSerializedData { } static readonly string k_UssPath = BuilderConstants.UtilitiesPath + "/MultiTypeField/MultiTypeField.uss"; static readonly string k_UxmlPath = BuilderConstants.UtilitiesPath + "/MultiTypeField/MultiTypeField.uxml"; static readonly string acceptDropVariantUssClassName = "unity-object-field-display--accept-drop"; static readonly PropertyName serializedPropertyKey = new PropertyName("--unity-object-field-serialized-property"); const string k_OptionsPopupContainerName = "unity-multi-type-options-popup-container"; readonly ObjectField m_ObjectField; readonly VisualElement m_ObjectFieldInput; readonly Dictionary<string, Type> m_TypeOptions; readonly PopupField<string> m_TypePopup; protected MultiTypeField() : this(null) {} protected MultiTypeField(string label) : base(label) { styleSheets.Add(BuilderPackageUtilities.LoadAssetAtPath<StyleSheet>(k_UssPath)); var template = BuilderPackageUtilities.LoadAssetAtPath<VisualTreeAsset>(k_UxmlPath); template.CloneTree(this); m_TypeOptions = new Dictionary<string, Type>(); m_ObjectField = this.Q<ObjectField>(); m_ObjectField.RegisterValueChangedCallback(OnObjectValueChange); // To be able to support drag and dropping assets of all the supported types, we need to override the default behaviour of the ObjectField. // to do this, we register a trickle down callback on the (private) element that handles that on the `ObjectField`. m_ObjectFieldInput = m_ObjectField.Q(className:"unity-object-field-display"); m_ObjectFieldInput.RegisterCallback<DragPerformEvent>(OnDragPerformed, TrickleDown.TrickleDown); m_ObjectFieldInput.RegisterCallback<DragUpdatedEvent>(OnDragUpdated, TrickleDown.TrickleDown); var popupContainer = this.Q(k_OptionsPopupContainerName); m_TypePopup = new PopupField<string> { formatSelectedValueCallback = OnFormatSelectedValue }; popupContainer.Add(m_TypePopup); } private void OnDragUpdated(DragUpdatedEvent evt) { Object validatedObject = DNDValidateObject(); if (validatedObject != null) { DragAndDrop.visualMode = DragAndDropVisualMode.Generic; m_ObjectFieldInput.EnableInClassList(acceptDropVariantUssClassName, true); evt.StopImmediatePropagation(); } } private void OnDragPerformed(DragPerformEvent evt) { Object validatedObject = DNDValidateObject(); if (validatedObject != null) { DragAndDrop.visualMode = DragAndDropVisualMode.Generic; m_ObjectField.value = validatedObject; DragAndDrop.AcceptDrag(); m_ObjectFieldInput.RemoveFromClassList(acceptDropVariantUssClassName); evt.StopImmediatePropagation(); } } private Object DNDValidateObject() { var references = DragAndDrop.objectReferences; var property = m_ObjectField.GetProperty(serializedPropertyKey) as SerializedProperty; foreach (var type in m_TypeOptions.Values) { var validatedObject = EditorGUI.ValidateObjectFieldAssignment(references, type, property, EditorGUI.ObjectFieldValidatorOptions.None); if (validatedObject != null) { // If scene objects are not allowed and object is a scene object then clear if (!m_ObjectField.allowSceneObjects && !EditorUtility.IsPersistent(validatedObject)) validatedObject = null; } if (validatedObject) return validatedObject; } return null; } void OnObjectValueChange(ChangeEvent<Object> evt) { value = evt.newValue; evt.StopImmediatePropagation(); } protected void AddType(Type type) { AddType(type, type.Name); } protected void AddType(Type type, string displayName) { if (m_TypeOptions.ContainsKey(displayName)) throw new ArgumentException($"Item with the name: {displayName} already exists.", nameof(displayName)); m_TypeOptions.Add(displayName, type); m_TypePopup.choices.Add(displayName); m_TypePopup.style.display = m_TypeOptions.Count <= 1 ? DisplayStyle.None : DisplayStyle.Flex; if (string.IsNullOrEmpty(m_TypePopup.value)) m_TypePopup.value = displayName; } string OnFormatSelectedValue(string formatValue) { if (m_TypeOptions.Count > 0) { m_ObjectField.objectType = m_TypeOptions[formatValue]; if (!m_ObjectField.value) return formatValue; if (!m_ObjectField.objectType.IsInstanceOfType(m_ObjectField.value)) m_ObjectField.value = null; } return formatValue; } public void SetTypePopupValueWithoutNotify(Type type) { var typeDisplayName = m_TypeOptions.FirstOrDefault(pair => pair.Value.IsAssignableFrom(type)).Key; m_TypePopup.SetValueWithoutNotify(typeDisplayName); } public override void SetValueWithoutNotify(Object newValue) { m_ObjectField.SetValueWithoutNotify(newValue); if (newValue) { foreach (var pair in m_TypeOptions) { if (pair.Value.IsInstanceOfType(newValue)) { m_TypePopup.SetValueWithoutNotify(pair.Key); break; } } } base.SetValueWithoutNotify(newValue); } } }
UnityCsReference/Modules/UIBuilder/Editor/Utilities/MultiTypeField/MultiTypeField.cs/0
{ "file_path": "UnityCsReference/Modules/UIBuilder/Editor/Utilities/MultiTypeField/MultiTypeField.cs", "repo_id": "UnityCsReference", "token_count": 2920 }
479
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using JetBrains.Annotations; using Object = UnityEngine.Object; using System; using System.Threading; using UnityEditor.PackageManager; using UnityEngine; using UnityEngine.UIElements; namespace Unity.UI.Builder { [UsedImplicitly] class ImageStyleField : MultiTypeField { [Serializable] public new class UxmlSerializedData : MultiTypeField.UxmlSerializedData { public override object CreateInstance() => new ImageStyleField(); } const double k_TimeoutMilliseconds = 10000; const int k_TimeDeltaMilliseconds = 10; const string k_UssPath = BuilderConstants.UtilitiesPath + "/StyleField/ImageStyleField.uss"; const string k_2DSpriteEditorPackageName = "com.unity.2d.sprite"; const string k_2DSpriteEditorButtonString = "Open in Sprite Editor"; const string k_No2DSpriteEditorPackageInstalledTitle = "Package required - 2D Sprite Editor"; const string k_No2DSpriteEditorPackageInstalledMessage = "You must install the 2D Sprite Editor package to edit Sprites.\n" + "If you do not install the package, you can use existing Sprites, but you cannot create or modify them.\n" + "Do you want to install the package now?"; const string k_2DSpriteEditorInstallationURL = "https://docs.unity3d.com/Packages/[email protected]/manual/index.html"; const string k_FieldInputName = "unity-visual-input"; const string k_ImageStyleFieldContainerName = "unity-image-style-field-container"; const string k_ImageStyleFieldContainerClassName = "unity-image-style-field__container"; const string k_ImageStyleFieldEditButtonHiddenClassName = "unity-image-style-field__button--hidden"; private const string k_2DSpriteEditorButtonTooltip_Installed = "Use the Sprite Editor to 9-slice the image or edit its 9-slicing values."; private const string k_2DSpriteEditorButtonTooltip_NotInstalled = k_2DSpriteEditorButtonTooltip_Installed + " Unity will prompt you to install the com.unity.2d.sprite package first."; string m_2DSpriteEditorButtonTooltip = k_2DSpriteEditorButtonTooltip_NotInstalled; public ImageStyleField() : this(null) {} public ImageStyleField(string label) : base(label) { AddType(typeof(Texture2D), "Texture"); AddType(typeof(RenderTexture), "Render Texture"); styleSheets.Add(BuilderPackageUtilities.LoadAssetAtPath<StyleSheet>(k_UssPath)); var fieldContainer = new VisualElement {name = k_ImageStyleFieldContainerName}; fieldContainer.AddToClassList(k_ImageStyleFieldContainerClassName); m_2DSpriteEditorButtonTooltip = BuilderExternalPackages.is2DSpriteEditorInstalled ? k_2DSpriteEditorButtonTooltip_Installed : k_2DSpriteEditorButtonTooltip_NotInstalled; var fieldInput = this.Q(k_FieldInputName); // Move visual input over to field container fieldContainer.Add(fieldInput); var editButton = new Button(OnEditButton) { text = k_2DSpriteEditorButtonString, tooltip = m_2DSpriteEditorButtonTooltip }; editButton.RegisterCallback<PointerEnterEvent>(OnEnterEditButton); fieldContainer.Add(editButton); Add(fieldContainer); var optionsPopup = this.Q<PopupField<string>>(); optionsPopup.formatSelectedValueCallback += formatValue => { editButton.EnableInClassList(k_ImageStyleFieldEditButtonHiddenClassName, !formatValue.Equals("Sprite")); return formatValue; }; AddType(typeof(Sprite), "Sprite"); AddType(typeof(VectorImage), "Vector"); } private void OnEnterEditButton(PointerEnterEvent evt) { m_2DSpriteEditorButtonTooltip = BuilderExternalPackages.is2DSpriteEditorInstalled ? k_2DSpriteEditorButtonTooltip_Installed : k_2DSpriteEditorButtonTooltip_NotInstalled; } private void OnEditButton() { if (BuilderExternalPackages.is2DSpriteEditorInstalled) { // Open 2D Sprite Editor with current image loaded BuilderExternalPackages.Open2DSpriteEditor((Object)value); return; } // Handle the missing 2D Sprite Editor package case. if (BuilderDialogsUtility.DisplayDialog( k_No2DSpriteEditorPackageInstalledTitle, k_No2DSpriteEditorPackageInstalledMessage, "Install", "Cancel")) { if (!Install2DSpriteEditorPackage()) Application.OpenURL(k_2DSpriteEditorInstallationURL); } } bool Install2DSpriteEditorPackage() { var startTime = DateTime.Now; var addRequest = Client.Add(k_2DSpriteEditorPackageName); while (!addRequest.IsCompleted) { var timeDelta = DateTime.Now - startTime; if (timeDelta.TotalMilliseconds >= k_TimeoutMilliseconds) { Debug.LogError( $"Could not install package \"{k_2DSpriteEditorPackageName}\" within reasonable time.\n" + "Please note that the installation might be taking longer than expected and may still end successfully."); return false; } Thread.Sleep(k_TimeDeltaMilliseconds); } if (addRequest.Result == null) Debug.LogError($"Could not install package \"{k_2DSpriteEditorPackageName}\". Error: {addRequest.Error.message}"); else Debug.Log($"Successfully installed package \"{k_2DSpriteEditorPackageName}\"."); return addRequest.Result != null; } } }
UnityCsReference/Modules/UIBuilder/Editor/Utilities/StyleField/ImageStyleField.cs/0
{ "file_path": "UnityCsReference/Modules/UIBuilder/Editor/Utilities/StyleField/ImageStyleField.cs", "repo_id": "UnityCsReference", "token_count": 2667 }
480
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using JetBrains.Annotations; using UnityEngine; using UnityEngine.UIElements; namespace Unity.UI.Builder { abstract class TransformOriginSelectorPointBase : VisualElement { static readonly string s_UssClassName = "unity-transform-origin-selector__point-base"; static readonly string s_VisualContentName = "visual-content"; float m_X = 0f; float m_Y = 0f; public float x { get { return m_X; } set { m_X = value; style.left = new Length(m_X * 100, LengthUnit.Percent); } } public float y { get { return m_Y; } set { m_Y = value; style.top = new Length(m_Y * 100, LengthUnit.Percent); } } protected TransformOriginSelectorPointBase(string visualContentUXMLFile = null) { AddToClassList(s_UssClassName); style.position = Position.Absolute; var template = BuilderPackageUtilities.LoadAssetAtPath<VisualTreeAsset>(visualContentUXMLFile); VisualElement visualContent = template.Instantiate(); visualContent.pickingMode = PickingMode.Ignore; Add(visualContent); visualContent.name = s_VisualContentName; } } class TransformOriginSelectorPoint : TransformOriginSelectorPointBase { static readonly string s_UssClassName = "unity-transform-origin-selector__point"; internal static readonly string s_ClickableAreaName = "clickable-area"; public TransformOriginSelectorPoint(Action<float, float> clicked, string tooltip) : base(BuilderConstants.UtilitiesPath + "/StyleField/TransformOriginSelectorPoint.uxml") { AddToClassList(s_UssClassName); var clickableArea = this.Q(s_ClickableAreaName); clickableArea.AddManipulator(new Clickable(() => clicked(x, y))); clickableArea.tooltip = tooltip; } } class TransformOriginSelectorIndicator : TransformOriginSelectorPointBase { public static readonly string s_UssClassName = "unity-transform-origin-selector__indicator"; public static readonly string s_IndicatorAtPresetClassName = s_UssClassName + "--preset"; public TransformOriginSelectorIndicator() : base(BuilderConstants.UtilitiesPath + "/StyleField/TransformOriginSelectorIndicator.uxml") { AddToClassList(s_UssClassName); pickingMode = PickingMode.Ignore; this.Q("shape").pickingMode = PickingMode.Ignore; } } [UsedImplicitly] class TransformOriginSelector : VisualElement { enum NavigationDirection { Backward = -1, Forward = 1 } static readonly string s_UssClassName = "unity-transform-origin-selector"; public static readonly string s_OutOfRangeHorName = "out-of-range-hor"; public static readonly string s_OutOfRangeHorClassName = s_UssClassName + "__out-of-range-hor"; public static readonly string s_OutOfRangeHorPosClassName = s_OutOfRangeHorClassName + "--pos"; public static readonly string s_OutOfRangeHorNegClassName = s_OutOfRangeHorClassName + "--neg"; public static readonly string s_OutOfRangeVerName = "out-of-range-ver"; public static readonly string s_OutOfRangeVerClassName = s_UssClassName + "__out-of-range-ver"; public static readonly string s_OutOfRangeVerPosClassName = s_OutOfRangeVerClassName + "--pos"; public static readonly string s_OutOfRangeVerNegClassName = s_OutOfRangeVerClassName + "--neg"; public static readonly string s_FocusRectName = "focus-rect"; static readonly string s_ContainerName = "container"; private TransformOriginSelectorIndicator m_Indicator; private VisualElement m_OutOfRangeVer; private VisualElement m_OutOfRangeHor; private VisualElement m_Container; float m_OriginX = 0; float m_OriginY = 0; public Action<float, float> pointSelected; public bool hasFocus { get { return elementPanel != null && elementPanel.focusController.GetLeafFocusedElement() == this; } } public float originX { get => m_OriginX; set { if (m_OriginX == value) return; m_OriginX = value; UpdateIndicator(); } } public float originY { get => m_OriginY; set { if (m_OriginY == value) return; m_OriginY = value; UpdateIndicator(); } } [Serializable] public new class UxmlSerializedData : VisualElement.UxmlSerializedData { public override object CreateInstance() => new TransformOriginSelector(); } public TransformOriginSelector() { AddToClassList(s_UssClassName); Add(new VisualElement { name = s_FocusRectName, pickingMode = PickingMode.Ignore }); m_Container = new VisualElement(); m_Container.name = s_ContainerName; AddPoint(0, 0, "left top"); AddPoint(0.5f, 0, "top"); AddPoint(1, 0, "right top"); AddPoint(1, 0.5f, "right"); AddPoint(1, 1, "right bottom"); AddPoint(0.5f, 1, "bottom"); AddPoint(0, 1, "left bottom"); AddPoint(0, 0.5f, "left"); AddPoint(0.5f, 0.5f, "Center"); m_Indicator = new TransformOriginSelectorIndicator(); m_OutOfRangeHor = new VisualElement { name = s_OutOfRangeHorName, pickingMode = PickingMode.Ignore }; m_OutOfRangeHor.AddToClassList(s_OutOfRangeHorClassName); m_OutOfRangeVer = new VisualElement { name = s_OutOfRangeVerName, pickingMode = PickingMode.Ignore }; m_OutOfRangeVer.AddToClassList(s_OutOfRangeVerClassName); m_Indicator.Add(m_OutOfRangeHor); m_Indicator.Add(m_OutOfRangeVer); m_Container.Add(m_Indicator); Add(m_Container); UpdateIndicator(); focusable = true; RegisterCallback<KeyDownEvent>(OnKeyDown); } void UpdateIndicator() { m_OutOfRangeHor.RemoveFromClassList(s_OutOfRangeHorPosClassName); m_OutOfRangeHor.RemoveFromClassList(s_OutOfRangeHorNegClassName); m_OutOfRangeVer.RemoveFromClassList(s_OutOfRangeVerPosClassName); m_OutOfRangeVer.RemoveFromClassList(s_OutOfRangeVerNegClassName); m_Indicator.RemoveFromClassList(TransformOriginSelectorIndicator.s_IndicatorAtPresetClassName); if (float.IsNaN(originX) || float.IsNaN(originY)) { m_Indicator.style.display = DisplayStyle.None; return; } else { m_Indicator.style.display = DisplayStyle.Flex; } var x = (int)Math.Round(originX * 100); var y = (int)Math.Round(originY * 100); bool inRange = true; if (x > 100) { m_Indicator.x = 1; m_OutOfRangeHor.AddToClassList(s_OutOfRangeHorPosClassName); inRange = false; } else if (x < 0) { m_Indicator.x = 0; m_OutOfRangeHor.AddToClassList(s_OutOfRangeHorNegClassName); inRange = false; } else { m_Indicator.x = originX; } if (y > 100) { m_Indicator.y = 1; m_OutOfRangeVer.AddToClassList(s_OutOfRangeVerPosClassName); inRange = false; } else if (y < 0) { m_Indicator.y = 0; m_OutOfRangeVer.AddToClassList(s_OutOfRangeVerNegClassName); inRange = false; } else { m_Indicator.y = originY; } // if the indicator is at a preset value: 0%, 50%, 100% then highlight it if (inRange && (x % 50 == 0) && (y % 50 == 0)) { m_Indicator.AddToClassList(TransformOriginSelectorIndicator.s_IndicatorAtPresetClassName); } } void AddPoint(float x, float y, string tooltip) { var point = new TransformOriginSelectorPoint(OnPointClicked, tooltip) { x = x, y = y }; m_Container.Add(point); } void OnPointClicked(float x, float y) { pointSelected?.Invoke(x, y); } void OnKeyDown(KeyDownEvent e) { if (IsNavigationKey(e.keyCode)) { Navigate(e.keyCode); } } static bool IsNavigationKey(KeyCode keyCode) { return keyCode == KeyCode.LeftArrow || keyCode == KeyCode.RightArrow || keyCode == KeyCode.UpArrow || keyCode == KeyCode.DownArrow; } void Navigate(KeyCode keyCode) { // If the position were undefined (values in px) then move to the center if (float.IsNaN(originX) || float.IsNaN(originY)) { pointSelected(0.5f, 0.5f); } else { // Ensure that to clamp the new postion in case the current position is out of bounds float newX = Mathf.Clamp(originX, 0, 1); float newY = Mathf.Clamp(originY, 0, 1); switch (keyCode) { case KeyCode.LeftArrow: newX = GetNextPosition(originX, NavigationDirection.Backward); break; case KeyCode.RightArrow: newX = GetNextPosition(originX, NavigationDirection.Forward); break; case KeyCode.UpArrow: newY = GetNextPosition(originY, NavigationDirection.Backward); break; case KeyCode.DownArrow: newY = GetNextPosition(originY, NavigationDirection.Forward); break; default: break; } if (!Mathf.Approximately(newX, originX) || !Mathf.Approximately(newY, originY)) { pointSelected(newX, newY); } } } static float GetNextPosition(float value, NavigationDirection navigationDirection) { const float k_Step = 0.5f; var newPos = value + ((int)navigationDirection * (k_Step / 2 + 0.0005f)); float index = Mathf.Round(newPos / k_Step); return Mathf.Clamp(index * k_Step, 0, 1); } } }
UnityCsReference/Modules/UIBuilder/Editor/Utilities/StyleField/TransformOriginSelector.cs/0
{ "file_path": "UnityCsReference/Modules/UIBuilder/Editor/Utilities/StyleField/TransformOriginSelector.cs", "repo_id": "UnityCsReference", "token_count": 5856 }
481
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System.Linq; using System.Reflection; using System.Text.RegularExpressions; using UnityEditor.UIElements.StyleSheets; using UnityEngine; using UnityEngine.UIElements; using UnityEngine.UIElements.StyleSheets; namespace Unity.UI.Builder { internal static class StyleSheetUtilities { public static readonly PropertyInfo[] ComputedStylesFieldInfos = typeof(ComputedStyle).GetProperties(BindingFlags.Instance | BindingFlags.Public); public static readonly PropertyInfo[] StylesFieldInfos = typeof(IStyle).GetProperties(BindingFlags.Instance | BindingFlags.Public); readonly static StyleSheetImporterImpl s_StyleSheetImporter = new StyleSheetImporterImpl(); public static StyleSheet CreateInstance() { var newStyleSheet = ScriptableObject.CreateInstance<StyleSheet>(); newStyleSheet.hideFlags = HideFlags.DontUnloadUnusedAsset | HideFlags.DontSaveInEditor; // Initialize all defaults. s_StyleSheetImporter.Import(newStyleSheet, ""); return newStyleSheet; } public static StyleValueKeyword ConvertStyleKeyword(StyleKeyword keyword) { switch (keyword) { case StyleKeyword.Auto: return StyleValueKeyword.Auto; case StyleKeyword.None: return StyleValueKeyword.None; case StyleKeyword.Initial: return StyleValueKeyword.Initial; } return StyleValueKeyword.Auto; } public static void AddFakeSelector(VisualElement selectorElement) { if (selectorElement == null) return; var styleSheet = selectorElement.GetClosestStyleSheet(); if (styleSheet == null) return; StyleComplexSelector complexSelector = selectorElement.GetProperty(BuilderConstants.ElementLinkedStyleSelectorVEPropertyName) as StyleComplexSelector; var fakeSelectorString = BuilderConstants.UssSelectorNameSymbol + selectorElement.name; var fakeSelector = styleSheet.FindSelector(fakeSelectorString); // May already exist because of Undo/Redo if (fakeSelector == null) fakeSelector = styleSheet.AddSelector(fakeSelectorString); fakeSelector.rule = complexSelector.rule; fakeSelector.ruleIndex = complexSelector.ruleIndex; // shared index selectorElement.SetProperty(BuilderConstants.ElementLinkedFakeStyleSelectorVEPropertyName, fakeSelector); // To ensure that the fake selector is removed from the stylesheet if the builder gets closed with a selector still selected selectorElement.RegisterCallback<DetachFromPanelEvent>(OnSelectorElementDetachedFromPanel); selectorElement.IncrementVersion((VersionChangeType)(-1)); } public static void RemoveFakeSelector(VisualElement selectorElement) { if (selectorElement == null) return; var styleSheet = selectorElement.GetClosestStyleSheet(); if (styleSheet == null) return; StyleComplexSelector fakeSelector = selectorElement.GetProperty(BuilderConstants.ElementLinkedFakeStyleSelectorVEPropertyName) as StyleComplexSelector; if (fakeSelector != null) { selectorElement.SetProperty(BuilderConstants.ElementLinkedFakeStyleSelectorVEPropertyName, null); styleSheet.RemoveSelector(fakeSelector); selectorElement.UnregisterCallback<DetachFromPanelEvent>(OnSelectorElementDetachedFromPanel); } } static void OnSelectorElementDetachedFromPanel(DetachFromPanelEvent e) { RemoveFakeSelector(e.elementTarget); } public static Dimension.Unit ConvertToDimensionUnit(LengthUnit unit) { return unit == LengthUnit.Percent ? Dimension.Unit.Percent : Dimension.Unit.Pixel; } public static Dimension.Unit ConvertToDimensionUnit(AngleUnit unit) { switch (unit) { case AngleUnit.Gradian: return Dimension.Unit.Gradian; case AngleUnit.Radian: return Dimension.Unit.Radian; case AngleUnit.Turn: return Dimension.Unit.Turn; default: return Dimension.Unit.Degree; } } public static string GetCleanVariableName(string value) { if (string.IsNullOrEmpty(value)) return value; var cleanName = Regex.Replace(value.Trim(), BuilderConstants.USSVariablePattern, BuilderConstants.USSVariableInvalidCharFiller); if (!cleanName.StartsWith(BuilderConstants.UssVariablePrefix)) cleanName = BuilderConstants.UssVariablePrefix + cleanName; return cleanName; } } }
UnityCsReference/Modules/UIBuilder/Editor/Utilities/StyleSheetExtensions/StyleSheetUtilities.cs/0
{ "file_path": "UnityCsReference/Modules/UIBuilder/Editor/Utilities/StyleSheetExtensions/StyleSheetUtilities.cs", "repo_id": "UnityCsReference", "token_count": 2127 }
482
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System.Collections.Generic; using UnityEngine.UIElements; namespace Unity.UI.Builder { internal static class TemplateAssetExtensions { public static void SetAttributeOverride( this TemplateAsset ta, string elementName, string attributeName, string value) { // See if the override already exists. for (int i = 0; i < ta.attributeOverrides.Count; ++i) { var over = ta.attributeOverrides[i]; if (over.m_ElementName == elementName && over.m_AttributeName == attributeName) { over.m_ElementName = elementName; over.m_AttributeName = attributeName; over.m_Value = value; ta.attributeOverrides[i] = over; return; } } // If the override does not exist, add it. var attributeOverride = new TemplateAsset.AttributeOverride(); attributeOverride.m_ElementName = elementName; attributeOverride.m_AttributeName = attributeName; attributeOverride.m_Value = value; ta.attributeOverrides.Add(attributeOverride); } public static void RemoveAttributeOverride( this TemplateAsset ta, string elementName, string attributeName) { // See if the override already exists. for (int i = 0; i < ta.attributeOverrides.Count; ++i) { var over = ta.attributeOverrides[i]; if (over.m_ElementName == elementName && over.m_AttributeName == attributeName) { ta.attributeOverrides.RemoveAt(i); return; } } } } }
UnityCsReference/Modules/UIBuilder/Editor/Utilities/VisualTreeAssetExtensions/TemplateAssetExtensions.cs/0
{ "file_path": "UnityCsReference/Modules/UIBuilder/Editor/Utilities/VisualTreeAssetExtensions/TemplateAssetExtensions.cs", "repo_id": "UnityCsReference", "token_count": 947 }
483
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using UnityEngine; using UnityEngine.Assertions; namespace UnityEngine.UIElements { /// <summary> /// Script interface for <see cref="VisualElement"/> background-size style property <see cref="IStyle.BackgroundSize"/>. /// </summary> public partial struct BackgroundSize : IEquatable<BackgroundSize> { /// <summary> /// Background size type /// </summary> public BackgroundSizeType sizeType { get { return m_SizeType; } set { m_SizeType = value; m_X = new Length(0); m_Y = new Length(0); } } /// <summary> /// Background size x /// </summary> public Length x { get { return m_X; } set { m_X = value; m_SizeType = BackgroundSizeType.Length; } } /// <summary> /// Background size y /// </summary> public Length y { get { return m_Y; } set { m_Y = value; m_SizeType = BackgroundSizeType.Length; } } private BackgroundSizeType m_SizeType; private Length m_X; private Length m_Y; /// <summary> /// Create a BackgroundSize with x and y repeat /// </summary> public BackgroundSize(Length sizeX, Length sizeY) { m_SizeType = BackgroundSizeType.Length; m_X = sizeX; m_Y = sizeY; } /// <summary> /// Create a BackgroundSize using Enum /// </summary> public BackgroundSize(BackgroundSizeType sizeType) { m_SizeType = sizeType; m_X = new Length(0); m_Y = new Length(0); } internal static BackgroundSize Initial() { return BackgroundPropertyHelper.ConvertScaleModeToBackgroundSize(); } /// <undoc/> public override bool Equals(object obj) { return obj is BackgroundSize && Equals((BackgroundSize)obj); } /// <undoc/> public bool Equals(BackgroundSize other) { return other.x == x && other.y == y && other.sizeType == sizeType; } /// <undoc/> public override int GetHashCode() { var hashCode = 1500536833; hashCode = hashCode * -1521134295 + m_SizeType.GetHashCode(); hashCode = hashCode * -1521134295 + m_X.GetHashCode(); hashCode = hashCode * -1521134295 + m_Y.GetHashCode(); return hashCode; } /// <undoc/> public static bool operator==(BackgroundSize style1, BackgroundSize style2) { return style1.Equals(style2); } /// <undoc/> public static bool operator!=(BackgroundSize style1, BackgroundSize style2) { return !(style1 == style2); } /// <undoc/> public override string ToString() { return $"(sizeType:{sizeType} x:{x}, y:{y})"; } } }
UnityCsReference/Modules/UIElements/Core/BackgroundSize.cs/0
{ "file_path": "UnityCsReference/Modules/UIElements/Core/BackgroundSize.cs", "repo_id": "UnityCsReference", "token_count": 1766 }
484
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; using System.Text.RegularExpressions; using Unity.Properties; using UnityEngine.Bindings; using UnityEngine.Pool; using UnityEngine.UIElements.Internal; namespace UnityEngine.UIElements { /// <summary> /// Type result of a binding visitation. /// </summary> [VisibleToOtherModules("UnityEditor.UIBuilderModule")] internal readonly struct BindingTypeResult { /// <summary> /// The property type. /// </summary> public readonly Type type; /// <summary> /// The visitation result. /// </summary> public readonly VisitReturnCode returnCode; /// <summary> /// The index of the property path part that is causing the error, -1 if visitation is successful. /// </summary> public readonly int errorIndex; /// <summary> /// The property path visited. /// </summary> public readonly PropertyPath resolvedPath; internal BindingTypeResult(Type type, in PropertyPath resolvedPath) { this.type = type; this.resolvedPath = resolvedPath; returnCode = VisitReturnCode.Ok; errorIndex = -1; } internal BindingTypeResult(VisitReturnCode returnCode, int errorIndex, in PropertyPath resolvedPath) { type = null; this.resolvedPath = resolvedPath; this.returnCode = returnCode; this.errorIndex = errorIndex; } } /// <summary> /// Provides information about a binding. /// </summary> public readonly struct BindingInfo { /// <summary> /// The visual element targeted by the binding. /// </summary> public VisualElement targetElement { get; } /// <summary> /// The binding id. /// </summary> public BindingId bindingId { get; } /// <summary> /// The binding matching this information. /// </summary> public Binding binding { get; } private BindingInfo(VisualElement targetElement, in BindingId bindingId, Binding binding) { this.targetElement = targetElement; this.bindingId = bindingId; this.binding = binding; } internal static BindingInfo FromRequest(VisualElement target, in PropertyPath targetPath, Binding binding) { return new BindingInfo(target, targetPath, binding); } internal static BindingInfo FromBindingData(in DataBindingManager.BindingData bindingData) { return new BindingInfo(bindingData.target.element, bindingData.target.bindingId, bindingData.binding); } } /// <summary> /// Provides information about the resolved type of a property. /// </summary> [VisibleToOtherModules("UnityEditor.UIBuilderModule")] internal readonly struct PropertyPathInfo { /// <summary> /// The property path used. /// </summary> public readonly PropertyPath propertyPath; /// <summary> /// The resolved property type. /// </summary> public readonly Type type; internal PropertyPathInfo(in PropertyPath propertyPath, Type type) { this.propertyPath = propertyPath; this.type = type; } } /// <summary> /// Provides a subset of helper methods for the data binding system. /// </summary> [VisibleToOtherModules("UnityEditor.UIBuilderModule")] internal static class DataBindingUtility { static readonly Pool.ObjectPool<TypePathVisitor> k_TypeVisitors = new(() => new TypePathVisitor(), v => v.Reset(), defaultCapacity: 1); static readonly Pool.ObjectPool<AutoCompletePathVisitor> k_AutoCompleteVisitors = new(() => new AutoCompletePathVisitor(), v => v.Reset(), defaultCapacity: 1); private static readonly Regex s_ReplaceIndices = new Regex("\\[[0-9]+\\]", RegexOptions.Compiled); /// <summary> /// Returns a list of all bound elements on a panel. /// </summary> /// <param name="panel">The panel to inspect.</param> /// <param name="boundElements">A list to contain the bound elements.</param> /// <remarks> /// The <see cref="boundElements"/> list will only be added to. /// </remarks> public static void GetBoundElements(IPanel panel, List<VisualElement> boundElements) { if (panel is BaseVisualElementPanel p) boundElements.AddRange(p.dataBindingManager.GetUnorderedBoundElements()); } /// <summary> /// Fills a list of all bindings on an element. /// </summary> /// <param name="element">The element to inspect.</param> /// <param name="result">The resulting list of binding infos.</param> /// <remarks>The order in which the binding information is returned is undefined.</remarks> public static void GetBindingsForElement(VisualElement element, List<BindingInfo> result) { using var pool = HashSetPool<PropertyPath>.Get(out var visited); foreach (var bindingRequest in DataBindingManager.GetBindingRequests(element)) { if (visited.Add(bindingRequest.bindingId) && null != bindingRequest.binding) result.Add(BindingInfo.FromRequest(element, bindingRequest.bindingId, bindingRequest.binding)); } if (element.elementPanel == null) return; var bindingData = element.elementPanel.dataBindingManager.GetBindingData(element); foreach (var binding in bindingData) { if (visited.Add(binding.target.bindingId)) result.Add(BindingInfo.FromBindingData(binding)); } } /// <summary> /// Gets the binding on a visual element at the specified path. /// </summary> /// <param name="element">The element to inspect.</param> /// <param name="bindingId">The id of the binding.</param> /// <param name="bindingInfo">The binding found on the element.</param> /// <returns>Whether a binding was found or not.</returns> public static bool TryGetBinding(VisualElement element, in BindingId bindingId, out BindingInfo bindingInfo) { if (DataBindingManager.TryGetBindingRequest(element, bindingId, out var binding)) { // The binding is being removed. if (null == binding) { bindingInfo = default; return false; } bindingInfo = BindingInfo.FromRequest(element, bindingId, binding); return true; } if (element.elementPanel != null) { if (element.elementPanel.dataBindingManager.TryGetBindingData(element, bindingId, out var bindingData)) { bindingInfo = BindingInfo.FromBindingData(bindingData); return true; } } bindingInfo = default; return false; } /// <summary> /// Finds the closest unresolved data source object or the data source type and the chain of binding paths inherited from the hierarchy of the specified visual element. /// </summary> /// <param name="element">The element to start from</param> /// <param name="dataSourceObject">The data source object found</param> /// <param name="dataSourceType">The data source type found</param> /// <param name="fullPath">The chain of paths found</param> /// <returns>Returns true if at least the data source, the data source type or a binding path is inherited</returns> [VisibleToOtherModules("UnityEditor.UIBuilderModule")] internal static bool TryGetDataSourceOrDataSourceTypeFromHierarchy(VisualElement element, out object dataSourceObject, out Type dataSourceType, out PropertyPath fullPath) { var sourceElement = element; dataSourceObject = null; dataSourceType = null; fullPath = new PropertyPath(); while (sourceElement != null) { if (!sourceElement.dataSourcePath.IsEmpty) { if (fullPath.IsEmpty) fullPath = sourceElement.dataSourcePath; else fullPath = PropertyPath.Combine(sourceElement.dataSourcePath, fullPath); } dataSourceObject = sourceElement.dataSource; if (sourceElement.dataSource != null) return true; dataSourceType = sourceElement.dataSourceType; if (dataSourceType != null) return true; sourceElement = sourceElement.hierarchy.parent; } return !fullPath.IsEmpty; } /// <summary> /// Finds the closest resolved data source in the hierarchy, including relative data sources. /// </summary> /// <param name="element">The element to start from.</param> /// <param name="dataSource">The data source found.</param> /// <returns>The resolved data source.</returns> public static bool TryGetRelativeDataSourceFromHierarchy(VisualElement element, out object dataSource) { var context = element.GetHierarchicalDataSourceContext(); dataSource = context.dataSource; if (context.dataSourcePath.IsEmpty) return null != dataSource; if (null == context.dataSource) return false; if (!PropertyContainer.TryGetValue(ref dataSource, context.dataSourcePath, out object value)) return true; dataSource = value; return true; } /// <summary> /// Finds the closest resolved data source type in the hierarchy, including relative data source types. /// </summary> /// <param name="element">The element to start from.</param> /// <param name="type">The data source type found.</param> /// <returns>True if the resolved data source type is found.</returns> [VisibleToOtherModules("UnityEditor.UIBuilderModule")] internal static bool TryGetRelativeDataSourceTypeFromHierarchy(VisualElement element, out Type type) { type = null; if (TryGetDataSourceOrDataSourceTypeFromHierarchy(element, out var dataSource, out var dataSourceType, out var bindingPath)) { // If the data source is defined then the binding path is related to it even if the data source type is defined. if (dataSource != null || dataSourceType == null) return false; // If the (combined) binding path is empty then returns the top data source type. if (bindingPath.IsEmpty) { type = dataSourceType; } // otherwise get the type of the property resolved from the (combined) binding path from the top data source type. else { var bindingPathStr = bindingPath.ToString(); using var pool = ListPool<PropertyPathInfo>.Get(out var allProperties); GetPropertyPaths(dataSourceType, int.MaxValue, allProperties); // Replace all the indices to '0' in the binding path before searching because the indices in the paths returned by DataBindingUtility.GetPropertyPaths are all '0'. bindingPathStr = ReplaceAllIndicesInPath(bindingPathStr, "0"); foreach (var prop in allProperties) { if (prop.propertyPath.ToString() != bindingPathStr) continue; type = prop.type; break; } } } return type != null; } /// <summary> /// Replaces all indices in the specified text by the new index. /// </summary> /// <param name="path">The original path</param> /// <param name="newText">The text to replace the indices</param> /// <returns>The new path with replaced indices</returns> [VisibleToOtherModules("UnityEditor.UIBuilderModule")] internal static string ReplaceAllIndicesInPath(string path, string newText) { return path.Contains('[') ? s_ReplaceIndices.Replace(path, $"[{newText}]") : path; } /// <summary> /// Retrieves the last cached binding result for the UI update. /// </summary> /// <param name="bindingId">The binding id to look for.</param> /// <param name="element">The element it is applied on.</param> /// <param name="result">The result of the last UI update for this binding, if found.</param> /// <returns>Whether a cached result was found or not.</returns> public static bool TryGetLastUIBindingResult(in BindingId bindingId, VisualElement element, out BindingResult result) { result = default; var bindingData = GetActiveBindingData(bindingId, element); if (bindingData?.binding == null || element.elementPanel == null) { return false; } return element.elementPanel.dataBindingManager.TryGetLastUIBindingResult(bindingData, out result); } /// <summary> /// Retrieves the last cached binding result for the source update. /// </summary> /// <param name="bindingId">The binding id to look for.</param> /// <param name="element">The element it is applied on.</param> /// <param name="result">The result of the last source update for this binding, if found.</param> /// <returns>Whether a cached result was found or not.</returns> public static bool TryGetLastSourceBindingResult(in BindingId bindingId, VisualElement element, out BindingResult result) { result = default; var bindingData = GetActiveBindingData(bindingId, element); if (bindingData?.binding == null) { return false; } return element.elementPanel.dataBindingManager.TryGetLastSourceBindingResult(bindingData, out result); } /// <summary> /// Fills a list of ids of all conversion groups that can convert between the 2 provided types. /// </summary> /// <param name="sourceType">The source type of the conversion.</param> /// <param name="destinationType">The destination type of the conversion.</param> /// <param name="result">The resulting list of converter ids.</param> public static void GetMatchingConverterGroups(Type sourceType, Type destinationType, List<string> result) { using (ListPool<ConverterGroup>.Get(out var groups)) { ConverterGroups.GetAllConverterGroups(groups); foreach (var group in groups) { if (group.registry.TryGetConverter(sourceType, destinationType, out _)) { result.Add(group.id); } } } } /// <summary> /// Fills a list of ids of all conversion groups that can convert from the source type. /// </summary> /// <param name="sourceType">The source type of the conversion.</param> /// <param name="result">The resulting list of converter ids.</param> public static void GetMatchingConverterGroupsFromType(Type sourceType, List<string> result) { using (ListPool<ConverterGroup>.Get(out var groups)) using (ListPool<Type>.Get(out var types)) { ConverterGroups.GetAllConverterGroups(groups); foreach (var group in groups) { group.registry.GetAllTypesConvertingFromType(sourceType, types); if (types.Count > 0) { result.Add(group.id); } types.Clear(); } } } /// <summary> /// Fills a list of ids of all conversion groups that can convert to the destination type. /// </summary> /// <param name="destinationType">The destination type of the conversion.</param> /// <param name="result">The resulting list of converter ids.</param> public static void GetMatchingConverterGroupsToType(Type destinationType, List<string> result) { using (ListPool<ConverterGroup>.Get(out var groups)) using (ListPool<Type>.Get(out var types)) { ConverterGroups.GetAllConverterGroups(groups); foreach (var group in groups) { group.registry.GetAllTypesConvertingToType(destinationType, types); if (types.Count > 0) { result.Add(group.id); } types.Clear(); } } } /// <summary> /// Fills a list of all types converting to the provided type, including local conversions on the binding and global ui conversions, /// when converting data between a data source to a UI control. /// </summary> /// <remarks>Does not include standard primitive conversions.</remarks> /// <param name="binding">The binding to inspect.</param> /// <param name="destinationType">The output type.</param> /// <param name="result">The resulting list of types that can be converted.</param> public static void GetAllConversionsFromSourceToUI(DataBinding binding, Type destinationType, List<Type> result) { result.Add(destinationType); binding?.sourceToUiConverters.registry.GetAllTypesConvertingToType(destinationType, result); ConverterGroups.globalConverters.registry.GetAllTypesConvertingToType(destinationType, result); ConverterGroups.primitivesConverters.registry.GetAllTypesConvertingToType(destinationType, result); } /// <summary> /// Fills a list of all types converting to the provided type, including local conversions on the binding and global ui conversions, /// when converting data between a UI control to a data source. /// </summary> /// <param name="binding">The binding to inspect.</param> /// <param name="sourceType">The type coming from the data source.</param> /// <param name="result">A list of types that can be converted.</param> public static void GetAllConversionsFromUIToSource(DataBinding binding, Type sourceType, List<Type> result) { result.Add(sourceType); binding?.uiToSourceConverters.registry.GetAllTypesConvertingToType(sourceType, result); ConverterGroups.globalConverters.registry.GetAllTypesConvertingToType(sourceType, result); ConverterGroups.primitivesConverters.registry.GetAllTypesConvertingToType(sourceType, result); } /// <summary> /// Checks whether a path exists on a data source or not and returns its type information. /// </summary> /// <param name="dataSource">The data source to inspect.</param> /// <param name="path">The path of the property to look for.</param> /// <returns>Type information of the property at the specified path.</returns> public static BindingTypeResult IsPathValid(object dataSource, string path) { return IsPathValid(dataSource, dataSource?.GetType(), path); } /// <summary> /// Checks whether a path exists on a source type or not and returns its type information. /// </summary> /// <param name="type">The type to inspect.</param> /// <param name="path">The path of the property to look for.</param> /// <returns>Type information of the property at the specified path.</returns> public static BindingTypeResult IsPathValid(Type type, string path) { return IsPathValid(null, type, path); } static BindingTypeResult IsPathValid(object dataSource, Type type, string path) { if (type == null) return new BindingTypeResult(VisitReturnCode.NullContainer, 0, default); var visitor = k_TypeVisitors.Get(); BindingTypeResult result; var properties = PropertyBag.GetPropertyBag(type); try { visitor.Path = new PropertyPath(path); if (properties == null) { visitor.ReturnCode = VisitReturnCode.MissingPropertyBag; } if (dataSource == null) { properties?.Accept(visitor); } else { properties?.Accept(visitor, ref dataSource); } if (visitor.ReturnCode == VisitReturnCode.Ok) { result = new BindingTypeResult(visitor.resolvedType, visitor.Path); } else { var resolvedPath = PropertyPath.SubPath(visitor.Path, 0, visitor.PathIndex); result = new BindingTypeResult(visitor.ReturnCode, visitor.PathIndex, resolvedPath); } } finally { k_TypeVisitors.Release(visitor); } return result; } /// <summary> /// Fills a list of all property paths available on this data source. /// </summary> /// <param name="dataSource">The data source to inspect.</param> /// <param name="depth">The maximum path depth to visit. The recommended depth to avoid <see cref="PropertyPath"/> allocations is 4.</param> /// <param name="listResult">The resulting list of property paths available on this data source.</param> public static void GetPropertyPaths(object dataSource, int depth, List<PropertyPathInfo> listResult) { GetPropertyPaths(dataSource, dataSource?.GetType(), depth, listResult); } /// <summary> /// Fills a list of all property paths available on this data source. /// </summary> /// <param name="type">The type to inspect.</param> /// <param name="depth">The maximum path depth to visit. The recommended depth to avoid <see cref="PropertyPath"/> allocations is 4.</param> /// <param name="listResult">The resulting list of property paths available on this type.</param> public static void GetPropertyPaths(Type type, int depth, List<PropertyPathInfo> listResult) { GetPropertyPaths(null, type, depth, listResult); } static void GetPropertyPaths(object dataSource, Type type, int depth, List<PropertyPathInfo> resultList) { if (type == null) return; var bag = PropertyBag.GetPropertyBag(type); if (bag == null) return; var visitor = k_AutoCompleteVisitors.Get(); try { visitor.propertyPathList = resultList; visitor.maxDepth = depth; if (dataSource == null) bag.Accept(visitor); else bag.Accept(visitor, ref dataSource); } finally { k_AutoCompleteVisitors.Release(visitor); } } static DataBindingManager.BindingData GetActiveBindingData(in BindingId bindingId, VisualElement element) { if (element.elementPanel != null && element.elementPanel.dataBindingManager.TryGetBindingData(element, bindingId, out var activeBinding)) return activeBinding; return default; } } }
UnityCsReference/Modules/UIElements/Core/Bindings/DataBindingUtility.cs/0
{ "file_path": "UnityCsReference/Modules/UIElements/Core/Bindings/DataBindingUtility.cs", "repo_id": "UnityCsReference", "token_count": 10401 }
485
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; namespace UnityEngine.UIElements { class ReusableTreeViewItem : ReusableCollectionItem { Toggle m_Toggle; VisualElement m_Container; VisualElement m_IndentElement; VisualElement m_BindableContainer; VisualElement m_Checkmark; public override VisualElement rootElement => m_Container ?? bindableElement; public event Action<PointerUpEvent> onPointerUp; public event Action<ChangeEvent<bool>> onToggleValueChanged; int m_Depth; float m_IndentWidth; // Internal for tests. internal float indentWidth => m_IndentWidth; EventCallback<PointerUpEvent> m_PointerUpCallback; EventCallback<ChangeEvent<bool>> m_ToggleValueChangedCallback; EventCallback<GeometryChangedEvent> m_ToggleGeometryChangedCallback; public ReusableTreeViewItem() { m_PointerUpCallback = OnPointerUp; m_ToggleValueChangedCallback = OnToggleValueChanged; m_ToggleGeometryChangedCallback = OnToggleGeometryChanged; } public override void Init(VisualElement item) { base.Init(item); var container = new VisualElement() { name = BaseTreeView.itemUssClassName }; container.AddToClassList(BaseTreeView.itemUssClassName); InitExpandHierarchy(container, item); } protected void InitExpandHierarchy(VisualElement root, VisualElement item) { m_Container = root; m_Container.style.flexDirection = FlexDirection.Row; m_IndentElement = new VisualElement() { name = BaseTreeView.itemIndentUssClassName, style = { flexDirection = FlexDirection.Row }, }; m_Container.hierarchy.Add(m_IndentElement); m_Toggle = new Toggle { name = BaseTreeView.itemToggleUssClassName, userData = this }; m_Toggle.AddToClassList(Foldout.toggleUssClassName); m_Toggle.AddToClassList(BaseTreeView.itemToggleUssClassName); m_Toggle.visualInput.AddToClassList(Foldout.inputUssClassName); m_Checkmark = m_Toggle.visualInput.Q(className: Toggle.checkmarkUssClassName); m_Checkmark.AddToClassList(Foldout.checkmarkUssClassName); m_Container.hierarchy.Add(m_Toggle); m_BindableContainer = new VisualElement() { name = BaseTreeView.itemContentContainerUssClassName, style = { flexGrow = 1 }, }; m_BindableContainer.AddToClassList(BaseTreeView.itemContentContainerUssClassName); m_Container.Add(m_BindableContainer); m_BindableContainer.Add(item); } public override void PreAttachElement() { base.PreAttachElement(); rootElement.AddToClassList(BaseTreeView.itemUssClassName); m_Container?.RegisterCallback(m_PointerUpCallback); m_Toggle?.visualInput.Q(className: Toggle.checkmarkUssClassName).RegisterCallback(m_ToggleGeometryChangedCallback); m_Toggle?.RegisterValueChangedCallback(m_ToggleValueChangedCallback); } public override void DetachElement() { base.DetachElement(); rootElement.RemoveFromClassList(BaseTreeView.itemUssClassName); m_Container?.UnregisterCallback(m_PointerUpCallback); m_Toggle?.visualInput.Q(className: Toggle.checkmarkUssClassName).UnregisterCallback(m_ToggleGeometryChangedCallback); m_Toggle?.UnregisterValueChangedCallback(m_ToggleValueChangedCallback); } public void Indent(int depth) { if (m_IndentElement == null) return; m_Depth = depth; UpdateIndentLayout(); } public void SetExpandedWithoutNotify(bool expanded) { m_Toggle?.SetValueWithoutNotify(expanded); } public void SetToggleVisibility(bool visible) { if (m_Toggle != null) m_Toggle.visible = visible; } void OnToggleGeometryChanged(GeometryChangedEvent evt) { var width = m_Checkmark.resolvedStyle.width + m_Checkmark.resolvedStyle.marginLeft + m_Checkmark.resolvedStyle.marginRight; if (Math.Abs(width - m_IndentWidth) < float.Epsilon) return; m_IndentWidth = width; UpdateIndentLayout(); } void UpdateIndentLayout() { m_IndentElement.style.width = m_IndentWidth * m_Depth; m_IndentElement.EnableInClassList(BaseTreeView.itemIndentUssClassName, m_Depth > 0); } void OnPointerUp(PointerUpEvent evt) { onPointerUp?.Invoke(evt); } void OnToggleValueChanged(ChangeEvent<bool> evt) { onToggleValueChanged?.Invoke(evt); } } }
UnityCsReference/Modules/UIElements/Core/Collections/Virtualization/ReusableTreeViewItem.cs/0
{ "file_path": "UnityCsReference/Modules/UIElements/Core/Collections/Virtualization/ReusableTreeViewItem.cs", "repo_id": "UnityCsReference", "token_count": 2359 }
486
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; namespace UnityEngine.UIElements { class ButtonStripField : BaseField<int> { [UnityEngine.Internal.ExcludeFromDocs, Serializable] public new class UxmlSerializedData : BaseField<int>.UxmlSerializedData { public override object CreateInstance() => new ButtonStripField(); } [Obsolete("UxmlFactory is deprecated and will be removed. Use UxmlElementAttribute instead.", false)] public new class UxmlFactory : UxmlFactory<ButtonStripField, UxmlTraits> {} [Obsolete("UxmlTraits is deprecated and will be removed. Use UxmlElementAttribute instead.", false)] public new class UxmlTraits : BaseField<int>.UxmlTraits {} public const string className = "unity-button-strip-field"; const string k_ButtonClass = className + "__button"; const string k_IconClass = className + "__button-icon"; const string k_ButtonLeftClass = k_ButtonClass + "--left"; const string k_ButtonMiddleClass = k_ButtonClass + "--middle"; const string k_ButtonRightClass = k_ButtonClass + "--right"; const string k_ButtonAloneClass = k_ButtonClass + "--alone"; readonly List<Button> m_Buttons = new List<Button>(); public void AddButton(string text, string name = "") { var button = CreateButton(name); button.text = text; Add(button); } /// <summary> /// Add a button to the button strip. /// </summary> /// <param name="icon">Icon used for the button</param> /// <param name="name"></param> public void AddButton(Background icon, string name = "") { var button = CreateButton(name); var iconElement = new VisualElement(); iconElement.AddToClassList(k_IconClass); iconElement.style.backgroundImage = icon; button.Add(iconElement); Add(button); } Button CreateButton(string name) { var button = new Button { name = name, }; button.AddToClassList(k_ButtonClass); button.RegisterCallback<DetachFromPanelEvent>(OnButtonDetachFromPanel); button.clicked += () => { value = m_Buttons.IndexOf(button); }; m_Buttons.Add(button); Add(button); RefreshButtonsStyling(); return button; } void OnButtonDetachFromPanel(DetachFromPanelEvent evt) { if (evt.currentTarget is VisualElement element && element.parent is ButtonStripField buttonStrip) { buttonStrip.RefreshButtonsStyling(); buttonStrip.EnsureValueIsValid(); } } void RefreshButtonsStyling() { for (var i = 0; i < m_Buttons.Count; ++i) { var button = m_Buttons[i]; bool alone = m_Buttons.Count == 1; bool left = i == 0; bool right = i == m_Buttons.Count - 1; button.EnableInClassList(k_ButtonAloneClass, alone); button.EnableInClassList(k_ButtonLeftClass, !alone && left); button.EnableInClassList(k_ButtonRightClass, !alone && right); button.EnableInClassList(k_ButtonMiddleClass, !alone && !left && !right); } } /// <summary> /// Creates a <see cref="ButtonStripField"/> with all default properties. The <see cref="itemsSource"/>, /// </summary> public ButtonStripField() : base(null) { } /// <summary> /// Constructs a <see cref="ButtonStripField"/>, with all required properties provided. /// </summary> /// <param name="label">The list of items to use as a data source.</param> public ButtonStripField(string label) : base(label) { AddToClassList(className); } public override void SetValueWithoutNotify(int newValue) { newValue = Mathf.Clamp(newValue, 0, m_Buttons.Count - 1); base.SetValueWithoutNotify(newValue); RefreshButtonsState(); } void EnsureValueIsValid() { SetValueWithoutNotify(Mathf.Clamp(value, 0, m_Buttons.Count - 1)); } void RefreshButtonsState() { for (int i = 0; i < m_Buttons.Count; ++i) { if (i == value) m_Buttons[i].pseudoStates |= PseudoStates.Checked; else m_Buttons[i].pseudoStates &= ~PseudoStates.Checked; } } } }
UnityCsReference/Modules/UIElements/Core/Controls/ButtonStripField.cs/0
{ "file_path": "UnityCsReference/Modules/UIElements/Core/Controls/ButtonStripField.cs", "repo_id": "UnityCsReference", "token_count": 2190 }
487
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License namespace UnityEngine.UIElements { internal class TextEditorEventHandler { protected TextElement textElement; protected TextEditingUtilities editingUtilities; protected TextEditorEventHandler(TextElement textElement, TextEditingUtilities editingUtilities) { this.textElement = textElement; this.editingUtilities = editingUtilities; } public virtual void RegisterCallbacksOnTarget(VisualElement target) {} public virtual void UnregisterCallbacksFromTarget(VisualElement target) {} public virtual void HandleEventBubbleUp(EventBase evt) {} } }
UnityCsReference/Modules/UIElements/Core/Controls/InputField/TextEditor.cs/0
{ "file_path": "UnityCsReference/Modules/UIElements/Core/Controls/InputField/TextEditor.cs", "repo_id": "UnityCsReference", "token_count": 268 }
488
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; namespace UnityEngine.UIElements.Internal { /// <summary> /// Displays the sort arrow indicator and the sort index when multi-sorting. /// </summary> class MultiColumnHeaderColumnSortIndicator : VisualElement { public static readonly string ussClassName = MultiColumnHeaderColumn.ussClassName + "__sort-indicator"; public static readonly string arrowUssClassName = ussClassName + "__arrow"; public static readonly string indexLabelUssClassName = ussClassName + "__index-label"; Label m_IndexLabel; public string sortOrderLabel { get => m_IndexLabel.text; set => m_IndexLabel.text = value; } public MultiColumnHeaderColumnSortIndicator() { AddToClassList(ussClassName); pickingMode = PickingMode.Ignore; VisualElement arrowIndicator = new VisualElement() { pickingMode = PickingMode.Ignore }; arrowIndicator.AddToClassList(arrowUssClassName); Add(arrowIndicator); m_IndexLabel = new Label() { pickingMode = PickingMode.Ignore }; m_IndexLabel.AddToClassList(indexLabelUssClassName); Add(m_IndexLabel); } } /// <summary> /// Displays the icon of a header column control. /// </summary> class MultiColumnHeaderColumnIcon : Image { public static new readonly string ussClassName = MultiColumnHeaderColumn.ussClassName + "__icon"; public bool isImageInline { get; set; } public MultiColumnHeaderColumnIcon() { AddToClassList(ussClassName); RegisterCallback<CustomStyleResolvedEvent>((evt) => UpdateClassList()); } public void UpdateClassList() { parent.RemoveFromClassList(MultiColumnHeaderColumn.hasIconUssClassName); if (image != null || sprite != null || vectorImage != null) { parent.AddToClassList(MultiColumnHeaderColumn.hasIconUssClassName); } } } /// <summary> /// Visual element representing column in header of a multi-column view. By default, it's basically a container for an image and a label. /// </summary> class MultiColumnHeaderColumn : VisualElement { public static readonly string ussClassName = MultiColumnCollectionHeader.ussClassName + "__column"; public static readonly string sortableUssClassName = ussClassName + "--sortable"; public static readonly string sortedAscendingUssClassName = ussClassName + "--sorted-ascending"; public static readonly string sortedDescendingUssClassName = ussClassName + "--sorted-descending"; public static readonly string movingUssClassName = ussClassName + "--moving"; public static readonly string contentContainerUssClassName = ussClassName + "__content-container"; public static readonly string contentUssClassName = ussClassName + "__content"; public static readonly string defaultContentUssClassName = ussClassName + "__default-content"; public static readonly string hasIconUssClassName = contentUssClassName + "--has-icon"; public static readonly string hasTitleUssClassName = contentUssClassName + "--has-title"; public static readonly string titleUssClassName = ussClassName + "__title"; public static readonly string iconElementName = "unity-multi-column-header-column-icon"; public static readonly string titleElementName = "unity-multi-column-header-column-title"; static readonly string s_BoundVEPropertyName = "__bound"; static readonly string s_BindingCallbackVEPropertyName = "__binding-callback"; static readonly string s_UnbindingCallbackVEPropertyName = "__unbinding-callback"; static readonly string s_DestroyCallbackVEPropertyName = "__destroy-callback"; VisualElement m_ContentContainer; VisualElement m_Content; MultiColumnHeaderColumnSortIndicator m_SortIndicatorContainer; IVisualElementScheduledItem m_ScheduledHeaderTemplateUpdate; /// <summary> /// Returns the clickable manipulator. /// </summary> public Clickable clickable { get; private set; } /// <summary> /// Returns the reorder manipulator. /// </summary> public ColumnMover mover { get; private set; } /// <summary> /// The sort order of this column control when multi-sorting. /// </summary> public string sortOrderLabel { get => m_SortIndicatorContainer.sortOrderLabel; set => m_SortIndicatorContainer.sortOrderLabel = value; } /// <summary> /// The column related to this column control. /// </summary> public Column column { get; set; } // For testing internal Label title => content?.Q<Label>(titleElementName); /// <summary> /// The content element of this column control. /// </summary> public VisualElement content { get => m_Content; set { if (m_Content != null) { if (m_Content.parent == m_ContentContainer) { m_Content.RemoveFromHierarchy(); } DestroyHeaderContent(); m_Content = null; } m_Content = value; if (m_Content != null) { m_Content.AddToClassList(contentUssClassName); m_ContentContainer.Add(m_Content); } } } bool isContentBound { get => m_Content != null && (bool) m_Content.GetProperty(s_BoundVEPropertyName); set => m_Content?.SetProperty(s_BoundVEPropertyName, value); } /// <summary> /// Default constructor. /// </summary> public MultiColumnHeaderColumn() : this(new Column()) {} /// <summary> /// Constructor. /// </summary> /// <param name="column"></param> public MultiColumnHeaderColumn(Column column) { this.column = column; column.changed += (c, role) => { if (role == ColumnDataType.HeaderTemplate) { m_ScheduledHeaderTemplateUpdate?.Pause(); m_ScheduledHeaderTemplateUpdate = schedule.Execute(UpdateHeaderTemplate); } else { UpdateDataFromColumn(); } }; column.resized += (c) => UpdateGeometryFromColumn(); AddToClassList(ussClassName); // Enforce to avoid override from uss. style.marginLeft = 0; style.marginTop = 0; style.marginRight = 0; style.marginBottom = 0; style.paddingLeft = 0; style.paddingTop = 0; style.paddingRight = 0; style.paddingBottom = 0; Add(m_SortIndicatorContainer = new MultiColumnHeaderColumnSortIndicator()); m_ContentContainer = new VisualElement(); m_ContentContainer.style.flexGrow = 1; m_ContentContainer.style.flexShrink = 1; m_ContentContainer.AddToClassList(contentContainerUssClassName); Add(m_ContentContainer); UpdateHeaderTemplate(); UpdateGeometryFromColumn(); InitManipulators(); } void InitManipulators() { this.AddManipulator(mover = new ColumnMover()); mover.movingChanged += (mv) => { if (mover.moving) AddToClassList(movingUssClassName); else RemoveFromClassList(movingUssClassName); }; this.AddManipulator(clickable = new Clickable((Action)null)); clickable.activators.Add(new ManipulatorActivationFilter { button = MouseButton.LeftMouse, modifiers = EventModifiers.Shift }); EventModifiers multiSortingModifier = EventModifiers.Control; if (Application.platform is RuntimePlatform.OSXEditor or RuntimePlatform.OSXPlayer) { multiSortingModifier = EventModifiers.Command; } clickable.activators.Add(new ManipulatorActivationFilter { button = MouseButton.LeftMouse, modifiers = multiSortingModifier }); } void UpdateDataFromColumn() { name = column.name; UnbindHeaderContent(); BindHeaderContent(); } void BindHeaderContent() { if (!isContentBound) { var bindCallback = content.GetProperty(s_BindingCallbackVEPropertyName) as Action<VisualElement>; bindCallback?.Invoke(content); isContentBound = true; } } void UnbindHeaderContent() { if (isContentBound) { var unbindCallback = content.GetProperty(s_UnbindingCallbackVEPropertyName) as Action<VisualElement>; unbindCallback?.Invoke(content); isContentBound = false; } } void DestroyHeaderContent() { // Unbind if bound before destroying UnbindHeaderContent(); var destroyCallback = content.GetProperty(s_DestroyCallbackVEPropertyName) as Action<VisualElement>; destroyCallback?.Invoke(content); } VisualElement CreateDefaultHeaderContent() { var defContent = new VisualElement() { pickingMode = PickingMode.Ignore }; defContent.AddToClassList(defaultContentUssClassName); var icon = new MultiColumnHeaderColumnIcon() { name = iconElementName, pickingMode = PickingMode.Ignore }; var title = new Label() { name = titleElementName, pickingMode = PickingMode.Ignore }; title.AddToClassList(titleUssClassName); defContent.Add(icon); defContent.Add(title); return defContent; } void DefaultBindHeaderContent(VisualElement ve) { var title = ve.Q<Label>(titleElementName); var icon = ve.Q<MultiColumnHeaderColumnIcon>(); ve.RemoveFromClassList(hasTitleUssClassName); if (title != null) title.text = column.title; if (!string.IsNullOrEmpty(column.title)) ve.AddToClassList(hasTitleUssClassName); if (icon != null) { if (column.icon.texture != null || column.icon.sprite != null || column.icon.vectorImage != null) { icon.isImageInline = true; icon.image = column.icon.texture; icon.sprite = column.icon.sprite; icon.vectorImage = column.icon.vectorImage; } else { if (icon.isImageInline) { icon.image = null; icon.sprite = null; icon.vectorImage = null; } } icon.UpdateClassList(); } } void UpdateHeaderTemplate() { Func<VisualElement> makeContentCallback = column.makeHeader; Action<VisualElement> bindContentCallback = column.bindHeader; Action<VisualElement> unbindContentCallback = column.unbindHeader; Action<VisualElement> destroyCallback = column.destroyHeader; if (makeContentCallback == null) { makeContentCallback = CreateDefaultHeaderContent; bindContentCallback = DefaultBindHeaderContent; unbindContentCallback = null; destroyCallback = null; } content = makeContentCallback(); content.SetProperty(s_BindingCallbackVEPropertyName, bindContentCallback); content.SetProperty(s_UnbindingCallbackVEPropertyName, unbindContentCallback); content.SetProperty(s_DestroyCallbackVEPropertyName, destroyCallback); isContentBound = false; m_ScheduledHeaderTemplateUpdate = null; UpdateDataFromColumn(); } void UpdateGeometryFromColumn() { if (float.IsNaN(column.desiredWidth)) return; style.width = column.desiredWidth; } } }
UnityCsReference/Modules/UIElements/Core/Controls/MultiColumn/MultiColumnHeaderColumn.cs/0
{ "file_path": "UnityCsReference/Modules/UIElements/Core/Controls/MultiColumn/MultiColumnHeaderColumn.cs", "repo_id": "UnityCsReference", "token_count": 5758 }
489
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using Unity.Properties; using UnityEngine.Bindings; namespace UnityEngine.UIElements { /// <summary> /// Creates a tab to organize content on different screens. /// </summary> /// <remarks> /// A Tab has a header that can respond to pointer and mouse events. The header can hold an icon, a label, or both. /// The Tab content container can hold anything inside of it giving more flexibility to customize its layout. /// /// For more information, refer to [[wiki:UIE-uxml-element-tab|UXML element Tab]]. /// </remarks> public class Tab : VisualElement { internal static readonly BindingId labelProperty = nameof(label); internal static readonly BindingId iconImageProperty = nameof(iconImage); internal static readonly BindingId closeableProperty = nameof(closeable); [UnityEngine.Internal.ExcludeFromDocs, Serializable] public new class UxmlSerializedData : VisualElement.UxmlSerializedData { #pragma warning disable 649 [SerializeField, MultilineTextField] string label; [SerializeField, UxmlIgnore, HideInInspector] UxmlAttributeFlags label_UxmlAttributeFlags; [ImageFieldValueDecorator] [SerializeField, UxmlAttribute("icon-image")] Object iconImageReference; [SerializeField, UxmlIgnore, HideInInspector] UxmlAttributeFlags iconImageReference_UxmlAttributeFlags; [SerializeField] bool closeable; [SerializeField, UxmlIgnore, HideInInspector] UxmlAttributeFlags closeable_UxmlAttributeFlags; #pragma warning restore 649 public override object CreateInstance() => new Tab(); public override void Deserialize(object obj) { base.Deserialize(obj); var e = (Tab) obj; if (ShouldWriteAttributeValue(label_UxmlAttributeFlags)) e.label = label; if (ShouldWriteAttributeValue(iconImageReference_UxmlAttributeFlags)) e.iconImageReference = iconImageReference; if (ShouldWriteAttributeValue(closeable_UxmlAttributeFlags)) e.closeable = closeable; } } /// <summary> /// Instantiates an <see cref="Tab"/> 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<Tab, UxmlTraits> {} /// <summary> /// Defines <see cref="UxmlTraits"/> for the <see cref="Tab"/>. /// </summary> /// <remarks> /// This class defines the properties of a Tab element that you can use in a UXML file. /// </remarks> [Obsolete("UxmlTraits is deprecated and will be removed. Use UxmlElementAttribute instead.", false)] public new class UxmlTraits : VisualElement.UxmlTraits { private readonly UxmlStringAttributeDescription m_Label = new() { name = "label" }; private readonly UxmlImageAttributeDescription m_IconImage = new() { name = "icon-image" }; private readonly UxmlBoolAttributeDescription m_Closeable = new () { name = "closeable", defaultValue = false }; public override void Init(VisualElement ve, IUxmlAttributes bag, CreationContext cc) { base.Init(ve, bag, cc); var tab = (Tab)ve; tab.label = m_Label.GetValueFromBag(bag, cc); tab.iconImage = m_IconImage.GetValueFromBag(bag, cc); tab.closeable = m_Closeable.GetValueFromBag(bag, cc); } } /// <summary> /// USS class name of elements of this type. /// </summary> public static readonly string ussClassName = "unity-tab"; /// <summary> /// USS class name for the header of this type. /// </summary> public static readonly string tabHeaderUssClassName = ussClassName + "__header"; /// <summary> /// USS class name for the icon inside the header. /// </summary> public static readonly string tabHeaderImageUssClassName = tabHeaderUssClassName + "-image"; /// <summary> /// USS class name for the icon inside the header when the value is null. /// </summary> public static readonly string tabHeaderEmptyImageUssClassName = tabHeaderImageUssClassName + "--empty"; /// <summary> /// USS class name for the icon inside the header when the label is empty or null. /// </summary> public static readonly string tabHeaderStandaloneImageUssClassName = tabHeaderImageUssClassName + "--standalone"; /// <summary> /// USS class name for the label of the header. /// </summary> public static readonly string tabHeaderLabelUssClassName = tabHeaderUssClassName + "-label"; /// <summary> /// USS class name for the label of the header when the value is empty or null. /// </summary> public static readonly string tabHeaderEmptyLabeUssClassName = tabHeaderLabelUssClassName + "--empty"; /// <summary> /// USS class name for the active state underline of the header. /// </summary> public static readonly string tabHeaderUnderlineUssClassName = tabHeaderUssClassName + "-underline"; /// <summary> /// USS class name of container element of this type. /// </summary> public static readonly string contentUssClassName = ussClassName + "__content-container"; /// <summary> /// USS class name for the dragging state of this type. /// </summary> public static readonly string draggingUssClassName = ussClassName + "--dragging"; /// <summary> /// USS class name for reorderable tab elements. /// </summary> public static readonly string reorderableUssClassName = ussClassName + "__reorderable"; /// <summary> /// USS class name for drag handle in reorderable tabs. /// </summary> public static readonly string reorderableItemHandleUssClassName = reorderableUssClassName + "-handle"; /// <summary> /// USS class name for drag handlebar in reorderable tabs. /// </summary> public static readonly string reorderableItemHandleBarUssClassName = reorderableItemHandleUssClassName + "-bar"; /// <summary> /// The USS class name for a closeable tab. /// </summary> public static readonly string closeableUssClassName = tabHeaderUssClassName + "__closeable"; /// <summary> /// The USS class name for close button in closable tabs. /// </summary> public static readonly string closeButtonUssClassName = ussClassName + "__close-button"; /// <summary> /// This event is called when a tab has been selected. /// </summary> public event Action<Tab> selected; /// <summary> /// This event is called before a tab is closed. Return true if the tab can be closed. /// </summary> /// <remarks> /// In the case where more than one events are assigned, all of them will be executed synchronously but only the /// last value will be taken into account. /// </remarks> public event Func<bool> closing; /// <summary> /// This event is called when a tab has been closed. /// </summary> public event Action<Tab> closed; // Used privately to help the serializer convert the Unity Object to the appropriate asset type. Object iconImageReference { get => iconImage.GetSelectedImage(); set => iconImage = Background.FromObject(value); } string m_Label; Background m_IconImage; bool m_Closeable; VisualElement m_ContentContainer; VisualElement m_DragHandle; VisualElement m_CloseButton; VisualElement m_TabHeader; Image m_TabHeaderImage; Label m_TabHeaderLabel; // Needed by the UIBuilder for authoring in the viewport internal Label headerLabel { [VisibleToOtherModules("UnityEditor.UIBuilderModule")] get => m_TabHeaderLabel; } /// <summary> /// Returns the Tab's header. /// </summary> public VisualElement tabHeader => m_TabHeader; // Returns the reorder manipulator. internal TabDragger dragger { get; } /// <summary> /// Sets the label of the Tab's header. /// </summary> [CreateProperty] public string label { get => m_Label; set { if (string.CompareOrdinal(value, m_Label) == 0) return; m_TabHeaderLabel.text = value; m_TabHeaderLabel.EnableInClassList(tabHeaderEmptyLabeUssClassName, string.IsNullOrEmpty(value)); // Removes the margin using this class. This is until we have better support for targeting siblings in // USS or additional pseudo support like :not(). m_TabHeaderImage.EnableInClassList(tabHeaderStandaloneImageUssClassName, string.IsNullOrEmpty(value)); m_Label = value; NotifyPropertyChanged(labelProperty); } } /// <summary> /// Sets the icon for the Tab's header. /// </summary> [CreateProperty] public Background iconImage { get => m_IconImage; set { if (value == m_IconImage) return; if (value.IsEmpty()) { m_TabHeaderImage.image = null; m_TabHeaderImage.sprite = null; m_TabHeaderImage.vectorImage = null; m_TabHeaderImage.AddToClassList(tabHeaderEmptyImageUssClassName); m_TabHeaderImage.RemoveFromClassList(tabHeaderStandaloneImageUssClassName); m_IconImage = value; NotifyPropertyChanged(iconImageProperty); return; } // The image control will reset the other values to null if (value.texture) m_TabHeaderImage.image = value.texture; else if (value.sprite) m_TabHeaderImage.sprite = value.sprite; else if (value.renderTexture) m_TabHeaderImage.image = value.renderTexture; else m_TabHeaderImage.vectorImage = value.vectorImage; m_TabHeaderImage.RemoveFromClassList(tabHeaderEmptyImageUssClassName); m_TabHeaderImage.EnableInClassList(tabHeaderStandaloneImageUssClassName, string.IsNullOrEmpty(m_Label)); m_IconImage = value; NotifyPropertyChanged(iconImageProperty); } } /// <summary> /// A property that adds the ability to close tabs. /// </summary> /// <remarks> /// The default value is <c>false</c>. /// Set this value to <c>true</c> to allow the user to close tabs in the tab view. /// </remarks> [CreateProperty] public bool closeable { get => m_Closeable; set { if (m_Closeable == value) return; m_Closeable = value; m_TabHeader.EnableInClassList(closeableUssClassName, value); EnableTabCloseButton(value); NotifyPropertyChanged(closeableProperty); } } /// <summary> /// The container for the content of the <see cref="Tab"/>. /// </summary> public override VisualElement contentContainer => m_ContentContainer; /// <summary> /// Constructs a Tab. /// </summary> public Tab() : this(null, null) {} /// <summary> /// Constructs a Tab. /// </summary> /// <param name="label">The text to use as the header label.</param> public Tab(string label) : this(label, null) {} /// <summary> /// Constructs a Tab. /// </summary> /// <param name="iconImage">The icon used as the header icon.</param> public Tab(Background iconImage) : this(null, iconImage) {} /// <summary> /// Constructs a Tab. /// </summary> /// <param name="label">The text to use as the header label.</param> /// <param name="iconImage">The icon used as the header icon.</param> public Tab(string label, Background iconImage) { AddToClassList(ussClassName); m_TabHeader = new VisualElement() { classList = { tabHeaderUssClassName }, name = tabHeaderUssClassName }; // Create Draggable handles for reorderable mode m_DragHandle = new VisualElement { name = reorderableItemHandleUssClassName, classList = { reorderableItemHandleUssClassName } }; m_DragHandle.AddToClassList(reorderableItemHandleUssClassName); m_DragHandle.Add(new VisualElement { name = reorderableItemHandleBarUssClassName, classList = { reorderableItemHandleBarUssClassName, $"{reorderableItemHandleBarUssClassName}--left" } }); m_DragHandle.Add(new VisualElement { name = reorderableItemHandleBarUssClassName, classList = { reorderableItemHandleBarUssClassName } }); // Creates the Image control that will hold the Tab's icon if applicable. m_TabHeaderImage = new Image() { name = tabHeaderImageUssClassName, classList = { tabHeaderImageUssClassName, tabHeaderEmptyImageUssClassName } }; m_TabHeader.Add(m_TabHeaderImage); m_TabHeaderLabel = new Label() { name = tabHeaderLabelUssClassName, classList = { tabHeaderLabelUssClassName } }; m_TabHeader.Add(m_TabHeaderLabel); m_TabHeader.RegisterCallback<PointerDownEvent>(OnTabClicked); // Add the Tab's underline for active tab m_TabHeader.Add(new VisualElement() { name = tabHeaderUnderlineUssClassName, classList = { tabHeaderUnderlineUssClassName } }); // Create close button for closable mode m_CloseButton = new VisualElement { name = closeButtonUssClassName, classList = { closeButtonUssClassName } }; m_CloseButton.RegisterCallback<PointerDownEvent>(OnCloseButtonClicked); hierarchy.Add(m_TabHeader); m_ContentContainer = new VisualElement() { name = contentUssClassName, classList = { contentUssClassName }, userData = m_TabHeader }; hierarchy.Add(m_ContentContainer); this.label = label; this.iconImage = iconImage; m_DragHandle.AddManipulator(dragger = new TabDragger()); // Take over and repurpose the default VisualElement tooltip behaviour for the TabHeader. m_TabHeader.RegisterCallback<TooltipEvent>(UpdateTooltip); // Stop the default tooltip behaviour for Tab otherwise the content will take the tooltip's value over the // content's tooltip value RegisterCallback<TooltipEvent>((evt) => evt.StopImmediatePropagation()); } // We want the tooltip to be displayed on the header level and not in the content-container. void UpdateTooltip(TooltipEvent evt) { if (evt.currentTarget is VisualElement element && !string.IsNullOrEmpty(tooltip)) { evt.rect = element.GetTooltipRect(); evt.tooltip = tooltip; evt.StopImmediatePropagation(); } } void AddDragHandles() { m_TabHeader.Insert(0, m_DragHandle); } void RemoveDragHandles() { if (m_TabHeader.Contains(m_DragHandle)) { m_TabHeader.Remove(m_DragHandle); } } internal void EnableTabDragHandles(bool enable) { if (enable) AddDragHandles(); else RemoveDragHandles(); } void AddCloseButton() { m_TabHeader.Add(m_CloseButton); } void RemoveCloseButton() { if (m_TabHeader.Contains(m_CloseButton)) { m_TabHeader.Remove(m_CloseButton); } } internal void EnableTabCloseButton(bool enable) { if (enable) AddCloseButton(); else RemoveCloseButton(); } /// <summary> /// Sets the tab header's pseudo state to checked. /// </summary> internal void SetActive() { m_TabHeader.pseudoStates |= PseudoStates.Checked; pseudoStates |= PseudoStates.Checked; } /// <summary> /// Resets the tab header's pseudo state to its original state. /// </summary> internal void SetInactive() { m_TabHeader.pseudoStates &= ~PseudoStates.Checked; pseudoStates &= ~PseudoStates.Checked; } void OnTabClicked(PointerDownEvent _) { selected?.Invoke(this); } void OnCloseButtonClicked(PointerDownEvent evt) { var canClose = closing?.Invoke() ?? true; if (canClose) { RemoveFromHierarchy(); closed?.Invoke(this); } evt.StopPropagation(); } } }
UnityCsReference/Modules/UIElements/Core/Controls/Tab.cs/0
{ "file_path": "UnityCsReference/Modules/UIElements/Core/Controls/Tab.cs", "repo_id": "UnityCsReference", "token_count": 8210 }
490
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; namespace UnityEngine.UIElements { unsafe struct CountingBloomFilter { private const int KEY_SIZE = 14; private const uint ARRAY_SIZE = 1 << KEY_SIZE; private const int KEY_MASK = (1 << KEY_SIZE) - 1; private fixed byte m_Counters[(int)ARRAY_SIZE]; private void AdjustSlot(uint index, bool increment) { if (increment) { if (m_Counters[index] != 0xff) // once a slot is full, it can't be increased anymore m_Counters[index]++; } else { if (m_Counters[index] != 0x00) // once a slot is empty, it can't be decreased anymore m_Counters[index]--; } } private uint Hash1(uint hash) { return hash & KEY_MASK; } private uint Hash2(uint hash) { return (hash >> KEY_SIZE) & KEY_MASK; } private bool IsSlotEmpty(uint index) { return m_Counters[index] == 0; } public void InsertHash(uint hash) { AdjustSlot(Hash1(hash), true); AdjustSlot(Hash2(hash), true); } public void RemoveHash(uint hash) { AdjustSlot(Hash1(hash), false); AdjustSlot(Hash2(hash), false); } public bool ContainsHash(uint hash) { return !IsSlotEmpty(Hash1(hash)) && !IsSlotEmpty(Hash2(hash)); } } class AncestorFilter { CountingBloomFilter m_CountingBloomFilter; Stack<int> m_HashStack = new Stack<int>(100); public AncestorFilter() {} private void AddHash(int hash) { m_HashStack.Push(hash); m_CountingBloomFilter.InsertHash((uint)hash); } unsafe public bool IsCandidate(StyleComplexSelector complexSel) { // We traverse the hash values for the complex selector parts to detect if any part isn't found // in the Bloom filter, in which case the selector is not a candidate for the exhaustive search. // Also, if a value of 0 is found during the search, then all parts have been visited without a // Bloom filter rejection, in which case we must proceed with the exhaustive search. for (int i = 0; i < Hashes.kSize; i++) { // A default part hash value means that all parts have been visited without a Bloom filter rejection. if (complexSel.ancestorHashes.hashes[i] == 0) return true; // A negative search in the Bloom filter means that the exhaustive search can be skipped for this selector. if (!m_CountingBloomFilter.ContainsHash((uint)complexSel.ancestorHashes.hashes[i])) return false; } return true; } public void PushElement(VisualElement element) { int rememberCount = m_HashStack.Count; AddHash(element.typeName.GetHashCode() * (int)Salt.TagNameSalt); if (!string.IsNullOrEmpty(element.name)) AddHash(element.name.GetHashCode() * (int)Salt.IdSalt); foreach (string cls in element.classList) { AddHash(cls.GetHashCode() * (int)Salt.ClassSalt); } m_HashStack.Push(m_HashStack.Count - rememberCount); } public void PopElement() { int elemCount = m_HashStack.Peek(); m_HashStack.Pop(); while (elemCount > 0) { int hash = m_HashStack.Peek(); m_CountingBloomFilter.RemoveHash((uint)hash); m_HashStack.Pop(); elemCount--; } } } }
UnityCsReference/Modules/UIElements/Core/CountingBloomFilter.cs/0
{ "file_path": "UnityCsReference/Modules/UIElements/Core/CountingBloomFilter.cs", "repo_id": "UnityCsReference", "token_count": 1917 }
491
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using UnityEngine.UIElements.Experimental; namespace UnityEngine.UIElements { internal class ListViewDraggerAnimated : ListViewDragger { int m_DragStartIndex; int m_CurrentIndex; float m_SelectionHeight; float m_LocalOffsetOnStart; Vector3 m_CurrentPointerPosition; ReusableCollectionItem m_Item; ReusableCollectionItem m_OffsetItem; public bool isDragging { get; private set; } public ReusableCollectionItem draggedItem => m_Item; protected override bool supportsDragEvents => false; public ListViewDraggerAnimated(BaseVerticalCollectionView listView) : base(listView) {} protected internal override StartDragArgs StartDrag(Vector3 pointerPosition) { targetView.ClearSelection(); var recycledItem = GetRecycledItem(pointerPosition); if (recycledItem == null) { return new StartDragArgs(string.Empty, DragVisualMode.Rejected); } targetView.SetSelection(recycledItem.index); isDragging = true; m_Item = recycledItem; targetView.virtualizationController.StartDragItem(m_Item); var y = m_Item.rootElement.layout.y; m_SelectionHeight = m_Item.rootElement.layout.height; m_Item.rootElement.style.position = Position.Absolute; m_Item.rootElement.style.height = m_Item.rootElement.layout.height; m_Item.rootElement.style.width = m_Item.rootElement.layout.width; m_Item.rootElement.style.top = y; m_DragStartIndex = m_Item.index; m_CurrentIndex = m_DragStartIndex; m_CurrentPointerPosition = pointerPosition; m_LocalOffsetOnStart = targetScrollView.contentContainer.WorldToLocal(pointerPosition).y - y; var item = targetView.GetRecycledItemFromIndex(m_CurrentIndex + 1); if (item != null) { m_OffsetItem = item; // We must set the animator even if we set the values directly afterwards, so that it is treated the same way in other callbacks. Animate(m_OffsetItem, m_SelectionHeight); m_OffsetItem.rootElement.style.paddingTop = m_SelectionHeight; if (targetView.virtualizationMethod == CollectionVirtualizationMethod.FixedHeight) m_OffsetItem.rootElement.style.height = targetView.fixedItemHeight + m_SelectionHeight; } return dragAndDropController.SetupDragAndDrop(new[] { m_Item.index }, true); } protected internal override void UpdateDrag(Vector3 pointerPosition) { if (m_Item == null) return; HandleDragAndScroll(pointerPosition); m_CurrentPointerPosition = pointerPosition; var positionInContainer = targetScrollView.contentContainer.WorldToLocal(m_CurrentPointerPosition); var itemLayout = m_Item.rootElement.layout; var contentHeight = targetScrollView.contentContainer.layout.height; itemLayout.y = Mathf.Clamp(positionInContainer.y - m_LocalOffsetOnStart, 0, contentHeight - m_SelectionHeight); var y = targetScrollView.contentContainer.resolvedStyle.paddingTop; m_CurrentIndex = -1; foreach (var item in targetView.activeItems) { if (item.index < 0 || (item.rootElement.style.display == DisplayStyle.None && !item.isDragGhost)) continue; if (item.index == m_Item.index && item.index < targetView.itemsSource.Count - 1) { var nextExpectedHeight = targetView.virtualizationController.GetExpectedItemHeight(item.index + 1); if (itemLayout.y <= y + nextExpectedHeight * 0.5f) { m_CurrentIndex = item.index; } continue; } var expectedHeight = targetView.virtualizationController.GetExpectedItemHeight(item.index); if (itemLayout.y <= y + expectedHeight * 0.5f) { if (m_CurrentIndex == -1) m_CurrentIndex = item.index; if (m_OffsetItem == item) break; Animate(m_OffsetItem, 0); Animate(item, m_SelectionHeight); m_OffsetItem = item; break; } y += expectedHeight; } if (m_CurrentIndex == -1) { m_CurrentIndex = targetView.itemsSource.Count; Animate(m_OffsetItem, 0); m_OffsetItem = null; } m_Item.rootElement.layout = itemLayout; m_Item.rootElement.BringToFront(); } void Animate(ReusableCollectionItem element, float paddingTop) { if (element == null) return; if (element.animator != null) { if ((element.animator.isRunning && element.animator.to.paddingTop == paddingTop) || (!element.animator.isRunning && element.rootElement.style.paddingTop == paddingTop)) return; } element.animator?.Stop(); element.animator?.Recycle(); var targetStyle = targetView.virtualizationMethod == CollectionVirtualizationMethod.FixedHeight ? new StyleValues { paddingTop = paddingTop, height = targetView.ResolveItemHeight() + paddingTop } : new StyleValues { paddingTop = paddingTop }; element.animator = element.rootElement.experimental.animation.Start(targetStyle, 500); element.animator.KeepAlive(); } protected internal override void OnDrop(Vector3 pointerPosition) { if (m_Item == null) return; // Stop dragging first, to allow the list to refresh properly dragged items. isDragging = false; m_Item.rootElement.ClearManualLayout(); targetView.virtualizationController.EndDrag(m_CurrentIndex); if (m_OffsetItem != null) { m_OffsetItem.animator?.Stop(); m_OffsetItem.animator?.Recycle(); m_OffsetItem.animator = null; m_OffsetItem.rootElement.style.paddingTop = 0; if (targetView.virtualizationMethod == CollectionVirtualizationMethod.FixedHeight) m_OffsetItem.rootElement.style.height = targetView.ResolveItemHeight(); } var dragPosition = new DragPosition { recycledItem = m_Item, insertAtIndex = m_CurrentIndex, dropPosition = DragAndDropPosition.BetweenItems }; var args = MakeDragAndDropArgs(dragPosition); dragAndDropController.OnDrop(args); dragAndDrop.AcceptDrag(); m_Item = null; m_OffsetItem = null; } protected override void ClearDragAndDropUI(bool dragCancelled) { // Nothing to clear. } protected override bool TryGetDragPosition(Vector2 pointerPosition, ref DragPosition dragPosition) { dragPosition.recycledItem = m_Item; dragPosition.insertAtIndex = m_CurrentIndex; dragPosition.dropPosition = DragAndDropPosition.BetweenItems; return true; } } }
UnityCsReference/Modules/UIElements/Core/DragAndDrop/ListViewDraggerAnimated.cs/0
{ "file_path": "UnityCsReference/Modules/UIElements/Core/DragAndDrop/ListViewDraggerAnimated.cs", "repo_id": "UnityCsReference", "token_count": 3580 }
492
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; namespace UnityEngine.UIElements.Experimental { struct EventDebuggerLogCall : IDisposable { private readonly Delegate m_Callback; private readonly EventBase m_Event; private readonly long m_Start; private readonly bool m_IsPropagationStopped; private readonly bool m_IsImmediatePropagationStopped; public EventDebuggerLogCall(Delegate callback, EventBase evt) { m_Callback = callback; m_Event = evt; m_Start = (long)(Time.realtimeSinceStartup * 1000.0f); m_IsPropagationStopped = evt.isPropagationStopped; m_IsImmediatePropagationStopped = evt.isImmediatePropagationStopped; } public void Dispose() { if (m_Event != null && m_Event.log) { IPanel panel = m_Event.elementTarget?.panel; IEventHandler capture = panel?.GetCapturingElement(PointerId.mousePointerId); m_Event.eventLogger.LogCall(GetCallbackHashCode(), GetCallbackName(), m_Event, m_IsPropagationStopped != m_Event.isPropagationStopped, m_IsImmediatePropagationStopped != m_Event.isImmediatePropagationStopped, (long)(Time.realtimeSinceStartup * 1000.0f) - m_Start, capture); } } private string GetCallbackName() { if (m_Callback == null) { return "No callback"; } if (m_Callback.Target != null) { return m_Callback.Target.GetType().FullName + "." + m_Callback.Method.Name; } if (m_Callback.Method.DeclaringType != null) { return m_Callback.Method.DeclaringType.FullName + "." + m_Callback.Method.Name; } return m_Callback.Method.Name; } private int GetCallbackHashCode() { return m_Callback?.GetHashCode() ?? 0; } } struct EventDebuggerLogIMGUICall : IDisposable { private readonly EventBase m_Event; private readonly long m_Start; public EventDebuggerLogIMGUICall(EventBase evt) { m_Event = evt; m_Start = (long)(Time.realtimeSinceStartup * 1000.0f); } public void Dispose() { if (m_Event != null && m_Event.log) { IPanel panel = m_Event.elementTarget?.panel; IEventHandler capture = panel?.GetCapturingElement(PointerId.mousePointerId); m_Event.eventLogger.LogIMGUICall(m_Event, (long)(Time.realtimeSinceStartup * 1000.0f) - m_Start, capture); } } } struct EventDebuggerLogExecuteDefaultAction : IDisposable { private readonly EventBase m_Event; private readonly long m_Start; public EventDebuggerLogExecuteDefaultAction(EventBase evt) { m_Event = evt; m_Start = (long)(Time.realtimeSinceStartup * 1000.0f); } public void Dispose() { if (m_Event != null && m_Event.log) { IPanel panel = m_Event.elementTarget?.panel; IEventHandler capture = panel?.GetCapturingElement(PointerId.mousePointerId); m_Event.eventLogger.LogExecuteDefaultAction(m_Event, m_Event.propagationPhase, (long)(Time.realtimeSinceStartup * 1000.0f) - m_Start, capture); } } } class EventDebugger { public IPanel panel { get { return panelDebug?.panel; } set { /* Ignore in editor */ } } IPanelDebug m_PanelDebug; public IPanelDebug panelDebug { get { return m_PanelDebug; } set { m_PanelDebug = value; if (m_PanelDebug != null) { if (!m_EventTypeProcessedCount.ContainsKey(panel)) m_EventTypeProcessedCount.Add(panel, new Dictionary<long, int>()); } } } public bool isReplaying { get; private set; } public float playbackSpeed { get; set; } = 1.0f; public bool isPlaybackPaused { get; set; } public void UpdateModificationCount() { if (panel == null) return; if (!m_ModificationCount.TryGetValue(panel, out var count)) { count = 0; } count++; m_ModificationCount[panel] = count; } public void BeginProcessEvent(EventBase evt, IEventHandler mouseCapture) { AddBeginProcessEvent(evt, mouseCapture); UpdateModificationCount(); } public void EndProcessEvent(EventBase evt, long duration, IEventHandler mouseCapture) { AddEndProcessEvent(evt, duration, mouseCapture); UpdateModificationCount(); } public void LogCall(int cbHashCode, string cbName, EventBase evt, bool propagationHasStopped, bool immediatePropagationHasStopped, long duration, IEventHandler mouseCapture) { AddCallObject(cbHashCode, cbName, evt, propagationHasStopped, immediatePropagationHasStopped, duration, mouseCapture); UpdateModificationCount(); } public void LogIMGUICall(EventBase evt, long duration, IEventHandler mouseCapture) { AddIMGUICall(evt, duration, mouseCapture); UpdateModificationCount(); } public void LogExecuteDefaultAction(EventBase evt, PropagationPhase phase, long duration, IEventHandler mouseCapture) { AddExecuteDefaultAction(evt, phase, duration, mouseCapture); UpdateModificationCount(); } public static void LogPropagationPaths(EventBase evt, PropagationPaths paths) { if (evt.log) { evt.eventLogger.LogPropagationPathsInternal(evt, paths); } } void LogPropagationPathsInternal(EventBase evt, PropagationPaths paths) { AddPropagationPaths(evt, paths); UpdateModificationCount(); } public List<EventDebuggerCallTrace> GetCalls(IPanel panel, EventDebuggerEventRecord evt = null) { if (!m_EventCalledObjects.TryGetValue(panel, out var list)) { return null; } if ((evt != null) && (list != null)) { List<EventDebuggerCallTrace> filteredList = new List<EventDebuggerCallTrace>(); foreach (var callObject in list) { if (callObject.eventBase.eventId == evt.eventId) { filteredList.Add(callObject); } } list = filteredList; } return list; } public List<EventDebuggerDefaultActionTrace> GetDefaultActions(IPanel panel, EventDebuggerEventRecord evt = null) { if (!m_EventDefaultActionObjects.TryGetValue(panel, out var list)) { return null; } if ((evt != null) && (list != null)) { List<EventDebuggerDefaultActionTrace> filteredList = new List<EventDebuggerDefaultActionTrace>(); foreach (var defaultActionObject in list) { if (defaultActionObject.eventBase.eventId == evt.eventId) { filteredList.Add(defaultActionObject); } } list = filteredList; } return list; } public List<EventDebuggerPathTrace> GetPropagationPaths(IPanel panel, EventDebuggerEventRecord evt = null) { if (!m_EventPathObjects.TryGetValue(panel, out var list)) { return null; } if ((evt != null) && (list != null)) { List<EventDebuggerPathTrace> filteredList = new List<EventDebuggerPathTrace>(); foreach (var pathObject in list) { if (pathObject.eventBase.eventId == evt.eventId) { filteredList.Add(pathObject); } } list = filteredList; } return list; } public List<EventDebuggerTrace> GetBeginEndProcessedEvents(IPanel panel, EventDebuggerEventRecord evt = null) { if (!m_EventProcessedEvents.TryGetValue(panel, out var list)) { return null; } if ((evt != null) && (list != null)) { List<EventDebuggerTrace> filteredList = new List<EventDebuggerTrace>(); foreach (var defaultActionObject in list) { if (defaultActionObject.eventBase.eventId == evt.eventId) { filteredList.Add(defaultActionObject); } } list = filteredList; } return list; } public long GetModificationCount(IPanel panel) { if (panel == null) return -1; if (!m_ModificationCount.TryGetValue(panel, out var modificationCount)) { modificationCount = -1; } return modificationCount; } public void ClearLogs() { UpdateModificationCount(); if (panel == null) { m_EventCalledObjects.Clear(); m_EventDefaultActionObjects.Clear(); m_EventPathObjects.Clear(); m_EventProcessedEvents.Clear(); m_StackOfProcessedEvent.Clear(); m_EventTypeProcessedCount.Clear(); return; } m_EventCalledObjects.Remove(panel); m_EventDefaultActionObjects.Remove(panel); m_EventPathObjects.Remove(panel); m_EventProcessedEvents.Remove(panel); m_StackOfProcessedEvent.Remove(panel); if (m_EventTypeProcessedCount.TryGetValue(panel, out var eventTypeProcessedForPanel)) eventTypeProcessedForPanel.Clear(); } public void SaveReplaySessionFromSelection(string path, List<EventDebuggerEventRecord> eventList) { if (string.IsNullOrEmpty(path)) return; var recordSave = new EventDebuggerRecordList() { eventList = eventList }; var json = JsonUtility.ToJson(recordSave); File.WriteAllText(path, json); Debug.Log($"Saved under: {path}"); } public EventDebuggerRecordList LoadReplaySession(string path) { if (string.IsNullOrEmpty(path)) return null; var fileContent = File.ReadAllText(path); return JsonUtility.FromJson<EventDebuggerRecordList>(fileContent); } public IEnumerator ReplayEvents(IEnumerable<EventDebuggerEventRecord> eventBases, Action<int, int> refreshList) { if (eventBases == null) yield break; isReplaying = true; var doReplay = DoReplayEvents(eventBases, refreshList); while (doReplay.MoveNext()) { yield return null; } } public void StopPlayback() { isReplaying = false; isPlaybackPaused = false; } private IEnumerator DoReplayEvents(IEnumerable<EventDebuggerEventRecord> eventBases, Action<int, int> refreshList) { var sortedEvents = eventBases.OrderBy(e => e.timestamp).ToList(); var sortedEventsCount = sortedEvents.Count; IEnumerator AwaitForNextEvent(int currentIndex) { if (currentIndex == sortedEvents.Count - 1) yield break; var deltaTimestampMs = sortedEvents[currentIndex + 1].timestamp - sortedEvents[currentIndex].timestamp; var timeMs = 0.0f; while (timeMs < deltaTimestampMs) { if (isPlaybackPaused) { yield return null; } else { var time = Panel.TimeSinceStartupMs(); yield return null; var delta = Panel.TimeSinceStartupMs() - time; timeMs += delta * playbackSpeed; } } } void SendEvent(EventBase evt) { (panel as BaseVisualElementPanel)?.SendEvent(evt); } for (var i = 0; i < sortedEventsCount; i++) { if (!isReplaying) break; var eventBase = sortedEvents[i]; var newEvent = new Event { button = eventBase.button, clickCount = eventBase.clickCount, modifiers = eventBase.modifiers, mousePosition = eventBase.mousePosition, }; if (eventBase.eventTypeId == MouseMoveEvent.TypeId() && eventBase.hasUnderlyingPhysicalEvent) { newEvent.type = EventType.MouseMove; SendEvent(UIElementsUtility.CreateEvent(newEvent, EventType.MouseMove)); } else if (eventBase.eventTypeId == MouseDownEvent.TypeId() && eventBase.hasUnderlyingPhysicalEvent) { newEvent.type = EventType.MouseDown; SendEvent(UIElementsUtility.CreateEvent(newEvent, EventType.MouseDown)); } else if (eventBase.eventTypeId == MouseUpEvent.TypeId() && eventBase.hasUnderlyingPhysicalEvent) { newEvent.type = EventType.MouseUp; SendEvent(UIElementsUtility.CreateEvent(newEvent, EventType.MouseUp)); } else if (eventBase.eventTypeId == ContextClickEvent.TypeId() && eventBase.hasUnderlyingPhysicalEvent) { newEvent.type = EventType.ContextClick; SendEvent(UIElementsUtility.CreateEvent(newEvent, EventType.ContextClick)); } else if (eventBase.eventTypeId == MouseEnterWindowEvent.TypeId() && eventBase.hasUnderlyingPhysicalEvent) { newEvent.type = EventType.MouseEnterWindow; SendEvent(UIElementsUtility.CreateEvent(newEvent, EventType.MouseEnterWindow)); } else if (eventBase.eventTypeId == MouseLeaveWindowEvent.TypeId() && eventBase.hasUnderlyingPhysicalEvent) { newEvent.type = EventType.MouseLeaveWindow; SendEvent(UIElementsUtility.CreateEvent(newEvent, EventType.MouseLeaveWindow)); } else if (eventBase.eventTypeId == PointerMoveEvent.TypeId() && eventBase.hasUnderlyingPhysicalEvent) { newEvent.type = EventType.MouseMove; SendEvent(UIElementsUtility.CreateEvent(newEvent, EventType.MouseMove)); } else if (eventBase.eventTypeId == PointerDownEvent.TypeId() && eventBase.hasUnderlyingPhysicalEvent) { newEvent.type = EventType.MouseDown; SendEvent(UIElementsUtility.CreateEvent(newEvent, EventType.MouseDown)); } else if (eventBase.eventTypeId == PointerUpEvent.TypeId() && eventBase.hasUnderlyingPhysicalEvent) { newEvent.type = EventType.MouseUp; SendEvent(UIElementsUtility.CreateEvent(newEvent, EventType.MouseUp)); } else if (eventBase.eventTypeId == WheelEvent.TypeId() && eventBase.hasUnderlyingPhysicalEvent) { newEvent.type = EventType.ScrollWheel; newEvent.delta = eventBase.delta; SendEvent(UIElementsUtility.CreateEvent(newEvent, EventType.ScrollWheel)); } else if (eventBase.eventTypeId == KeyDownEvent.TypeId()) { newEvent.type = EventType.KeyDown; newEvent.character = eventBase.character; newEvent.keyCode = eventBase.keyCode; SendEvent(UIElementsUtility.CreateEvent(newEvent, EventType.KeyDown)); } else if (eventBase.eventTypeId == KeyUpEvent.TypeId()) { newEvent.type = EventType.KeyUp; newEvent.character = eventBase.character; newEvent.keyCode = eventBase.keyCode; SendEvent(UIElementsUtility.CreateEvent(newEvent, EventType.KeyUp)); } else if (eventBase.eventTypeId == NavigationMoveEvent.TypeId()) { SendEvent(NavigationMoveEvent.GetPooled(eventBase.navigationDirection, eventBase.deviceType, eventBase.modifiers)); } else if (eventBase.eventTypeId == NavigationSubmitEvent.TypeId()) { SendEvent(NavigationSubmitEvent.GetPooled(eventBase.deviceType, eventBase.modifiers)); } else if (eventBase.eventTypeId == NavigationCancelEvent.TypeId()) { SendEvent(NavigationCancelEvent.GetPooled(eventBase.deviceType, eventBase.modifiers)); } else if (eventBase.eventTypeId == DragUpdatedEvent.TypeId()) { newEvent.type = EventType.DragUpdated; SendEvent(UIElementsUtility.CreateEvent(newEvent, EventType.DragUpdated)); } else if (eventBase.eventTypeId == DragPerformEvent.TypeId()) { newEvent.type = EventType.DragPerform; SendEvent(UIElementsUtility.CreateEvent(newEvent, EventType.DragPerform)); } else if (eventBase.eventTypeId == DragExitedEvent.TypeId()) { newEvent.type = EventType.DragExited; SendEvent(UIElementsUtility.CreateEvent(newEvent, EventType.DragExited)); } else if (eventBase.eventTypeId == ValidateCommandEvent.TypeId()) { newEvent.type = EventType.ValidateCommand; newEvent.commandName = eventBase.commandName; SendEvent(UIElementsUtility.CreateEvent(newEvent, EventType.ValidateCommand)); } else if (eventBase.eventTypeId == ExecuteCommandEvent.TypeId()) { newEvent.type = EventType.ExecuteCommand; newEvent.commandName = eventBase.commandName; SendEvent(UIElementsUtility.CreateEvent(newEvent, EventType.ExecuteCommand)); } else if (eventBase.eventTypeId == IMGUIEvent.TypeId()) { Debug.Log("Skipped IMGUI event (" + eventBase.eventBaseName + "): " + eventBase); var awaitSkipped = AwaitForNextEvent(i); while (awaitSkipped.MoveNext()) yield return null; continue; } else { Debug.Log("Skipped event (" + eventBase.eventBaseName + "): " + eventBase); var awaitSkipped = AwaitForNextEvent(i); while (awaitSkipped.MoveNext()) yield return null; continue; } refreshList?.Invoke(i, sortedEventsCount); Debug.Log($"Replayed event {eventBase.eventId.ToString()} ({eventBase.eventBaseName}): {newEvent}"); var await = AwaitForNextEvent(i); while (await.MoveNext()) yield return null; } isReplaying = false; } internal struct HistogramRecord { public long count; public long duration; } public Dictionary<string, HistogramRecord> ComputeHistogram(List<EventDebuggerEventRecord> eventBases) { if (panel == null || !m_EventProcessedEvents.TryGetValue(panel, out var list)) return null; if (list == null) return null; Dictionary<string, HistogramRecord> histogram = new Dictionary<string, HistogramRecord>(); foreach (var callObject in list) { if (eventBases == null || eventBases.Count == 0 || eventBases.Contains(callObject.eventBase)) { var key = callObject.eventBase.eventBaseName; var totalDuration = callObject.duration; long totalCount = 1; if (histogram.TryGetValue(key, out var currentHistogramRecord)) { totalDuration += currentHistogramRecord.duration; totalCount += currentHistogramRecord.count; } histogram[key] = new HistogramRecord { count = totalCount, duration = totalDuration }; } } return histogram; } // Call Object Dictionary<IPanel, List<EventDebuggerCallTrace>> m_EventCalledObjects; Dictionary<IPanel, List<EventDebuggerDefaultActionTrace>> m_EventDefaultActionObjects; Dictionary<IPanel, List<EventDebuggerPathTrace>> m_EventPathObjects; Dictionary<IPanel, List<EventDebuggerTrace>> m_EventProcessedEvents; Dictionary<IPanel, Stack<EventDebuggerTrace>> m_StackOfProcessedEvent; Dictionary<IPanel, Dictionary<long, int>> m_EventTypeProcessedCount; public Dictionary<long, int> eventTypeProcessedCount => m_EventTypeProcessedCount.TryGetValue(panel, out var eventTypeProcessedCountForPanel) ? eventTypeProcessedCountForPanel : null; readonly Dictionary<IPanel, long> m_ModificationCount; readonly bool m_Log; public bool suspended { get; set; } // Methods public EventDebugger() { m_EventCalledObjects = new Dictionary<IPanel, List<EventDebuggerCallTrace>>(); m_EventDefaultActionObjects = new Dictionary<IPanel, List<EventDebuggerDefaultActionTrace>>(); m_EventPathObjects = new Dictionary<IPanel, List<EventDebuggerPathTrace>>(); m_StackOfProcessedEvent = new Dictionary<IPanel, Stack<EventDebuggerTrace>>(); m_EventProcessedEvents = new Dictionary<IPanel, List<EventDebuggerTrace>>(); m_EventTypeProcessedCount = new Dictionary<IPanel, Dictionary<long, int>>(); m_ModificationCount = new Dictionary<IPanel, long>(); m_Log = true; } void AddCallObject(int cbHashCode, string cbName, EventBase evt, bool propagationHasStopped, bool immediatePropagationHasStopped, long duration, IEventHandler mouseCapture) { if (suspended) return; if (m_Log) { var callObject = new EventDebuggerCallTrace(panel, evt, cbHashCode, cbName, propagationHasStopped, immediatePropagationHasStopped, duration, mouseCapture); if (!m_EventCalledObjects.TryGetValue(panel, out var list)) { list = new List<EventDebuggerCallTrace>(); m_EventCalledObjects.Add(panel, list); } list.Add(callObject); } } void AddExecuteDefaultAction(EventBase evt, PropagationPhase phase, long duration, IEventHandler mouseCapture) { if (suspended) return; if (m_Log) { var defaultActionObject = new EventDebuggerDefaultActionTrace(panel, evt, phase, duration, mouseCapture); if (!m_EventDefaultActionObjects.TryGetValue(panel, out var list)) { list = new List<EventDebuggerDefaultActionTrace>(); m_EventDefaultActionObjects.Add(panel, list); } list.Add(defaultActionObject); } } void AddPropagationPaths(EventBase evt, PropagationPaths paths) { if (suspended) return; if (m_Log) { var pathObject = new EventDebuggerPathTrace(panel, evt, new PropagationPaths(paths)); if (!m_EventPathObjects.TryGetValue(panel, out var list)) { list = new List<EventDebuggerPathTrace>(); m_EventPathObjects.Add(panel, list); } list.Add(pathObject); } } void AddIMGUICall(EventBase evt, long duration, IEventHandler mouseCapture) { if (suspended) return; if (m_Log) { var callObject = new EventDebuggerCallTrace(panel, evt, 0, "OnGUI", false, false, duration, mouseCapture); if (!m_EventCalledObjects.TryGetValue(panel, out var list)) { list = new List<EventDebuggerCallTrace>(); m_EventCalledObjects.Add(panel, list); } list.Add(callObject); } } void AddBeginProcessEvent(EventBase evt, IEventHandler mouseCapture) { if (suspended) return; var dbgObject = new EventDebuggerTrace(panel, evt, -1, mouseCapture); if (!m_StackOfProcessedEvent.TryGetValue(panel, out var stack)) { stack = new Stack<EventDebuggerTrace>(); m_StackOfProcessedEvent.Add(panel, stack); } if (!m_EventProcessedEvents.TryGetValue(panel, out var list)) { list = new List<EventDebuggerTrace>(); m_EventProcessedEvents.Add(panel, list); } list.Add(dbgObject); stack.Push(dbgObject); if (!m_EventTypeProcessedCount.TryGetValue(panel, out var eventTypeProcessedCountForPanel)) return; if (!eventTypeProcessedCountForPanel.TryGetValue(dbgObject.eventBase.eventTypeId, out var count)) count = 0; eventTypeProcessedCountForPanel[dbgObject.eventBase.eventTypeId] = count + 1; } void AddEndProcessEvent(EventBase evt, long duration, IEventHandler mouseCapture) { if (suspended) return; bool evtHandled = false; if (m_StackOfProcessedEvent.TryGetValue(panel, out var stack)) { if (stack.Count > 0) { var dbgObject = stack.Peek(); if (dbgObject.eventBase.eventId == evt.eventId) { stack.Pop(); dbgObject.duration = duration; // Update the target if it was unknown in AddBeginProcessEvent. if (dbgObject.eventBase.target == null) { dbgObject.eventBase.target = evt.target; } evtHandled = true; } } } if (!evtHandled) { var dbgObject = new EventDebuggerTrace(panel, evt, duration, mouseCapture); if (!m_EventProcessedEvents.TryGetValue(panel, out var list)) { list = new List<EventDebuggerTrace>(); m_EventProcessedEvents.Add(panel, list); } list.Add(dbgObject); if (!m_EventTypeProcessedCount.TryGetValue(panel, out var eventTypeProcessedForPanel)) return; if (!eventTypeProcessedForPanel.TryGetValue(dbgObject.eventBase.eventTypeId, out var count)) count = 0; eventTypeProcessedForPanel[dbgObject.eventBase.eventTypeId] = count + 1; } } public static string GetObjectDisplayName(object obj, bool withHashCode = true) { if (obj == null) return String.Empty; var type = obj.GetType(); var objectName = GetTypeDisplayName(type); if (obj is VisualElement) { VisualElement ve = obj as VisualElement; if (!String.IsNullOrEmpty(ve.name)) { objectName += "#" + ve.name; } } if (withHashCode) { objectName += " (" + obj.GetHashCode().ToString("x8") + ")"; } return objectName; } public static string GetTypeDisplayName(Type type) { return type.IsGenericType ? $"{type.Name.TrimEnd('`', '1')}<{type.GetGenericArguments()[0].Name}>" : type.Name; } } }
UnityCsReference/Modules/UIElements/Core/Events/EventDebugger/EventDebugger.cs/0
{ "file_path": "UnityCsReference/Modules/UIElements/Core/Events/EventDebugger/EventDebugger.cs", "repo_id": "UnityCsReference", "token_count": 15368 }
493
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; using JetBrains.Annotations; using Unity.IntegerTime; using UnityEngine.InputForUI; namespace UnityEngine.UIElements { /// <summary> /// A static class that holds pointer type values. /// </summary> /// <remarks> /// These values are used as the values for IPointerEvent.pointerType. /// </remarks> public static class PointerType { /// <summary> /// The pointer type for mouse events. /// </summary> public static readonly string mouse = "mouse"; /// <summary> /// The pointer type for touch events. /// </summary> public static readonly string touch = "touch"; /// <summary> /// The pointer type for pen events. /// </summary> public static readonly string pen = "pen"; /// <summary> /// The pointer type for events created by unknown devices. /// </summary> public static readonly string unknown = ""; internal static string GetPointerType(int pointerId) { if (pointerId == PointerId.mousePointerId) return mouse; else if (pointerId == PointerId.penPointerIdBase) return pen; else return touch; } // A direct manipulation device is a device where the user directly manipulates elements // (like a touch screen), without any cursor acting as an intermediate. internal static bool IsDirectManipulationDevice(string pointerType) { return ReferenceEquals(pointerType, touch) || ReferenceEquals(pointerType, pen); } } /// <summary> /// A static class that holds pointer ID values. /// </summary> /// <remarks> /// These values are used as the values for IPointerEvent.pointerId. /// </remarks> public static class PointerId { /// <summary> /// The maximum number of pointers the implementation supports. /// </summary> public static readonly int maxPointers = 32; /// <summary> /// Represents an invalid pointer ID value. /// </summary> public static readonly int invalidPointerId = -1; /// <summary> /// The mouse pointer ID. /// </summary> public static readonly int mousePointerId = 0; /// <summary> /// The base ID for touch pointers. /// </summary> /// <remarks> /// The pointer ID for a touch event is a number between touchPointerIdBase and touchPointerIdBase + touchPointerCount - 1. /// </remarks> public static readonly int touchPointerIdBase = 1; /// <summary> /// The number of touch pointers the implementation supports. /// </summary> /// <remarks> /// The pointer ID for a touch event is a number between touchPointerIdBase and touchPointerIdBase + touchPointerCount - 1. /// </remarks> public static readonly int touchPointerCount = 20; /// <summary> /// The base ID for pen pointers. /// </summary> /// <remarks> /// The pointer ID for a pen event is a number between penPointerIdBase and penPointerIdBase + penPointerCount - 1. /// </remarks> public static readonly int penPointerIdBase = touchPointerIdBase + touchPointerCount; /// <summary> /// The number of pen pointers the implementation supports. /// </summary> /// <remarks> /// The pointer ID for a pen event is a number between penPointerIdBase and penPointerIdBase + penPointerCount - 1. /// </remarks> public static readonly int penPointerCount = 2; internal static readonly int[] hoveringPointers = { mousePointerId }; } /// <summary> /// This interface describes properties available to pointer events. /// </summary> public interface IPointerEvent { /// <summary> /// Gets the identifier of the pointer that sends the event. /// </summary> /// <remarks> /// If the mouse sends the event, the identifier is set to 0. If a touchscreen device sends the event, the identifier /// is set to the finger ID, which ranges from 1 to the number of touches the device supports. /// </remarks> int pointerId { get; } /// <summary> /// Gets the type of pointer that created the event. /// </summary> /// <remarks> /// This value is taken from the values defined in `PointerType`. /// </remarks> string pointerType { get; } /// <summary> /// Gets a boolean value that indicates whether the pointer is a primary pointer. True means the pointer is a primary /// pointer. False means it isn't. /// </summary> /// <remarks> /// A primary pointer is a pointer that manipulates the mouse cursor. The mouse pointer is always a primary pointer. For touch /// events, the first finger that touches the screen is the primary pointer. Once it is processed, a pointer event from a primary /// pointer generates compatibility mouse events. /// </remarks> bool isPrimary { get; } /// <summary> /// Gets a value that indicates which mouse button was pressed or released (if any) to cause this event: /// 0 is the left button, 1 is the right button, 2 is the middle button. /// A negative value indicates that no mouse button changed state during this event. /// </summary> int button { get; } /// <summary> /// Gets a bitmask that describes the buttons that are currently pressed. /// </summary> /// <remarks> /// Pressing a mouse button sets a bit. Releasing the button clears the bit. The left mouse button sets/clears Bit 0. /// The right mouse button and pen barrel button set/clear Bit 1. The middle mouse button sets/clears Bit 2. /// The pen eraser sets/clears Bit 5. Additional buttons set/clear other bits. /// </remarks> int pressedButtons { get; } /// <summary> /// Gets the pointer position in the Screen or World coordinate system. /// </summary> Vector3 position { get; } /// <summary> /// Gets the pointer position in the current target's coordinate system. /// </summary> Vector3 localPosition { get; } /// <summary> /// Gets the difference between the pointer's position during the previous mouse event and its position during the /// current mouse event. /// </summary> Vector3 deltaPosition { get; } /// <summary> /// Gets the amount of time that has elapsed since the last recorded change in pointer values, in seconds. /// </summary> float deltaTime { get; } /// <summary> /// Gets the number of times the button was pressed. /// </summary> int clickCount { get; } /// <summary> /// Gets the amount of pressure currently applied by a touch. /// </summary> /// <remarks> /// If the device does not report pressure, the value of this property is 1.0f. /// </remarks> float pressure { get; } /// <summary> /// Gets the pressure applied to an additional pressure-sensitive control on the stylus. /// </summary> float tangentialPressure { get; } /// <summary> /// Gets the angle of the stylus relative to the surface, in radians /// </summary> /// <remarks> /// A value of 0 indicates that the stylus is parallel to the surface. A value of pi/2 indicates that it is perpendicular to the surface. /// </remarks> float altitudeAngle { get; } /// <summary> /// Gets the angle of the stylus relative to the x-axis, in radians. /// </summary> /// <remarks> /// A value of 0 indicates that the stylus is pointed along the x-axis of the device. /// </remarks> float azimuthAngle { get; } /// <summary> /// Gets the rotation of the stylus around its axis, in radians. /// </summary> float twist { get; } /// <summary> /// Specifies the angle of the pen relative to the X and Y axis respectively, in radians. /// </summary> Vector2 tilt { get; } /// <summary> /// Specifies the state of the pen. For example, whether the pen is in contact with the screen or tablet, whether the pen is inverted, and whether buttons are pressed. /// On macOS, penStatus will not reflect changes to button mappings. /// </summary> PenStatus penStatus { get; } /// <summary> /// Gets an estimate of the radius of a touch. /// </summary> /// <remarks> /// Add `radiusVariance` to get the maximum touch radius, subtract it to get the minimum touch radius. /// </remarks> Vector2 radius { get; } /// <summary> /// Gets the accuracy of the touch radius. /// </summary> /// <remarks> /// Add this value to the radius to get the maximum touch radius, subtract it to get the minimum touch radius. /// </remarks> Vector2 radiusVariance { get; } /// <summary> /// Gets flags that indicate whether modifier keys (Alt, Ctrl, Shift, Windows/Cmd) are pressed. /// </summary> EventModifiers modifiers { get; } /// <summary> /// Gets a boolean value that indicates whether the Shift key is pressed. True means the Shift key is pressed. /// False means it isn't. /// </summary> bool shiftKey { get; } /// <summary> /// Gets a boolean value that indicates whether the Ctrl key is pressed. True means the Ctrl key is pressed. /// False means it isn't. /// </summary> bool ctrlKey { get; } /// <summary> /// Gets a boolean value that indicates whether the Windows/Cmd key is pressed. True means the Windows/Cmd key /// is pressed. False means it isn't. /// </summary> bool commandKey { get; } /// <summary> /// Gets a boolean value that indicates whether the Alt key is pressed. True means the Alt key is pressed. /// False means it isn't. /// </summary> bool altKey { get; } /// <summary> /// Gets a boolean value that indicates whether the platform-specific action key is pressed. True means the action /// key is pressed. False means it isn't. /// </summary> /// <remarks> /// The platform-specific action key is Cmd on macOS, and Ctrl on all other platforms. /// </remarks> bool actionKey { get; } } internal interface IPointerEventInternal { bool triggeredByOS { get; set; } IMouseEvent compatibilityMouseEvent { get; set; } int displayIndex { get; set; } } internal interface IPointerOrMouseEvent { int pointerId { get; } Vector3 position { get; } } internal static class PointerEventHelper { public static EventBase GetPooled(EventType eventType, Vector3 mousePosition, Vector2 delta, int button, int clickCount, EventModifiers modifiers, int displayIndex) { if (eventType == EventType.MouseDown && !PointerDeviceState.HasAdditionalPressedButtons(PointerId.mousePointerId, button)) return PointerDownEvent.GetPooled(eventType, mousePosition, delta, button, clickCount, modifiers, displayIndex); if (eventType == EventType.MouseUp && !PointerDeviceState.HasAdditionalPressedButtons(PointerId.mousePointerId, button)) return PointerUpEvent.GetPooled(eventType, mousePosition, delta, button, clickCount, modifiers, displayIndex); return PointerMoveEvent.GetPooled(eventType, mousePosition, delta, button, clickCount, modifiers, displayIndex); } } /// <summary> /// This is the base class for pointer events. /// </summary> /// <remarks> /// Pointer events are sent by the mouse, touchscreen, or digital pens. /// /// By default, pointer events trickle down the hierarchy of VisualElements, and then bubble up /// back to the root. /// /// A cycle of pointer events occurs as follows: /// - The user presses a mouse button, touches the screen, or otherwise causes a <see cref="PointerDownEvent"/> to be sent. /// - If the user changes the pointer's state, a <see cref="PointerMoveEvent"/> is sent. Many PointerMove events can be sent. /// - If the user doesn't change the pointer's state for a specific amount of time, a <see cref="PointerStationaryEvent"/> is sent. /// - If the user cancels the loop, a <see cref="PointerCancelEvent"/> is sent. /// - If the user doesn't cancel the loop, and either releases the last button pressed or releases the last touch, a <see cref="PointerUpEvent"/> is sent. /// - If the initial PointerDownEvent and the PointerUpEvent occur on the same VisualElement, a <see cref="ClickEvent"/> is sent. /// /// </remarks> [EventCategory(EventCategory.Pointer)] public abstract class PointerEventBase<T> : EventBase<T>, IPointerEvent, IPointerEventInternal, IPointerOrMouseEvent where T : PointerEventBase<T>, new() { // See HTML spec for pointer pressure: https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/pressure private const float k_DefaultButtonPressure = 0.5f; private bool m_AltitudeNeedsConversion = true; private bool m_AzimuthNeedsConversion = true; private float m_AltitudeAngle = 0f; private float m_AzimuthAngle = 0f; private bool m_TiltNeeded = true; private Vector2 m_Tilt = new Vector2(0, 0); /// <summary> /// Gets the identifier of the pointer that sent the event. /// </summary> /// <remarks> /// If the mouse sends the event, the identifier is set to 0. If a touchscreen device sends the event, the identifier /// is set to the finger ID, which ranges from 1 to the number of touches the device supports. /// </remarks> public int pointerId { get; protected set; } /// <summary> /// Gets the type of pointer that created the event. /// </summary> /// <remarks> /// This value is taken from the values defined in `PointerType`. /// </remarks> public string pointerType { get; protected set; } /// <summary> /// Gets a boolean value that indicates whether the pointer is a primary pointer. True means the pointer is a primary /// pointer. False means it isn't. /// </summary> /// <remarks> /// A primary pointer is a pointer that manipulates the mouse cursor. The mouse pointer is always a primary pointer. For touch /// events, the first finger that touches the screen is the primary pointer. Once it is processed, a pointer event from a primary /// pointer generates compatibility mouse events. /// </remarks> public bool isPrimary { get; protected set; } /// <summary> /// Gets a value that indicates which mouse button was pressed or released (if any) to cause this event: /// 0 is the left button, 1 is the right button, 2 is the middle button. /// A negative value indicates that no mouse button changed state during this event. /// </summary> public int button { get; protected set; } /// <summary> /// Gets a bitmask that describes the buttons that are currently pressed. /// </summary> /// <remarks> /// Pressing a mouse button sets a bit. Releasing the button clears the bit. The left mouse button sets/clears Bit 0. /// The right mouse button sets/clears Bit 1. The middle mouse button sets/clears Bit 2. Additional buttons set/clear /// other bits. /// </remarks> public int pressedButtons { get; protected set; } /// <summary> /// Gets the pointer position in the Screen or World coordinate system. /// </summary> public Vector3 position { get; protected set; } /// <summary> /// Gets the pointer position in the current target's coordinate system. /// </summary> public Vector3 localPosition { get; protected set; } /// <summary> /// Gets the difference between the pointer's position during the previous mouse event and its position during the /// current mouse event. /// </summary> public Vector3 deltaPosition { get; protected set; } /// <summary> /// Gets the amount of time that has elapsed since the last recorded change in pointer values, in seconds. /// </summary> public float deltaTime { get; protected set; } /// <summary> /// Gets the number of times the button was pressed. /// </summary> public int clickCount { get; protected set; } /// <summary> /// Gets the amount of pressure currently applied by a touch. /// </summary> /// <remarks> /// If the device does not report pressure, the value of this property is 1.0f. /// </remarks> public float pressure { get; protected set; } /// <summary> /// Gets the pressure applied to an additional pressure-sensitive control on the stylus. /// </summary> public float tangentialPressure { get; protected set; } /// <summary> /// Gets the angle of the stylus relative to the surface, in radians /// </summary> /// <remarks> /// A value of 0 indicates that the stylus is parallel to the surface. A value of pi/2 indicates that it is perpendicular to the surface. /// </remarks> public float altitudeAngle { // only calculate angle when requested get { if (m_AltitudeNeedsConversion) { m_AltitudeAngle = TiltToAltitude(tilt); m_AltitudeNeedsConversion = false; } return m_AltitudeAngle; } protected set { m_AltitudeNeedsConversion = true; m_AltitudeAngle = value; } } /// <summary> /// Gets the angle of the stylus relative to the x-axis, in radians. /// </summary> /// <remarks> /// A value of 0 indicates that the stylus is pointed along the x-axis of the device. /// </remarks> public float azimuthAngle { // only calculate angle when requested get { if (m_AzimuthNeedsConversion) { m_AzimuthAngle = TiltToAzimuth(tilt); m_AzimuthNeedsConversion = false; } return m_AzimuthAngle; } protected set { m_AzimuthNeedsConversion = true; m_AzimuthAngle = value; } } /// <summary> /// Gets the rotation of the stylus around its axis, in radians. /// </summary> public float twist { get; protected set; } /// <summary> /// Specifies the angle of the pen relative to the X and Y axis respectively, in radians. /// </summary> public Vector2 tilt { // only calculate tilt when requested and not natively provided get { // windows does not provide altitude or azimuth for touch events, so there's nothing to convert if (!(Application.platform == RuntimePlatform.WindowsEditor || Application.platform == RuntimePlatform.WindowsPlayer) && this.pointerType == PointerType.touch && m_TiltNeeded) { m_Tilt = AzimuthAndAlitutudeToTilt(m_AltitudeAngle, m_AzimuthAngle); m_TiltNeeded = false; } return m_Tilt; } protected set { m_TiltNeeded = true; m_Tilt = value; } } /// <summary> /// Specifies the state of the pen. For example, whether the pen is in contact with the screen or tablet, whether the pen is inverted, and whether buttons are pressed. /// On macOS, penStatus will not reflect changes to button mappings. /// </summary> public PenStatus penStatus { get; protected set; } /// <summary> /// Gets an estimate of the radius of a touch. /// </summary> /// <remarks> /// Add `radiusVariance` to get the maximum touch radius, subtract it to get the minimum touch radius. /// </remarks> public Vector2 radius { get; protected set; } /// <summary> /// Gets the accuracy of the touch radius. /// </summary> /// <remarks> /// Add this value to the radius to get the maximum touch radius, subtract it to get the minimum touch radius. /// </remarks> public Vector2 radiusVariance { get; protected set; } /// <summary> /// Gets flags that indicate whether modifier keys (Alt, Ctrl, Shift, Windows/Cmd) are pressed. /// </summary> public EventModifiers modifiers { get; protected set; } /// <summary> /// Gets a boolean value that indicates whether the Shift key is pressed. True means the Shift key is pressed. /// False means it isn't. /// </summary> public bool shiftKey { get { return (modifiers & EventModifiers.Shift) != 0; } } /// <summary> /// Gets a boolean value that indicates whether the Ctrl key is pressed. True means the Ctrl key is pressed. /// False means it isn't. /// </summary> public bool ctrlKey { get { return (modifiers & EventModifiers.Control) != 0; } } /// <summary> /// Gets a boolean value that indicates whether the Windows/Cmd key is pressed. True means the Windows/Cmd key /// is pressed. False means it isn't. /// </summary> public bool commandKey { get { return (modifiers & EventModifiers.Command) != 0; } } /// <summary> /// Gets a boolean value that indicates whether the Alt key is pressed. True means the Alt key is pressed. /// False means it isn't. /// </summary> public bool altKey { get { return (modifiers & EventModifiers.Alt) != 0; } } /// <summary> /// Gets a boolean value that indicates whether the platform-specific action key is pressed. True means the action /// key is pressed. False means it isn't. /// </summary> /// <remarks> /// The platform-specific action key is Cmd on macOS, and Ctrl on all other platforms. /// </remarks> public bool actionKey { get { if (Application.platform == RuntimePlatform.OSXEditor || Application.platform == RuntimePlatform.OSXPlayer) { return commandKey; } else { return ctrlKey; } } } bool IPointerEventInternal.triggeredByOS { get; set; } IMouseEvent IPointerEventInternal.compatibilityMouseEvent { get; set; } int IPointerEventInternal.displayIndex { get; set; } /// <summary> /// Resets the event members to their initial values. /// </summary> protected override void Init() { base.Init(); LocalInit(); } void LocalInit() { propagation = EventPropagation.Bubbles | EventPropagation.TricklesDown; pointerId = 0; pointerType = PointerType.unknown; isPrimary = false; button = -1; pressedButtons = 0; position = Vector3.zero; localPosition = Vector3.zero; deltaPosition = Vector3.zero; deltaTime = 0; clickCount = 0; pressure = 0; tangentialPressure = 0; altitudeAngle = 0; azimuthAngle = 0; tilt = new Vector2(0f, 0f); twist = 0.0f; penStatus = PenStatus.None; radius = Vector2.zero; radiusVariance = Vector2.zero; modifiers = EventModifiers.None; ((IPointerEventInternal)this).triggeredByOS = false; if (((IPointerEventInternal) this).compatibilityMouseEvent != null) { ((IDisposable) ((IPointerEventInternal) this).compatibilityMouseEvent).Dispose(); ((IPointerEventInternal) this).compatibilityMouseEvent = null; } } /// <summary> /// Gets the current target of the event. /// </summary> /// <remarks> /// The current target is the element in the propagation path for which event handlers are currently being executed. /// </remarks> public override IEventHandler currentTarget { get { return base.currentTarget; } internal set { base.currentTarget = value; var element = currentTarget as VisualElement; if (element != null) { localPosition = element.WorldToLocal(position); } else { localPosition = position; } } } private static bool IsMouse(Event systemEvent) { EventType t = systemEvent.rawType; return t == EventType.MouseMove || t == EventType.MouseDown || t == EventType.MouseUp || t == EventType.MouseDrag || t == EventType.ContextClick || t == EventType.MouseEnterWindow || t == EventType.MouseLeaveWindow; } private static bool IsTouch(Event systemEvent) { EventType t = systemEvent.rawType; return t == EventType.TouchMove || t == EventType.TouchDown || t == EventType.TouchUp || t == EventType.TouchStationary || t == EventType.TouchEnter || t == EventType.TouchLeave; } /// <summary> /// Converts touch or stylus tilt to azimuth angle. /// </summary> /// <param name="tilt">Angle relative to the X and Y axis, in radians. abs(tilt.y) must be < pi/2</param> /// <returns>Azimuth angle as determined by tilt along x and y axese.</returns> private static float TiltToAzimuth(Vector2 tilt) { float azimuth = 0f; if (tilt.x != 0) { azimuth = Mathf.PI / 2 - Mathf.Atan2(-Mathf.Cos(tilt.x) * Mathf.Sin(tilt.y), Mathf.Cos(tilt.y) * Mathf.Sin(tilt.x)); if (azimuth < 0) // fix range to [0, 2*pi) azimuth += 2 * Mathf.PI; // follow UIKit conventions where azimuth is 0 when the cap end of the stylus points along the positive x axis of the device's screen if (azimuth >= (Mathf.PI / 2)) azimuth -= Mathf.PI / 2; else azimuth += (3 * Mathf.PI / 2); } return azimuth; } /// <summary> /// Converts touch or stylus azimuth and altitude to tilt /// </summary> /// <param name="tilt">Angle relative to the X and Y axis, in radians. abs(tilt.y) must be < pi/2</param> /// <returns>Azimuth angle as determined by tilt along x and y axese.</returns> private static Vector2 AzimuthAndAlitutudeToTilt(float altitude, float azimuth) { Vector2 t = new Vector2(0, 0); t.x = Mathf.Atan(Mathf.Cos(azimuth) * Mathf.Cos(altitude) / Mathf.Sin(azimuth)); t.y = Mathf.Atan(Mathf.Cos(azimuth) * Mathf.Sin(altitude) / Mathf.Sin(azimuth)); return t; } /// <summary> /// Converts touch or stylus tilt to altitude angle. /// </summary> /// <param name="tilt">Angle relative to the X and Y axis, in radians. abs(tilt.y) must be < pi/2</param> /// <returns>Altitude angle as determined by tilt along x and y axese.</returns> private static float TiltToAltitude(Vector2 tilt) { return Mathf.PI / 2 - Mathf.Acos(Mathf.Cos(tilt.x) * Mathf.Cos(tilt.y)); } /// <summary> /// Gets an event from the event pool and initializes it with the given values. Use this function instead of creating new events. /// Events obtained using this method need to be released back to the pool. You can use `Dispose()` to release them. /// </summary> /// <param name="systemEvent">An IMGUI mouse event.</param> /// <returns>An initialized event.</returns> public static T GetPooled(Event systemEvent) { T e = GetPooled(); if (!(IsMouse(systemEvent) || IsTouch(systemEvent) || systemEvent.rawType == EventType.DragUpdated)) { Debug.Assert(false, "Unexpected event type: " + systemEvent.rawType + " (" + systemEvent.type + ")"); } switch (systemEvent.pointerType) { default: e.pointerType = PointerType.mouse; e.pointerId = PointerId.mousePointerId; break; case UnityEngine.PointerType.Touch: e.pointerType = PointerType.touch; e.pointerId = PointerId.touchPointerIdBase; break; case UnityEngine.PointerType.Pen: e.pointerType = PointerType.pen; e.pointerId = PointerId.penPointerIdBase; // system events are not fired for pen buttons, so in order to keep buttonsate up to date we need to check the status of these buttons for all pen events if (systemEvent.penStatus == PenStatus.Barrel) PointerDeviceState.PressButton(e.pointerId, (int) PenButton.PenBarrel); else PointerDeviceState.ReleaseButton(e.pointerId, (int) PenButton.PenBarrel); if (systemEvent.penStatus == PenStatus.Eraser) PointerDeviceState.PressButton(e.pointerId, (int) PenButton.PenEraser); else PointerDeviceState.ReleaseButton(e.pointerId, (int) PenButton.PenEraser); break; } e.isPrimary = true; // calculate these on demand e.altitudeAngle = 0f; e.azimuthAngle = 0f; e.radius = Vector2.zero; e.radiusVariance = Vector2.zero; e.imguiEvent = systemEvent; if (systemEvent.rawType == EventType.MouseDown || systemEvent.rawType == EventType.TouchDown) { PointerDeviceState.PressButton(e.pointerId, systemEvent.button); e.button = systemEvent.button; } else if (systemEvent.rawType == EventType.MouseUp || systemEvent.rawType == EventType.TouchUp) { PointerDeviceState.ReleaseButton(e.pointerId, systemEvent.button); e.button = systemEvent.button; } else if (systemEvent.rawType == EventType.MouseMove || systemEvent.rawType == EventType.TouchMove) { e.button = -1; } e.pressedButtons = PointerDeviceState.GetPressedButtons(e.pointerId); e.position = systemEvent.mousePosition; e.localPosition = systemEvent.mousePosition; e.deltaPosition = systemEvent.delta; e.clickCount = systemEvent.clickCount; e.modifiers = systemEvent.modifiers; e.tilt = systemEvent.tilt; e.penStatus = systemEvent.penStatus; e.twist = systemEvent.twist; switch (systemEvent.pointerType) { default: e.pressure = e.pressedButtons == 0 ? 0f : k_DefaultButtonPressure; break; case UnityEngine.PointerType.Touch: e.pressure = systemEvent.pressure; break; case UnityEngine.PointerType.Pen: e.pressure = systemEvent.pressure; break; } e.tangentialPressure = 0; ((IPointerEventInternal)e).triggeredByOS = true; return e; } internal static T GetPooled(EventType eventType, Vector3 mousePosition, Vector2 delta, int button, int clickCount, EventModifiers modifiers, int displayIndex) { T e = GetPooled(); e.pointerId = PointerId.mousePointerId; e.pointerType = PointerType.mouse; e.isPrimary = true; ((IPointerEventInternal) e).displayIndex = displayIndex; if (eventType == EventType.MouseDown) { PointerDeviceState.PressButton(e.pointerId, button); e.button = button; } else if (eventType == EventType.MouseUp) { PointerDeviceState.ReleaseButton(e.pointerId, button); e.button = button; } else { e.button = -1; } e.pressedButtons = PointerDeviceState.GetPressedButtons(e.pointerId); e.position = mousePosition; e.localPosition = mousePosition; e.deltaPosition = delta; e.clickCount = clickCount; e.modifiers = modifiers; e.pressure = e.pressedButtons == 0 ? 0f : k_DefaultButtonPressure; ((IPointerEventInternal)e).triggeredByOS = true; return e; } /// <summary> /// Gets an event from the event pool and initializes it with the given values. Use this function instead of creating new events. /// Events obtained using this method need to be released back to the pool. You can use `Dispose()` to release them. /// </summary> /// <param name="touch">A <see cref="Touch"/> structure from the InputManager.</param> /// <param name="modifiers">The modifier keys held down during the event.</param> /// <returns>An initialized event.</returns> public static T GetPooled(Touch touch, EventModifiers modifiers = EventModifiers.None) => GetPooled(touch, modifiers, 0); internal static T GetPooled(Touch touch, EventModifiers modifiers, int displayIndex) { T e = GetPooled(); e.pointerId = touch.fingerId + PointerId.touchPointerIdBase; e.pointerType = PointerType.touch; ((IPointerEventInternal) e).displayIndex = displayIndex; // TODO: Rethink this logic. When two fingers are down, PointerMoveEvents should still have 1 primary touch. bool otherTouchDown = false; for (var i = PointerId.touchPointerIdBase; i < PointerId.touchPointerIdBase + PointerId.touchPointerCount; i++) { if (i != e.pointerId && PointerDeviceState.GetPressedButtons(i) != 0) { otherTouchDown = true; break; } } e.isPrimary = !otherTouchDown; if (touch.phase == TouchPhase.Began) { PointerDeviceState.PressButton(e.pointerId, 0); e.button = 0; } else if (touch.phase == TouchPhase.Ended || touch.phase == TouchPhase.Canceled) { PointerDeviceState.ReleaseButton(e.pointerId, 0); e.button = 0; } else { e.button = -1; } e.pressedButtons = PointerDeviceState.GetPressedButtons(e.pointerId); e.position = touch.position; e.localPosition = touch.position; e.deltaPosition = touch.deltaPosition; e.deltaTime = touch.deltaTime; e.clickCount = touch.tapCount; e.pressure = Mathf.Abs(touch.maximumPossiblePressure) > UIRUtility.k_Epsilon ? touch.pressure / touch.maximumPossiblePressure : 1f; e.tangentialPressure = 0; e.altitudeAngle = touch.altitudeAngle; e.azimuthAngle = touch.azimuthAngle; e.twist = 0.0f; e.tilt = new Vector2(0f, 0f); e.penStatus = PenStatus.None; e.radius = new Vector2(touch.radius, touch.radius); e.radiusVariance = new Vector2(touch.radiusVariance, touch.radiusVariance); e.modifiers = modifiers; ((IPointerEventInternal)e).triggeredByOS = true; return e; } /// <summary> /// Gets a pointer event from the event pool and initializes it with the given values. Use this function instead of creating new events. /// Events obtained using this method need to be released back to the pool. You can use `Dispose()` to release them. /// </summary> /// <param name="pen">A <see cref="PenData"/> structure from the InputManager containing pen event information.</param> /// <param name="modifiers">The modifier keys held down during the event.</param> /// <returns>An initialized event.</returns> public static T GetPooled(PenData pen, EventModifiers modifiers = EventModifiers.None) => GetPooled(pen, modifiers, 0); internal static T GetPooled(PenData pen, EventModifiers modifiers, int displayIndex) { T e = GetPooled(); e.pointerId = PointerId.penPointerIdBase; e.pointerType = PointerType.pen; ((IPointerEventInternal) e).displayIndex = displayIndex; e.isPrimary = true; if (pen.contactType == PenEventType.PenDown) { PointerDeviceState.PressButton(e.pointerId, 0); e.button = 0; } else if (pen.contactType == PenEventType.PenUp) { PointerDeviceState.ReleaseButton(e.pointerId, 0); e.button = 0; } else { e.button = -1; } // system events are not fired for pen buttons, so in order to keep buttonsate up to date we need to check the status of these buttons for all pen events if (pen.penStatus == PenStatus.Barrel) PointerDeviceState.PressButton(e.pointerId, (int) PenButton.PenBarrel); else PointerDeviceState.ReleaseButton(e.pointerId, (int) PenButton.PenBarrel); if (pen.penStatus == PenStatus.Eraser) PointerDeviceState.PressButton(e.pointerId, (int) PenButton.PenEraser); else PointerDeviceState.ReleaseButton(e.pointerId, (int) PenButton.PenEraser); e.pressedButtons = PointerDeviceState.GetPressedButtons(e.pointerId); e.position = pen.position; e.localPosition = pen.position; e.deltaPosition = pen.deltaPos; e.clickCount = 0; e.pressure = pen.pressure; e.tangentialPressure = 0; e.twist = pen.twist; e.tilt = pen.tilt; e.penStatus = pen.penStatus; e.radius = Vector2.zero; e.radiusVariance = Vector2.zero; e.modifiers = modifiers; ((IPointerEventInternal)e).triggeredByOS = true; return e; } internal static T GetPooled(PointerEvent pointerEvent, Vector2 position, Vector2 deltaPosition, int pointerId, float deltaTime) { T e = GetPooled(); e.position = position; e.localPosition = position; e.deltaPosition = deltaPosition; e.pointerId = pointerId; e.deltaTime = deltaTime; ((IPointerEventInternal) e).displayIndex = pointerEvent.displayIndex; e.isPrimary = pointerEvent.isPrimaryPointer; e.button = -1; if (pointerEvent.eventSource == EventSource.Mouse) { e.pointerType = PointerType.mouse; Debug.Assert(pointerEvent.isPrimaryPointer, "PointerEvent from Mouse source is expected to be a primary pointer."); Debug.Assert(pointerId == PointerId.mousePointerId, "PointerEvent from Mouse source is expected to have mouse pointer id."); if (pointerEvent.button == PointerEvent.Button.MouseLeft) { e.button = (int)MouseButton.LeftMouse; } else if (pointerEvent.button == PointerEvent.Button.MouseRight) { e.button = (int)MouseButton.RightMouse; } else if (pointerEvent.button == PointerEvent.Button.MouseMiddle) { e.button = (int)MouseButton.MiddleMouse; } } else if (pointerEvent.eventSource == EventSource.Touch) { e.pointerType = PointerType.touch; Debug.Assert(e.pointerId >= PointerId.touchPointerIdBase && e.pointerId < PointerId.touchPointerIdBase + PointerId.touchPointerCount, "PointerEvent from Touch source is expected to have touch-based pointer id."); if (pointerEvent.button == PointerEvent.Button.FingerInTouch) e.button = 0; } else if (pointerEvent.eventSource == EventSource.Pen) { e.pointerType = PointerType.pen; Debug.Assert(e.pointerId >= PointerId.penPointerIdBase && e.pointerId < PointerId.penPointerIdBase + PointerId.penPointerCount, "PointerEvent from Pen source is expected to have pen-based pointer id."); if (pointerEvent.button == PointerEvent.Button.PenTipInTouch) e.button = (int)PenButton.PenContact; else if (pointerEvent.button == PointerEvent.Button.PenBarrelButton) e.button = (int)PenButton.PenBarrel; else if (pointerEvent.button == PointerEvent.Button.PenEraserInTouch) e.button = (int)PenButton.PenEraser; } else { throw new ArgumentOutOfRangeException(nameof(pointerEvent), "Unsupported EventSource for pointer event"); } if (pointerEvent.type == PointerEvent.Type.ButtonPressed) { Debug.Assert(e.button != -1, "PointerEvent of type ButtonPressed is expected to have button != -1."); PointerDeviceState.PressButton(e.pointerId, e.button); } else if (pointerEvent.type == PointerEvent.Type.ButtonReleased) { Debug.Assert(e.button != -1, "PointerEvent of type ButtonReleased is expected to have button != -1."); PointerDeviceState.ReleaseButton(e.pointerId, e.button); } else if (pointerEvent.type != PointerEvent.Type.TouchCanceled) { Debug.Assert(e.button == -1, "PointerEvent of type other than ButtonPressed, ButtonReleased, or TouchCanceled is expected to have button set to none."); } e.pressedButtons = PointerDeviceState.GetPressedButtons(e.pointerId); if (pointerEvent.eventSource == EventSource.Pen) { e.penStatus = PenStatus.None; if ((e.pressedButtons & (1 << (int) PenButton.PenContact)) != 0) e.penStatus |= PenStatus.Contact; if ((e.pressedButtons & (1 << (int) PenButton.PenBarrel)) != 0) e.penStatus |= PenStatus.Barrel; if ((e.pressedButtons & (1 << (int) PenButton.PenEraser)) != 0) e.penStatus |= PenStatus.Eraser; if (pointerEvent.isInverted) e.penStatus |= PenStatus.Inverted; } e.clickCount = pointerEvent.clickCount; e.pressure = pointerEvent.pressure; e.altitudeAngle = pointerEvent.altitude; e.azimuthAngle = pointerEvent.azimuth; e.twist = pointerEvent.twist; e.tilt = pointerEvent.tilt; // Not supported by InputForUI: e.tangentialPressure, e.radius, e.radiusVariance // Not supported by UIToolkit: pointerEvent.deltaBeforeAccelerationCurve EventModifiers modifiers = EventModifiers.None; if (pointerEvent.eventModifiers.isShiftPressed) { modifiers |= EventModifiers.Shift; } if (pointerEvent.eventModifiers.isCtrlPressed) { modifiers |= EventModifiers.Control; } if (pointerEvent.eventModifiers.isAltPressed) { modifiers |= EventModifiers.Alt; } if (pointerEvent.eventModifiers.isMetaPressed) { modifiers |= EventModifiers.Command; } // As stated in documentation, e.modifiers indicate whether (Alt, Ctrl, Shift, Windows/Cmd) are pressed. // Also, Editor-side IMGUI Events of type MouseUp/Down/Move don't seem to set the other modifiers either. e.modifiers = modifiers; ((IPointerEventInternal)e).triggeredByOS = true; return e; } internal static T GetPooled(IPointerEvent triggerEvent, Vector2 position, int pointerId) { if (triggerEvent != null) { return GetPooled(triggerEvent); } T e = GetPooled(); e.position = position; e.localPosition = position; e.pointerId = pointerId; e.pointerType = PointerType.GetPointerType(pointerId); return e; } /// <summary> /// Gets an event from the event pool and initializes it with the given values. Use this function instead of creating new events. /// Events obtained using this method need to be released back to the pool. You can use `Dispose()` to release them. /// </summary> /// <param name="triggerEvent">The event that sent this event.</param> /// <returns>An initialized event.</returns> public static T GetPooled(IPointerEvent triggerEvent) { T e = GetPooled(); if (triggerEvent != null) { e.pointerId = triggerEvent.pointerId; e.pointerType = triggerEvent.pointerType; e.isPrimary = triggerEvent.isPrimary; e.button = triggerEvent.button; e.pressedButtons = triggerEvent.pressedButtons; e.position = triggerEvent.position; e.localPosition = triggerEvent.localPosition; e.deltaPosition = triggerEvent.deltaPosition; e.deltaTime = triggerEvent.deltaTime; e.clickCount = triggerEvent.clickCount; e.pressure = triggerEvent.pressure; e.tangentialPressure = triggerEvent.tangentialPressure; e.altitudeAngle = triggerEvent.altitudeAngle; e.azimuthAngle = triggerEvent.azimuthAngle; e.twist = triggerEvent.twist; e.tilt = triggerEvent.tilt; e.penStatus = triggerEvent.penStatus; e.radius = triggerEvent.radius; e.radiusVariance = triggerEvent.radiusVariance; e.modifiers = triggerEvent.modifiers; IPointerEventInternal pointerEventInternal = triggerEvent as IPointerEventInternal; if (pointerEventInternal != null) { ((IPointerEventInternal)e).triggeredByOS |= pointerEventInternal.triggeredByOS; } } return e; } protected internal override void PreDispatch(IPanel panel) { base.PreDispatch(panel); if (((IPointerEventInternal)this).triggeredByOS) { PointerDeviceState.SavePointerPosition(pointerId, position, panel, panel.contextType); } ((EventBase) ((IPointerEventInternal) this).compatibilityMouseEvent)?.PreDispatch(panel); } protected internal override void PostDispatch(IPanel panel) { for (var i = 0; i < PointerId.maxPointers; i++) { panel.ProcessPointerCapture(i); } if (((IPointerEventInternal)this).triggeredByOS) { (panel as BaseVisualElementPanel)?.CommitElementUnderPointers(); } ((EventBase) ((IPointerEventInternal) this).compatibilityMouseEvent)?.PostDispatch(panel); panel.dispatcher.m_ClickDetector.ProcessEvent(this); base.PostDispatch(panel); } internal override void Dispatch(BaseVisualElementPanel panel) { EventDispatchUtilities.DispatchToCapturingElementOrElementUnderPointer(this, panel, pointerId, position); } protected PointerEventBase() { LocalInit(); } } /// <summary> /// This event is sent when a pointer is pressed. /// </summary> /// <remarks> /// A PointerDownEvent is sent the first time a finger touches the screen or a mouse button is /// pressed. Additional button presses and touches with additional fingers trigger PointerMoveEvents. /// /// A PointerDownEvent uses the default pointer event propagation path: it trickles down, bubbles up and /// can be cancelled. /// Disabled elements won't receive this event by default. /// /// See <see cref="UIElements.PointerEventBase{T}"/> to see how PointerDownEvent relates to other pointer events. /// </remarks> [EventCategory(EventCategory.PointerDown)] public sealed class PointerDownEvent : PointerEventBase<PointerDownEvent> { static PointerDownEvent() { SetCreateFunction(() => new PointerDownEvent()); } /// <summary> /// Resets the event members to their initial values. /// </summary> protected override void Init() { base.Init(); LocalInit(); } void LocalInit() { propagation = EventPropagation.Bubbles | EventPropagation.TricklesDown | EventPropagation.SkipDisabledElements; ((IPointerEventInternal)this).triggeredByOS = true; } /// <summary> /// Constructor. Avoid creating new event instances. Instead, use GetPooled() to get an instance from a pool of reusable event instances. /// </summary> public PointerDownEvent() { LocalInit(); } protected internal override void PreDispatch(IPanel panel) { base.PreDispatch(panel); if (panel.ShouldSendCompatibilityMouseEvents(this)) { ((IPointerEventInternal) this).compatibilityMouseEvent = MouseDownEvent.GetPooled(this); } } protected internal override void PostDispatch(IPanel panel) { panel.focusController.SwitchFocusOnEvent(panel.focusController.GetLeafFocusedElement(), this); base.PostDispatch(panel); } } /// <summary> /// This event is sent when a pointer changes state. /// </summary> /// <remarks> /// The state of a pointer changes when one or more of its properties changes after a <see cref="PointerDownEvent"/> but before a /// <see cref="PointerUpEvent"/>. For example if its position or pressure change, or a different button is pressed. /// /// A PointerMoveEvent uses the default pointer event propagation path: it trickles down, bubbles up and /// can be cancelled. /// Disabled elements receive this event by default. /// /// See <see cref="UIElements.PointerEventBase{T}"/> to see how PointerMoveEvent relates to other pointer events. /// </remarks> [EventCategory(EventCategory.PointerMove)] public sealed class PointerMoveEvent : PointerEventBase<PointerMoveEvent> { static PointerMoveEvent() { SetCreateFunction(() => new PointerMoveEvent()); } /// <summary> /// Set this variable if the target should have priority when used in a touch enabled scroll view. /// </summary> internal bool isHandledByDraggable { get; set; } internal bool isPointerUpDown => button >= 0; internal bool isPointerDown => button >= 0 && 0 != (pressedButtons & (1 << button)); internal bool isPointerUp => button >= 0 && 0 == (pressedButtons & (1 << button)); /// <summary> /// Resets the event members to their initial values. /// </summary> protected override void Init() { base.Init(); LocalInit(); } void LocalInit() { propagation = EventPropagation.Bubbles | EventPropagation.TricklesDown; ((IPointerEventInternal)this).triggeredByOS = true; isHandledByDraggable = false; } /// <summary> /// Constructor. Avoid creating new event instances. Instead, use GetPooled() to get an instance from a pool of reusable event instances. /// </summary> public PointerMoveEvent() { LocalInit(); } protected internal override void PreDispatch(IPanel panel) { base.PreDispatch(panel); if (panel.ShouldSendCompatibilityMouseEvents(this)) { if (imguiEvent != null && imguiEvent.rawType == EventType.MouseDown) { ((IPointerEventInternal) this).compatibilityMouseEvent = MouseDownEvent.GetPooled(this); } else if (imguiEvent != null && imguiEvent.rawType == EventType.MouseUp) { ((IPointerEventInternal) this).compatibilityMouseEvent = MouseUpEvent.GetPooled(this); } else { ((IPointerEventInternal) this).compatibilityMouseEvent = MouseMoveEvent.GetPooled(this); } } } } /// <summary> /// This event is sent when a pointer does not change for a set amount of time, determined by the operating system. /// </summary> /// <remarks> /// After a <see cref="PointerDownEvent"/> is sent, this event is sent if a <see cref="PointerMoveEvent"/> or /// a <see cref="PointerUpEvent"/> is not sent before a set amount of time. /// /// A PointerStationaryEvent uses the default pointer event propagation path: it trickles down, bubbles up /// and can be cancelled. /// Disabled elements receive this event by default. /// /// See <see cref="UIElements.PointerEventBase{T}"/> to see how PointerStationaryEvent relates to other pointer events. /// </remarks> [Obsolete("Not sent by input backend.")] public sealed class PointerStationaryEvent : PointerEventBase<PointerStationaryEvent> { static PointerStationaryEvent() { SetCreateFunction(() => new PointerStationaryEvent()); } /// <summary> /// Resets the event members to their initial values. /// </summary> protected override void Init() { base.Init(); LocalInit(); } void LocalInit() { propagation = EventPropagation.Bubbles | EventPropagation.TricklesDown; ((IPointerEventInternal)this).triggeredByOS = true; } /// <summary> /// Constructor. Avoid creating new event instances. Instead, use GetPooled() to get an instance from a pool of reusable event instances. /// </summary> public PointerStationaryEvent() { LocalInit(); } } /// <summary> /// This event is sent when a pointer's last pressed button is released. /// </summary> /// <remarks> /// The last pressed button may or may not be the same button that triggered the <see cref="PointerDownEvent"/>. /// /// A PointerUpEvent uses the default pointer event propagation path: it is trickled down, bubbled up /// and can be cancelled. /// Disabled elements won't receive this event by default. /// /// See <see cref="UIElements.PointerEventBase{T}"/> to see how PointerUpEvent relates to other pointer events. /// </remarks> public sealed class PointerUpEvent : PointerEventBase<PointerUpEvent> { static PointerUpEvent() { SetCreateFunction(() => new PointerUpEvent()); } /// <summary> /// Resets the event members to their initial values. /// </summary> protected override void Init() { base.Init(); LocalInit(); } void LocalInit() { propagation = EventPropagation.Bubbles | EventPropagation.TricklesDown | EventPropagation.SkipDisabledElements; ((IPointerEventInternal)this).triggeredByOS = true; } /// <summary> /// Constructor. Avoid creating new event instances. Instead, use GetPooled() to get an instance from a pool of reusable event instances. /// </summary> public PointerUpEvent() { LocalInit(); } protected internal override void PreDispatch(IPanel panel) { base.PreDispatch(panel); if (panel.ShouldSendCompatibilityMouseEvents(this)) { ((IPointerEventInternal) this).compatibilityMouseEvent = MouseUpEvent.GetPooled(this); } } protected internal override void PostDispatch(IPanel panel) { if (PointerType.IsDirectManipulationDevice(pointerType)) { panel.ReleasePointer(pointerId); BaseVisualElementPanel basePanel = panel as BaseVisualElementPanel; basePanel?.ClearCachedElementUnderPointer(pointerId, this); } base.PostDispatch(panel); panel.ActivateCompatibilityMouseEvents(pointerId); } } /// <summary> /// This event is sent when pointer interaction is cancelled. /// </summary> /// <remarks> /// A PointerCancelEvent can trickle down or bubble up, but cannot be cancelled. /// Disabled elements won't receive this event by default. /// /// See <see cref="UIElements.PointerEventBase{T}"/> to see how PointerCancelEvent relates to other pointer events. /// </remarks> public sealed class PointerCancelEvent : PointerEventBase<PointerCancelEvent> { static PointerCancelEvent() { SetCreateFunction(() => new PointerCancelEvent()); } /// <summary> /// Resets the event members to their initial values. /// </summary> protected override void Init() { base.Init(); LocalInit(); } void LocalInit() { propagation = EventPropagation.Bubbles | EventPropagation.TricklesDown | EventPropagation.SkipDisabledElements; ((IPointerEventInternal)this).triggeredByOS = true; } /// <summary> /// Constructor. Avoid creating new event instances. Instead, use GetPooled() to get an instance from a pool of reusable event instances. /// </summary> public PointerCancelEvent() { LocalInit(); } protected internal override void PreDispatch(IPanel panel) { base.PreDispatch(panel); if (panel.ShouldSendCompatibilityMouseEvents(this)) { ((IPointerEventInternal) this).compatibilityMouseEvent = MouseUpEvent.GetPooled(this); } } protected internal override void PostDispatch(IPanel panel) { if (PointerType.IsDirectManipulationDevice(pointerType)) { panel.ReleasePointer(pointerId); BaseVisualElementPanel basePanel = panel as BaseVisualElementPanel; basePanel?.ClearCachedElementUnderPointer(pointerId, this); } base.PostDispatch(panel); panel.ActivateCompatibilityMouseEvents(pointerId); } } /// <summary> /// This event is sent when the left mouse button is clicked. /// </summary> /// <remarks> /// A click consists of a mouse down event followed by a mouse up event on the same VisualElement. /// The mouse might move between the two events but the move is ignored as long as the mouse down /// and mouse up events occur on the same VisualElement. /// /// A ClickEvent uses the default pointer event propagation path: it trickles down, bubbles up /// and can be cancelled. /// Disabled elements won't receive this event by default. /// /// See <see cref="UIElements.PointerEventBase{T}"/> to see how ClickEvent relates to other pointer events. /// /// </remarks> public sealed class ClickEvent : PointerEventBase<ClickEvent> { static ClickEvent() { SetCreateFunction(() => new ClickEvent()); } /// <summary> /// Resets the event members to their initial values. /// </summary> protected override void Init() { base.Init(); LocalInit(); } void LocalInit() { propagation = EventPropagation.Bubbles | EventPropagation.TricklesDown | EventPropagation.SkipDisabledElements; } /// <summary> /// Constructor. Avoid creating new event instances. Instead, use GetPooled() to get an instance from a pool of reusable event instances. /// </summary> public ClickEvent() { LocalInit(); } internal static ClickEvent GetPooled(IPointerEvent pointerEvent, int clickCount) { var evt = PointerEventBase<ClickEvent>.GetPooled(pointerEvent); evt.clickCount = clickCount; return evt; } // Note that ClickDetector always sends ClickEvents with an assigned target. However, we're not assuming we can // dispatch directly to target because users may send their own ClickEvents with a position and no target. } /// <summary> /// This event is sent when a pointer enters a VisualElement or one of its descendants. /// The event does not trickle down and does not bubble up. /// </summary> [EventCategory(EventCategory.EnterLeave)] public sealed class PointerEnterEvent : PointerEventBase<PointerEnterEvent> { static PointerEnterEvent() { SetCreateFunction(() => new PointerEnterEvent()); } /// <summary> /// Resets the event members to their initial values. /// </summary> protected override void Init() { base.Init(); LocalInit(); } void LocalInit() { propagation = EventPropagation.TricklesDown; } /// <summary> /// Constructor. Avoid creating new event instances. Instead, use GetPooled() to get an instance from a pool of reusable event instances. /// </summary> public PointerEnterEvent() { LocalInit(); } internal override void Dispatch(BaseVisualElementPanel panel) { EventDispatchUtilities.DispatchToAssignedTarget(this, panel); } protected internal override void PreDispatch(IPanel panel) { base.PreDispatch(panel); elementTarget.containedPointerIds |= 1 << pointerId; elementTarget.UpdateHoverPseudoState(); } } /// <summary> /// This event is sent when a pointer exits an element and all of its descendants. /// The event does not trickle down and does not bubble up. /// </summary> [EventCategory(EventCategory.EnterLeave)] public sealed class PointerLeaveEvent : PointerEventBase<PointerLeaveEvent> { static PointerLeaveEvent() { SetCreateFunction(() => new PointerLeaveEvent()); } /// <summary> /// Resets the event members to their initial values. /// </summary> protected override void Init() { base.Init(); LocalInit(); } void LocalInit() { propagation = EventPropagation.TricklesDown; } /// <summary> /// Constructor. Avoid creating new event instances. Instead, use GetPooled() to get an instance from a pool of reusable event instances. /// </summary> public PointerLeaveEvent() { LocalInit(); } internal override void Dispatch(BaseVisualElementPanel panel) { EventDispatchUtilities.DispatchToAssignedTarget(this, panel); } protected internal override void PreDispatch(IPanel panel) { base.PreDispatch(panel); elementTarget.containedPointerIds &= ~(1 << pointerId); elementTarget.UpdateHoverPseudoState(); } } /// <summary> /// This event is sent when a pointer enters an element. /// The event trickles down and bubbles up. /// </summary> [EventCategory(EventCategory.EnterLeave)] public sealed class PointerOverEvent : PointerEventBase<PointerOverEvent> { static PointerOverEvent() { SetCreateFunction(() => new PointerOverEvent()); } internal override void Dispatch(BaseVisualElementPanel panel) { EventDispatchUtilities.DispatchToAssignedTarget(this, panel); } } /// <summary> /// This event is sent when a pointer exits an element. /// The event trickles down and bubbles up. /// </summary> [EventCategory(EventCategory.EnterLeave)] public sealed class PointerOutEvent : PointerEventBase<PointerOutEvent> { static PointerOutEvent() { SetCreateFunction(() => new PointerOutEvent()); } internal override void Dispatch(BaseVisualElementPanel panel) { EventDispatchUtilities.DispatchToAssignedTarget(this, panel); } } }
UnityCsReference/Modules/UIElements/Core/Events/PointerEvents.cs/0
{ "file_path": "UnityCsReference/Modules/UIElements/Core/Events/PointerEvents.cs", "repo_id": "UnityCsReference", "token_count": 29029 }
494
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; namespace UnityEngine.UIElements { internal static class GroupBoxUtility { static Dictionary<IGroupBox, IGroupManager> s_GroupManagers = new Dictionary<IGroupBox, IGroupManager>(); static Dictionary<IGroupBoxOption, IGroupManager> s_GroupOptionManagerCache = new Dictionary<IGroupBoxOption, IGroupManager>(); static readonly Type k_GenericGroupBoxType = typeof(IGroupBox<>); /// <summary> /// Registers this group option panel callbacks. /// </summary> public static void RegisterGroupBoxOption<T>(this T option) where T : VisualElement, IGroupBoxOption { var element = option as VisualElement; IGroupBox groupInHierarchy = null; var hierarchyParent = element.hierarchy.parent; while (hierarchyParent != null) { if (hierarchyParent is IGroupBox group) { groupInHierarchy = group; break; } hierarchyParent = hierarchyParent.hierarchy.parent; } var groupBox = groupInHierarchy ?? element.elementPanel; var groupManager = FindOrCreateGroupManager(groupBox); groupManager.RegisterOption(option); s_GroupOptionManagerCache[option] = groupManager; } public static void UnregisterGroupBoxOption<T>(this T option) where T : VisualElement, IGroupBoxOption { if (!s_GroupOptionManagerCache.ContainsKey(option)) return; s_GroupOptionManagerCache[option].UnregisterOption(option); s_GroupOptionManagerCache.Remove(option); } /// <summary> /// Updates selection on all group options linked to this one. /// </summary> public static void OnOptionSelected<T>(this T selectedOption) where T : VisualElement, IGroupBoxOption { if (!s_GroupOptionManagerCache.ContainsKey(selectedOption)) return; s_GroupOptionManagerCache[selectedOption].OnOptionSelectionChanged(selectedOption); } /// <summary> /// Retrieve the selected option in this group /// </summary> public static IGroupBoxOption GetSelectedOption(this IGroupBox groupBox) { return !s_GroupManagers.ContainsKey(groupBox) ? null : s_GroupManagers[groupBox].GetSelectedOption(); } /// <summary> /// Accessor for the group manager of a specified group box implementation. /// Note: A group manager is only created once an option is added under its group box. It has no use otherwise. /// </summary> /// <param name="groupBox">The group box to search against.</param> /// <returns>The group manager associated to this group box.</returns> public static IGroupManager GetGroupManager(this IGroupBox groupBox) { return s_GroupManagers.ContainsKey(groupBox) ? s_GroupManagers[groupBox] : null; } static IGroupManager FindOrCreateGroupManager(IGroupBox groupBox) { if (s_GroupManagers.ContainsKey(groupBox)) { return s_GroupManagers[groupBox]; } Type genericType = null; foreach (var interfaceType in groupBox.GetType().GetInterfaces()) { if (interfaceType.IsGenericType && k_GenericGroupBoxType.IsAssignableFrom(interfaceType.GetGenericTypeDefinition())) { genericType = interfaceType.GetGenericArguments()[0]; break; } } var groupManager = genericType != null ? (IGroupManager)Activator.CreateInstance(genericType) : new DefaultGroupManager(); groupManager.Init(groupBox); if (groupBox is BaseVisualElementPanel panel) { panel.panelDisposed += OnPanelDestroyed; } else if (groupBox is VisualElement visualElement) { visualElement.RegisterCallback<DetachFromPanelEvent>(OnGroupBoxDetachedFromPanel); } s_GroupManagers[groupBox] = groupManager; return groupManager; } static void OnGroupBoxDetachedFromPanel(DetachFromPanelEvent evt) { s_GroupManagers.Remove(evt.currentTarget as IGroupBox); } static void OnPanelDestroyed(BaseVisualElementPanel panel) { s_GroupManagers.Remove(panel); panel.panelDisposed -= OnPanelDestroyed; } } }
UnityCsReference/Modules/UIElements/Core/GroupBoxUtility.cs/0
{ "file_path": "UnityCsReference/Modules/UIElements/Core/GroupBoxUtility.cs", "repo_id": "UnityCsReference", "token_count": 2050 }
495
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Threading; using Unity.Collections; using UnityEngine.Scripting; namespace UnityEngine.UIElements.Layout; [RequiredByNativeCode] enum LayoutNodeDataType { Node = 0, Style = 1, Computed = 2, Cache = 3, StyleDimensions = 4, StyleMargin = 5, StyleBorder = 6 } [RequiredByNativeCode] enum LayoutConfigDataType { Config = 0 } delegate void LayoutMeasureFunction( VisualElement ve, ref LayoutNode node, float width, LayoutMeasureMode widthMode, float height, LayoutMeasureMode heightMode, out LayoutSize result); delegate float LayoutBaselineFunction( ref LayoutNode node, float width, float height); class ManagedObjectStore<T> where T : class { const int k_ChunkSize = 1024 * 2; // 2k elements per 'chunk' int m_Length; readonly List<T[]> m_Chunks; readonly Queue<int> m_Free; public ManagedObjectStore() { m_Chunks = new List<T[]> { new T[k_ChunkSize] }; m_Length = 1; m_Free = new Queue<int>(); } public T GetValue(int index) { if (index == 0) return null; var chunkIndex = index / k_ChunkSize; var indexInChunk = index % k_ChunkSize; return m_Chunks[chunkIndex][indexInChunk]; } public void UpdateValue(ref int index, T value) { if (index != 0) { if (value != null) { var chunkIndex = index / k_ChunkSize; var indexInChunk = index % k_ChunkSize; // We have an index already and the value we are assigning is non-null. Perform a simple update. m_Chunks[chunkIndex][indexInChunk] = value; } else { // We have an index but the assigned value is null. Treat this as a removal and record the index as free for re-use. m_Free.Enqueue(index); var chunkIndex = index / k_ChunkSize; var indexInChunk = index % k_ChunkSize; m_Chunks[chunkIndex][indexInChunk] = default; index = 0; } } else if (value != null) { // We don't have an index and the value is not null. We need a new entry in the list. if (m_Free.Count > 0) { // Use the free list if available. index = m_Free.Dequeue(); var chunkIndex = index / k_ChunkSize; var indexInChunk = index % k_ChunkSize; m_Chunks[chunkIndex][indexInChunk] = value; } else { // Otherwise allocate a new entry. index = m_Length++; if (index >= m_Chunks.Count * k_ChunkSize) m_Chunks.Add(new T[k_ChunkSize]); var chunkIndex = index / k_ChunkSize; var indexInChunk = index % k_ChunkSize; m_Chunks[chunkIndex][indexInChunk] = value; } } } } internal class LayoutManager : IDisposable { static bool s_Initialized; static bool s_AppDomainUnloadRegistered; static LayoutManager s_SharedInstance; public static LayoutManager SharedManager => s_SharedInstance; static readonly List<LayoutManager> s_Managers = new List<LayoutManager>(); static LayoutManager() { Initialize(); } static void Initialize() { if (s_Initialized) return; s_Initialized = true; if (!s_AppDomainUnloadRegistered) { // important: this will always be called from a special unload thread (main thread will be blocking on this) AppDomain.CurrentDomain.DomainUnload += (_, __) => { if (s_Initialized) Shutdown(); }; s_AppDomainUnloadRegistered = true; } s_SharedInstance = new LayoutManager(Allocator.Persistent); } static void Shutdown() { if (!s_Initialized) return; s_Initialized = false; s_SharedInstance.Dispose(); } const int k_InitialNodeCapacity = 1024 * 64; const int k_InitialConfigCapacity = 32; readonly int m_Index; LayoutDataStore m_Nodes; LayoutDataStore m_Configs; readonly object m_SyncRoot = new(); readonly Stack<LayoutHandle> m_NodesToFree = new(); readonly LayoutHandle m_DefaultConfig; readonly ManagedObjectStore<LayoutMeasureFunction> m_ManagedMeasureFunctions = new(); readonly ManagedObjectStore<LayoutBaselineFunction> m_ManagedBaselineFunctions = new(); readonly ManagedObjectStore<WeakReference<VisualElement>> m_ManagedOwners = new(); // Last allocated index in the store (0 mean index 0 is valid aka a node was allocated) int m_HighMark = -1; internal static LayoutManager GetManager(int index) => (uint) index < s_Managers.Count ? s_Managers[index] : null; public LayoutManager(Allocator allocator) { m_Index = s_Managers.Count; s_Managers.Add(this); var nodeComponentTypes = new[] { ComponentType.Create<LayoutNodeData>(), ComponentType.Create<LayoutStyleData>(), ComponentType.Create<LayoutComputedData>(), ComponentType.Create<LayoutCacheData>(), ComponentType.Create<LayoutStyleDimensionData>(), ComponentType.Create<LayoutStyleMarginData>(), ComponentType.Create<LayoutStyleBorderData>(), }; var configComponentTypes = new[] { ComponentType.Create<LayoutConfigData>() }; m_Nodes = new LayoutDataStore(nodeComponentTypes, k_InitialNodeCapacity, allocator); m_Configs = new LayoutDataStore(configComponentTypes, k_InitialConfigCapacity, allocator); m_DefaultConfig = CreateConfig().Handle; } public void Dispose() { s_Managers[m_Index] = null; unsafe { // if m_HighMark == 0, then a single node was allocated and we need to dispose it for (var i = 0; i <= m_HighMark; i++) { var data = (LayoutNodeData*) m_Nodes.GetComponentDataPtr(i, (int)LayoutNodeDataType.Node); if (!data->Children.IsCreated) continue; data->Children.Dispose(); data->Children = new(); } } m_Nodes.Dispose(); m_Configs.Dispose(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] LayoutDataAccess GetAccess() { return new LayoutDataAccess(m_Index, m_Nodes, m_Configs); } public LayoutConfig GetDefaultConfig() { return new LayoutConfig(GetAccess(), m_DefaultConfig); } public LayoutConfig CreateConfig() { return new LayoutConfig(GetAccess(), m_Configs.Allocate(LayoutConfigData.Default)); } public void DestroyConfig(ref LayoutConfig config) { m_Configs.Free(config.Handle); config = LayoutConfig.Undefined; } public LayoutNode CreateNode() { return CreateNodeInternal(m_DefaultConfig); } public LayoutNode CreateNode(LayoutConfig config) { return CreateNodeInternal(config.Handle); } public LayoutNode CreateNode(LayoutNode source) { var node = CreateNodeInternal(source.Config.Handle); node.CopyStyle(source); return node; } LayoutNode CreateNodeInternal(LayoutHandle configHandle) { TryFreeNodes(); var handle = m_Nodes.Allocate( new LayoutNodeData { Config = configHandle , Children= new() }, LayoutStyleData.Default, LayoutComputedData.Default, LayoutCacheData.Default, LayoutStyleDimensionData.Default, LayoutStyleMarginData.Default, LayoutStyleBorderData.Default); if (handle.Index > m_HighMark) m_HighMark = handle.Index; var node = new LayoutNode(GetAccess(), handle); Debug.Assert(!GetAccess().GetNodeData(handle).Children.IsCreated, "memory is not initialized" ); return node; } void TryFreeNodes() { var @lock = false; try { Monitor.TryEnter(m_SyncRoot, ref @lock); if (@lock) { while (m_NodesToFree.Count > 0) FreeNode(m_NodesToFree.Pop()); } } finally { if (@lock) Monitor.Exit(m_SyncRoot); } } public void DestroyNode(ref LayoutNode node) { if (node.IsUndefined) return; var access = GetAccess(); // The data access has been disposed. if (!access.IsValid) return; // Destroy thread safe data as this can be called from the finalizer. ref var data = ref access.GetNodeData(node.Handle); if (data.Children.IsCreated) { data.Children.Dispose(); data.Children = new(); } // Defer the shared resource free until later. lock (m_SyncRoot) m_NodesToFree.Push(node.Handle); node = LayoutNode.Undefined; } void FreeNode(LayoutHandle handle) { ref var data = ref GetAccess().GetNodeData(handle); m_ManagedMeasureFunctions.UpdateValue(ref data.ManagedMeasureFunctionIndex, null); m_ManagedBaselineFunctions.UpdateValue(ref data.ManagedBaselineFunctionIndex, null); m_ManagedOwners.UpdateValue(ref data.ManagedOwnerIndex, null); m_Nodes.Free(handle); } public void Collect() { lock (m_SyncRoot) while (m_NodesToFree.Count > 0) FreeNode(m_NodesToFree.Pop()); } public LayoutMeasureFunction GetMeasureFunction(LayoutHandle handle) { return m_ManagedMeasureFunctions.GetValue(GetAccess().GetNodeData(handle).ManagedMeasureFunctionIndex); } public void SetMeasureFunction(LayoutHandle handle, LayoutMeasureFunction value) { if (GetAccess().GetNodeData(handle).ManagedOwnerIndex == 0) Debug.LogWarning("Settomg Measure method on a node with no Owner"); ref var index = ref GetAccess().GetNodeData(handle).ManagedMeasureFunctionIndex; m_ManagedMeasureFunctions.UpdateValue(ref index, value); } public VisualElement GetOwner(LayoutHandle handle) { //This assumes an internal behavior of the managed object store... invalid could be -1 instead if (GetAccess().GetNodeData(handle).ManagedOwnerIndex == 0) return null; // Will throw if the weak referenc is not in the list m_ManagedOwners.GetValue(GetAccess().GetNodeData(handle).ManagedOwnerIndex).TryGetTarget(out var ve); return ve; } public void SetOwner(LayoutHandle handle, VisualElement value) { if (value == null) { if (GetAccess().GetNodeData(handle).ManagedMeasureFunctionIndex != 0) Debug.LogWarning("Node with no owner has a Measure method"); if (GetAccess().GetNodeData(handle).ManagedBaselineFunctionIndex != 0) Debug.LogWarning("Node with no owner has a baseline method"); } ref var index = ref GetAccess().GetNodeData(handle).ManagedOwnerIndex; m_ManagedOwners.UpdateValue(ref index, new(value)); } public LayoutBaselineFunction GetBaselineFunction(LayoutHandle handle) { return m_ManagedBaselineFunctions.GetValue(GetAccess().GetNodeData(handle).ManagedMeasureFunctionIndex); } public void SetBaselineFunction(LayoutHandle handle, LayoutBaselineFunction value) { if (GetAccess().GetNodeData(handle).ManagedOwnerIndex == 0) Debug.LogWarning("Setting Baseline method on a node with no Owner"); ref var index = ref GetAccess().GetNodeData(handle).ManagedBaselineFunctionIndex; m_ManagedBaselineFunctions.UpdateValue(ref index, value); } }
UnityCsReference/Modules/UIElements/Core/Layout/LayoutManager.cs/0
{ "file_path": "UnityCsReference/Modules/UIElements/Core/Layout/LayoutManager.cs", "repo_id": "UnityCsReference", "token_count": 5244 }
496
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License namespace UnityEngine.UIElements.Layout; enum LayoutWrap { NoWrap, Wrap, WrapReverse, }
UnityCsReference/Modules/UIElements/Core/Layout/Model/LayoutWrap.cs/0
{ "file_path": "UnityCsReference/Modules/UIElements/Core/Layout/Model/LayoutWrap.cs", "repo_id": "UnityCsReference", "token_count": 93 }
497
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; namespace UnityEngine.UIElements { class ObjectPool<T> where T : new() { private readonly Stack<T> m_Stack = new Stack<T>(); private int m_MaxSize; internal Func<T> CreateFunc; public int maxSize { get { return m_MaxSize; } set { m_MaxSize = Math.Max(0, value); while (Size() > m_MaxSize) { Get(); } } } public ObjectPool(Func<T> CreateFunc, int maxSize = 100) { this.maxSize = maxSize; if (CreateFunc == null) { this.CreateFunc = () => new T(); } else { this.CreateFunc = CreateFunc; } } public int Size() { return m_Stack.Count; } public void Clear() { m_Stack.Clear(); } public T Get() { T evt = m_Stack.Count == 0 ? CreateFunc() : m_Stack.Pop(); return evt; } public void Release(T element) { if (m_Stack.Count > 0 && ReferenceEquals(m_Stack.Peek(), element)) Debug.LogError("Internal error. Trying to destroy object that is already released to pool."); if (m_Stack.Count < maxSize) { m_Stack.Push(element); } } } }
UnityCsReference/Modules/UIElements/Core/ObjectPool.cs/0
{ "file_path": "UnityCsReference/Modules/UIElements/Core/ObjectPool.cs", "repo_id": "UnityCsReference", "token_count": 914 }
498
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; namespace UnityEngine.UIElements.UIR { abstract class BaseElementBuilder { public abstract bool RequiresStencilMask(VisualElement ve); public void Build(MeshGenerationContext mgc) { var ve = mgc.visualElement; Debug.Assert(ve.areAncestorsAndSelfDisplayed); if (ve.shouldCutRenderChain) mgc.entryRecorder.CutRenderChain(mgc.parentEntry); bool isGroupTransform = ve.renderChainData.isGroupTransform; if (isGroupTransform) mgc.entryRecorder.PushGroupMatrix(mgc.parentEntry); bool usesSubRenderTargetMode = ve.subRenderTargetMode != VisualElement.RenderTargetMode.None; if (usesSubRenderTargetMode) mgc.entryRecorder.PushRenderTexture(mgc.parentEntry); bool changesDefaultMaterial = ve.defaultMaterial != null; if (changesDefaultMaterial) mgc.entryRecorder.PushDefaultMaterial(mgc.parentEntry, ve.defaultMaterial); bool mustPopClipping = false; if (ve.visible) { DrawVisualElementBackground(mgc); DrawVisualElementBorder(mgc); PushVisualElementClipping(mgc); mustPopClipping = true; InvokeGenerateVisualContent(mgc); } else { var isClippingWithStencil = ve.renderChainData.clipMethod == ClipMethod.Stencil; var isClippingWithScissors = ve.renderChainData.clipMethod == ClipMethod.Scissor; // Even though the element hidden, we still have to push the stencil shape or setup the scissors in case any children are visible. if (isClippingWithScissors || isClippingWithStencil) { mustPopClipping = true; PushVisualElementClipping(mgc); } } mgc.entryRecorder.DrawChildren(mgc.parentEntry); if (mustPopClipping) PopVisualElementClipping(mgc); if (changesDefaultMaterial) mgc.entryRecorder.PopDefaultMaterial(mgc.parentEntry); if (isGroupTransform) mgc.entryRecorder.PopGroupMatrix(mgc.parentEntry); if (usesSubRenderTargetMode) mgc.entryRecorder.BlitAndPopRenderTexture(mgc.parentEntry); } protected abstract void DrawVisualElementBackground(MeshGenerationContext mgc); protected abstract void DrawVisualElementBorder(MeshGenerationContext mgc); protected abstract void DrawVisualElementStencilMask(MeshGenerationContext mgc); public abstract void ScheduleMeshGenerationJobs(MeshGenerationContext mgc); void PushVisualElementClipping(MeshGenerationContext mgc) { var ve = mgc.visualElement; if (ve.renderChainData.clipMethod == ClipMethod.Scissor) { mgc.entryRecorder.PushScissors(mgc.parentEntry); } else if (ve.renderChainData.clipMethod == ClipMethod.Stencil) { mgc.entryRecorder.BeginStencilMask(mgc.parentEntry); DrawVisualElementStencilMask(mgc); mgc.entryRecorder.EndStencilMask(mgc.parentEntry); } mgc.entryRecorder.PushClippingRect(mgc.parentEntry); } static void PopVisualElementClipping(MeshGenerationContext mgc) { var ve = mgc.visualElement; mgc.entryRecorder.PopClippingRect(mgc.parentEntry); if (ve.renderChainData.clipMethod == ClipMethod.Scissor) mgc.entryRecorder.PopScissors(mgc.parentEntry); else if (ve.renderChainData.clipMethod == ClipMethod.Stencil) mgc.entryRecorder.PopStencilMask(mgc.parentEntry); } static void InvokeGenerateVisualContent(MeshGenerationContext mgc) { var ve = mgc.visualElement; Painter2D.isPainterActive = true; ve.InvokeGenerateVisualContent(mgc); Painter2D.isPainterActive = false; } } class DefaultElementBuilder : BaseElementBuilder { RenderChain m_RenderChain; public DefaultElementBuilder(RenderChain renderChain) { m_RenderChain = renderChain; } public override bool RequiresStencilMask(VisualElement ve) { return UIRUtility.IsRoundRect(ve) || UIRUtility.IsVectorImageBackground(ve); } protected override void DrawVisualElementBackground(MeshGenerationContext mgc) { var ve = mgc.visualElement; if (ve.layout.width <= UIRUtility.k_Epsilon || ve.layout.height <= UIRUtility.k_Epsilon) return; var style = ve.computedStyle; // UUM-40007 Store the cached background color. This will prevent the DynamicColor from forcing a // full repaint if the color didn't actually change. var backgroundColor = style.backgroundColor; ve.renderChainData.backgroundAlpha = backgroundColor.a; if (backgroundColor.a > UIRUtility.k_Epsilon) { // Draw solid color background var rectParams = new MeshGenerator.RectangleParams { rect = ve.rect, color = backgroundColor, colorPage = ColorPage.Init(m_RenderChain, ve.renderChainData.backgroundColorID), playmodeTintColor = ve.playModeTintColor }; MeshGenerator.GetVisualElementRadii(ve, out rectParams.topLeftRadius, out rectParams.bottomLeftRadius, out rectParams.topRightRadius, out rectParams.bottomRightRadius); MeshGenerator.AdjustBackgroundSizeForBorders(ve, ref rectParams); mgc.meshGenerator.DrawRectangle(rectParams); } var slices = new Vector4( style.unitySliceLeft, style.unitySliceTop, style.unitySliceRight, style.unitySliceBottom); var radiusParams = new MeshGenerator.RectangleParams(); MeshGenerator.GetVisualElementRadii(ve, out radiusParams.topLeftRadius, out radiusParams.bottomLeftRadius, out radiusParams.topRightRadius, out radiusParams.bottomRightRadius); var background = style.backgroundImage; if (background.texture != null || background.sprite != null || background.vectorImage != null || background.renderTexture != null) { // Draw background image (be it from a texture or a vector image) var rectParams = new MeshGenerator.RectangleParams(); float sliceScale = ve.resolvedStyle.unitySliceScale; var playModeTintColor = ve.playModeTintColor; if (background.texture != null) { rectParams = MeshGenerator.RectangleParams.MakeTextured( ve.rect, new Rect(0, 0, 1, 1), background.texture, ScaleMode.ScaleToFit, playModeTintColor); rectParams.rect = new Rect(0, 0, rectParams.texture.width, rectParams.texture.height); } else if (background.sprite != null) { ScaleMode scaleMode = BackgroundPropertyHelper.ResolveUnityBackgroundScaleMode(style.backgroundPositionX, style.backgroundPositionY, style.backgroundRepeat, style.backgroundSize, out bool validScaleMode); bool useRepeat = !validScaleMode || (scaleMode == ScaleMode.ScaleAndCrop); rectParams = MeshGenerator.RectangleParams.MakeSprite( ve.rect, new Rect(0, 0, 1, 1), background.sprite, useRepeat ? ScaleMode.StretchToFill : scaleMode, playModeTintColor, radiusParams.HasRadius(MeshBuilderNative.kEpsilon), ref slices, useRepeat); if (rectParams.texture != null) { rectParams.rect = new Rect(0, 0, background.sprite.rect.width, background.sprite.rect.height); } sliceScale *= UIElementsUtility.PixelsPerUnitScaleForElement(ve, background.sprite); } else if (background.renderTexture != null) { rectParams = MeshGenerator.RectangleParams.MakeTextured( ve.rect, new Rect(0, 0, 1, 1), background.renderTexture, ScaleMode.ScaleToFit, playModeTintColor); rectParams.rect = new Rect(0, 0, rectParams.texture.width, rectParams.texture.height); } else if (background.vectorImage != null) { ScaleMode scaleMode = BackgroundPropertyHelper.ResolveUnityBackgroundScaleMode(style.backgroundPositionX, style.backgroundPositionY, style.backgroundRepeat, style.backgroundSize, out bool validScaleMode); bool useRepeat = !validScaleMode || (scaleMode == ScaleMode.ScaleAndCrop); rectParams = MeshGenerator.RectangleParams.MakeVectorTextured( ve.rect, new Rect(0, 0, 1, 1), background.vectorImage, useRepeat ? ScaleMode.StretchToFill : scaleMode, playModeTintColor); rectParams.rect = new Rect(0, 0, rectParams.vectorImage.size.x, rectParams.vectorImage.size.y); } rectParams.topLeftRadius = radiusParams.topLeftRadius; rectParams.topRightRadius = radiusParams.topRightRadius; rectParams.bottomRightRadius = radiusParams.bottomRightRadius; rectParams.bottomLeftRadius = radiusParams.bottomLeftRadius; if (slices != Vector4.zero) { rectParams.leftSlice = Mathf.RoundToInt(slices.x); rectParams.topSlice = Mathf.RoundToInt(slices.y); rectParams.rightSlice = Mathf.RoundToInt(slices.z); rectParams.bottomSlice = Mathf.RoundToInt(slices.w); rectParams.sliceScale = sliceScale; } rectParams.color = style.unityBackgroundImageTintColor; rectParams.colorPage = ColorPage.Init(m_RenderChain, ve.renderChainData.tintColorID); rectParams.backgroundPositionX = style.backgroundPositionX; rectParams.backgroundPositionY = style.backgroundPositionY; rectParams.backgroundRepeat = style.backgroundRepeat; rectParams.backgroundSize = style.backgroundSize; MeshGenerator.AdjustBackgroundSizeForBorders(ve, ref rectParams); if (rectParams.texture != null) { mgc.meshGenerator.DrawRectangleRepeat(rectParams, ve.rect, ve.scaledPixelsPerPoint); } else if (rectParams.vectorImage != null) { mgc.meshGenerator.DrawRectangleRepeat(rectParams, ve.rect, ve.scaledPixelsPerPoint); } else { mgc.meshGenerator.DrawRectangle(rectParams); } } } protected override void DrawVisualElementBorder(MeshGenerationContext mgc) { var ve = mgc.visualElement; if (ve.layout.width >= UIRUtility.k_Epsilon && ve.layout.height >= UIRUtility.k_Epsilon) { var style = ve.resolvedStyle; if (style.borderLeftColor != Color.clear && style.borderLeftWidth > 0.0f || style.borderTopColor != Color.clear && style.borderTopWidth > 0.0f || style.borderRightColor != Color.clear && style.borderRightWidth > 0.0f || style.borderBottomColor != Color.clear && style.borderBottomWidth > 0.0f) { var borderParams = new MeshGenerator.BorderParams { rect = ve.rect, leftColor = style.borderLeftColor, topColor = style.borderTopColor, rightColor = style.borderRightColor, bottomColor = style.borderBottomColor, leftWidth = style.borderLeftWidth, topWidth = style.borderTopWidth, rightWidth = style.borderRightWidth, bottomWidth = style.borderBottomWidth, leftColorPage = ColorPage.Init(m_RenderChain, ve.renderChainData.borderLeftColorID), topColorPage = ColorPage.Init(m_RenderChain, ve.renderChainData.borderTopColorID), rightColorPage = ColorPage.Init(m_RenderChain, ve.renderChainData.borderRightColorID), bottomColorPage = ColorPage.Init(m_RenderChain, ve.renderChainData.borderBottomColorID), playmodeTintColor = ve.playModeTintColor }; MeshGenerator.GetVisualElementRadii( ve, out borderParams.topLeftRadius, out borderParams.bottomLeftRadius, out borderParams.topRightRadius, out borderParams.bottomRightRadius); mgc.meshGenerator.DrawBorder(borderParams); } } } protected override void DrawVisualElementStencilMask(MeshGenerationContext mgc) { if (UIRUtility.IsVectorImageBackground(mgc.visualElement)) // In the future, we should initially draw it into a detached context and just re-draw it here without // tessellating once more as we do here. However this is better than the previous approach which would // intercept entries (and would fail whenever more than 1 is used: e.g. with background-repeat DrawVisualElementBackground(mgc); else GenerateStencilClipEntryForRoundedRectBackground(mgc); } static void GenerateStencilClipEntryForRoundedRectBackground(MeshGenerationContext mgc) { var ve = mgc.visualElement; if (ve.layout.width <= UIRUtility.k_Epsilon || ve.layout.height <= UIRUtility.k_Epsilon) return; var resolvedStyle = ve.resolvedStyle; Vector2 radTL, radTR, radBL, radBR; MeshGenerator.GetVisualElementRadii(ve, out radTL, out radBL, out radTR, out radBR); float widthT = resolvedStyle.borderTopWidth; float widthL = resolvedStyle.borderLeftWidth; float widthB = resolvedStyle.borderBottomWidth; float widthR = resolvedStyle.borderRightWidth; var rp = new MeshGenerator.RectangleParams() { rect = ve.rect, color = Color.white, // Adjust the radius of the inner masking shape topLeftRadius = Vector2.Max(Vector2.zero, radTL - new Vector2(widthL, widthT)), topRightRadius = Vector2.Max(Vector2.zero, radTR - new Vector2(widthR, widthT)), bottomLeftRadius = Vector2.Max(Vector2.zero, radBL - new Vector2(widthL, widthB)), bottomRightRadius = Vector2.Max(Vector2.zero, radBR - new Vector2(widthR, widthB)), playmodeTintColor = ve.playModeTintColor }; // Only clip the interior shape, skipping the border rp.rect.x += widthL; rp.rect.y += widthT; rp.rect.width -= widthL + widthR; rp.rect.height -= widthT + widthB; // Skip padding, when requested if (ve.computedStyle.unityOverflowClipBox == OverflowClipBox.ContentBox) { rp.rect.x += resolvedStyle.paddingLeft; rp.rect.y += resolvedStyle.paddingTop; rp.rect.width -= resolvedStyle.paddingLeft + resolvedStyle.paddingRight; rp.rect.height -= resolvedStyle.paddingTop + resolvedStyle.paddingBottom; } mgc.meshGenerator.DrawRectangle(rp); } public override void ScheduleMeshGenerationJobs(MeshGenerationContext mgc) { mgc.meshGenerator.ScheduleJobs(mgc); if (mgc.hasPainter2D) mgc.painter2D.ScheduleJobs(mgc); } } }
UnityCsReference/Modules/UIElements/Core/Renderer/UIRElementBuilder.cs/0
{ "file_path": "UnityCsReference/Modules/UIElements/Core/Renderer/UIRElementBuilder.cs", "repo_id": "UnityCsReference", "token_count": 8681 }
499
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; using Unity.Collections; namespace UnityEngine.UIElements.UIR { // Features of this collection: // a) An amount of pooling can be specified // b) Excess is trimmed on reset // c) No copies are involved when pages are created // d) Inner pages are exposed as NativeSlices // e) Pages grow by a factor of 2x // f) Elements can be added by ref or value class NativePagedList<T> : IDisposable where T : struct { readonly int k_PoolCapacity; List<NativeArray<T>> m_Pages = new List<NativeArray<T>>(8); NativeArray<T> m_CurrentPage; int m_CurrentPageCount; public NativePagedList(int poolCapacity) { Debug.Assert(poolCapacity > 0); k_PoolCapacity = Mathf.NextPowerOfTwo(poolCapacity); } public void Add(ref T data) { // Add to the current page if there is still room if (m_CurrentPageCount < m_CurrentPage.Length) { m_CurrentPage[m_CurrentPageCount++] = data; return; } int newPageSize = m_Pages.Count > 0 ? m_CurrentPage.Length << 1 : k_PoolCapacity; m_CurrentPage = new NativeArray<T>(newPageSize, Allocator.Persistent, NativeArrayOptions.UninitializedMemory); m_Pages.Add(m_CurrentPage); m_CurrentPage[0] = data; m_CurrentPageCount = 1; } public void Add(T data) { Add(ref data); } List<NativeSlice<T>> m_Enumerator = new List<NativeSlice<T>>(8); public List<NativeSlice<T>> GetPages() { m_Enumerator.Clear(); if (m_Pages.Count > 0) { int last = m_Pages.Count - 1; for(int i = 0 ; i < last ; ++i) m_Enumerator.Add(m_Pages[i]); // Last page might not be full if(m_CurrentPageCount > 0) m_Enumerator.Add(m_CurrentPage.Slice(0, m_CurrentPageCount)); } return m_Enumerator; } public void Reset() { if (m_Pages.Count > 1) { // Keep first page alive m_CurrentPage = m_Pages[0]; // Trim excess for (int i = 1; i < m_Pages.Count; ++i) m_Pages[i].Dispose(); m_Pages.Clear(); m_Pages.Add(m_CurrentPage); } m_CurrentPageCount = 0; } #region Dispose Pattern protected bool disposed { get; private set; } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected void Dispose(bool disposing) { if (disposed) return; if (disposing) { for (int i = 0; i < m_Pages.Count; ++i) m_Pages[i].Dispose(); m_Pages.Clear(); m_CurrentPageCount = 0; } else DisposeHelper.NotifyMissingDispose(this); disposed = true; } #endregion // Dispose Pattern } }
UnityCsReference/Modules/UIElements/Core/Renderer/UIRNativePagedList.cs/0
{ "file_path": "UnityCsReference/Modules/UIElements/Core/Renderer/UIRNativePagedList.cs", "repo_id": "UnityCsReference", "token_count": 1710 }
500
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; using Unity.Profiling; namespace UnityEngine.UIElements.UIR { class VectorImageRenderInfoPool : LinkedPool<VectorImageRenderInfo> { public VectorImageRenderInfoPool() : base(() => new VectorImageRenderInfo(), vectorImageInfo => vectorImageInfo.Reset()) {} } class VectorImageRenderInfo : LinkedPoolItem<VectorImageRenderInfo> { public int useCount; public GradientRemap firstGradientRemap; public Alloc gradientSettingsAlloc; public void Reset() { useCount = 0; firstGradientRemap = null; gradientSettingsAlloc = new Alloc(); } } class GradientRemapPool : LinkedPool<GradientRemap> { public GradientRemapPool() : base(() => new GradientRemap(), gradientRemap => gradientRemap.Reset()) {} } class GradientRemap : LinkedPoolItem<GradientRemap> { public int origIndex; public int destIndex; public RectInt location; public GradientRemap next; // To avoid arrays. public TextureId atlas; public void Reset() { origIndex = 0; destIndex = 0; location = new RectInt(); atlas = TextureId.invalid; } } class VectorImageManager : IDisposable { public static List<VectorImageManager> instances = new List<VectorImageManager>(16); static ProfilerMarker s_MarkerRegister = new ProfilerMarker("UIR.VectorImageManager.Register"); static ProfilerMarker s_MarkerUnregister = new ProfilerMarker("UIR.VectorImageManager.Unregister"); readonly AtlasBase m_Atlas; Dictionary<VectorImage, VectorImageRenderInfo> m_Registered; VectorImageRenderInfoPool m_RenderInfoPool; GradientRemapPool m_GradientRemapPool; GradientSettingsAtlas m_GradientSettingsAtlas; bool m_LoggedExhaustedSettingsAtlas; public Texture2D atlas { get { return m_GradientSettingsAtlas?.atlas; }} public VectorImageManager(AtlasBase atlas) { instances.Add(this); m_Atlas = atlas; m_Registered = new Dictionary<VectorImage, VectorImageRenderInfo>(32); m_RenderInfoPool = new VectorImageRenderInfoPool(); m_GradientRemapPool = new GradientRemapPool(); m_GradientSettingsAtlas = new GradientSettingsAtlas(); } #region Dispose Pattern protected bool disposed { get; private set; } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposed) return; if (disposing) { m_Registered.Clear(); m_RenderInfoPool.Clear(); m_GradientRemapPool.Clear(); m_GradientSettingsAtlas.Dispose(); instances.Remove(this); } else UnityEngine.UIElements.DisposeHelper.NotifyMissingDispose(this); disposed = true; } #endregion // Dispose Pattern #region Reset Pattern public void Reset() { if (disposed) { DisposeHelper.NotifyDisposedUsed(this); return; } // Actually perform the reset here. m_Registered.Clear(); m_RenderInfoPool.Clear(); m_GradientRemapPool.Clear(); m_GradientSettingsAtlas.Reset(); } #endregion // Reset Pattern public void Commit() { if (disposed) { DisposeHelper.NotifyDisposedUsed(this); return; } m_GradientSettingsAtlas.Commit(); } public GradientRemap AddUser(VectorImage vi, VisualElement context) { if (disposed) { DisposeHelper.NotifyDisposedUsed(this); return null; } if (vi == null) return null; VectorImageRenderInfo renderInfo; if (m_Registered.TryGetValue(vi, out renderInfo)) ++renderInfo.useCount; else renderInfo = Register(vi, context); return renderInfo.firstGradientRemap; } public void RemoveUser(VectorImage vi) { if (disposed) { DisposeHelper.NotifyDisposedUsed(this); return; } if (vi == null) return; VectorImageRenderInfo renderInfo; if (m_Registered.TryGetValue(vi, out renderInfo)) { --renderInfo.useCount; if (renderInfo.useCount == 0) Unregister(vi, renderInfo); } } VectorImageRenderInfo Register(VectorImage vi, VisualElement context) { s_MarkerRegister.Begin(); VectorImageRenderInfo renderInfo = m_RenderInfoPool.Get(); renderInfo.useCount = 1; m_Registered[vi] = renderInfo; if (vi.settings?.Length > 0) { // We first attempt to allocate into the gradient settings atlas since it supports deallocation. int gradientCount = vi.settings.Length; Alloc alloc = m_GradientSettingsAtlas.Add(gradientCount); if (alloc.size > 0) { // Then attempt to allocate in the texture atlas. // TODO: Once the atlas actually processes returns, we should call it at some point. if (m_Atlas.TryGetAtlas(context, vi.atlas, out TextureId atlasId, out RectInt uvs)) { // Remap. GradientRemap previous = null; for (int i = 0; i < gradientCount; ++i) { // Chain. GradientRemap current = m_GradientRemapPool.Get(); if (i > 0) previous.next = current; else renderInfo.firstGradientRemap = current; previous = current; // Remap the index. current.origIndex = i; current.destIndex = (int)alloc.start + i; // Remap the rect. GradientSettings gradient = vi.settings[i]; RectInt location = gradient.location; location.x += uvs.x; location.y += uvs.y; current.location = location; current.atlas = atlasId; } // Write into the previously allocated gradient settings now that we are sure to use it. m_GradientSettingsAtlas.Write(alloc, vi.settings, renderInfo.firstGradientRemap); } else { // If the texture atlas didn't fit, keep it as a standalone custom texture, only need to remap the setting indices GradientRemap previous = null; for (int i = 0; i < gradientCount; ++i) { GradientRemap current = m_GradientRemapPool.Get(); if (i > 0) previous.next = current; else renderInfo.firstGradientRemap = current; previous = current; current.origIndex = i; current.destIndex = (int)alloc.start + i; current.atlas = TextureId.invalid; } m_GradientSettingsAtlas.Write(alloc, vi.settings, null); } } else { if (!m_LoggedExhaustedSettingsAtlas) { Debug.LogError("Exhausted max gradient settings (" + m_GradientSettingsAtlas.length + ") for atlas: " + m_GradientSettingsAtlas.atlas?.name); m_LoggedExhaustedSettingsAtlas = true; } } } s_MarkerRegister.End(); return renderInfo; } void Unregister(VectorImage vi, VectorImageRenderInfo renderInfo) { s_MarkerUnregister.Begin(); if (renderInfo.gradientSettingsAlloc.size > 0) m_GradientSettingsAtlas.Remove(renderInfo.gradientSettingsAlloc); GradientRemap remap = renderInfo.firstGradientRemap; while (remap != null) { GradientRemap next = remap.next; m_GradientRemapPool.Return(remap); remap = next; } m_Registered.Remove(vi); m_RenderInfoPool.Return(renderInfo); s_MarkerUnregister.End(); } } }
UnityCsReference/Modules/UIElements/Core/Renderer/UIRVectorImageManager.cs/0
{ "file_path": "UnityCsReference/Modules/UIElements/Core/Renderer/UIRVectorImageManager.cs", "repo_id": "UnityCsReference", "token_count": 5047 }
501
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; namespace UnityEngine.UIElements { /// <summary> /// Represents a mathematical function that describes the rate at which a numerical value changes. /// </summary> public enum EasingMode { /// <undoc/> Ease, /// <undoc/> EaseIn, /// <undoc/> EaseOut, /// <undoc/> EaseInOut, /// <undoc/> Linear, /// <undoc/> EaseInSine, /// <undoc/> EaseOutSine, /// <undoc/> EaseInOutSine, /// <undoc/> EaseInCubic, /// <undoc/> EaseOutCubic, /// <undoc/> EaseInOutCubic, /// <undoc/> EaseInCirc, /// <undoc/> EaseOutCirc, /// <undoc/> EaseInOutCirc, /// <undoc/> EaseInElastic, /// <undoc/> EaseOutElastic, /// <undoc/> EaseInOutElastic, /// <undoc/> EaseInBack, /// <undoc/> EaseOutBack, /// <undoc/> EaseInOutBack, /// <undoc/> EaseInBounce, /// <undoc/> EaseOutBounce, /// <undoc/> EaseInOutBounce } /// <summary> /// Determines how intermediate values are calculated for a transition. /// </summary> public partial struct EasingFunction : IEquatable<EasingFunction> { /// <summary> /// The value of the <see cref="EasingMode"/>. /// </summary> public EasingMode mode { get => m_Mode; set => m_Mode = value; } /// <summary> /// Creates from a <see cref="EasingMode"/>. /// </summary> public EasingFunction(EasingMode mode) { m_Mode = mode; } private EasingMode m_Mode; /// <undoc/> public static implicit operator EasingFunction(EasingMode easingMode) { return new EasingFunction(easingMode); } /// <undoc/> public static bool operator==(EasingFunction lhs, EasingFunction rhs) { return lhs.m_Mode == rhs.m_Mode; } /// <undoc/> public static bool operator!=(EasingFunction lhs, EasingFunction rhs) { return !(lhs == rhs); } /// <undoc/> public bool Equals(EasingFunction other) { return other == this; } /// <undoc/> public override bool Equals(object obj) { return obj is EasingFunction other && Equals(other); } public override string ToString() { return m_Mode.ToString(); } public override int GetHashCode() { return (int)m_Mode; } } }
UnityCsReference/Modules/UIElements/Core/Style/EasingFunction.cs/0
{ "file_path": "UnityCsReference/Modules/UIElements/Core/Style/EasingFunction.cs", "repo_id": "UnityCsReference", "token_count": 1503 }
502
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License /******************************************************************************/ // // DO NOT MODIFY // This file has been generated by the UIElementsGenerator tool // See StylePropertyCacheCsGenerator class for details // /******************************************************************************/ using System; using System.Collections.Generic; namespace UnityEngine.UIElements.StyleSheets { internal static partial class StylePropertyCache { internal static readonly Dictionary<string, string> s_PropertySyntaxCache = new Dictionary<string, string>() { {"align-content", "flex-start | flex-end | center | stretch | auto"}, {"align-items", "flex-start | flex-end | center | stretch | auto"}, {"align-self", "flex-start | flex-end | center | stretch | auto"}, {"all", "initial"}, {"background-color", "<color>"}, {"background-image", "<resource> | <url> | none"}, {"background-position", "[ [ left | center | right | top | bottom | <length-percentage> ] | [ left | center | right | <length-percentage> ] [ top | center | bottom | <length-percentage> ] | [ center | [ left | right ] <length-percentage>? ] && [ center | [ top | bottom ] <length-percentage>? ] ]"}, {"background-position-x", "[ center | [ [ left | right ]? <length-percentage>? ] ]"}, {"background-position-y", "[ center | [ [ top | bottom ]? <length-percentage>? ] ]"}, {"background-repeat", "repeat-x | repeat-y | [ repeat | space | round | no-repeat ]{1,2}"}, {"background-size", "[ <length-percentage> | auto ]{1,2} | cover | contain"}, {"border-bottom-color", "<color>"}, {"border-bottom-left-radius", "<length-percentage>"}, {"border-bottom-right-radius", "<length-percentage>"}, {"border-bottom-width", "<length>"}, {"border-color", "<color>{1,4}"}, {"border-left-color", "<color>"}, {"border-left-width", "<length>"}, {"border-radius", "[ <length-percentage> ]{1,4}"}, {"border-right-color", "<color>"}, {"border-right-width", "<length>"}, {"border-top-color", "<color>"}, {"border-top-left-radius", "<length-percentage>"}, {"border-top-right-radius", "<length-percentage>"}, {"border-top-width", "<length>"}, {"border-width", "<length>{1,4}"}, {"bottom", "<length-percentage> | auto"}, {"color", "<color>"}, {"cursor", "[ [ <resource> | <url> ] [ <integer> <integer> ]? ] | [ arrow | text | resize-vertical | resize-horizontal | link | slide-arrow | resize-up-right | resize-up-left | move-arrow | rotate-arrow | scale-arrow | arrow-plus | arrow-minus | pan | orbit | zoom | fps | split-resize-up-down | split-resize-left-right | not-allowed ]"}, {"display", "flex | none"}, {"flex", "none | [ <'flex-grow'> <'flex-shrink'>? || <'flex-basis'> ]"}, {"flex-basis", "<'width'>"}, {"flex-direction", "column | row | column-reverse | row-reverse"}, {"flex-grow", "<number>"}, {"flex-shrink", "<number>"}, {"flex-wrap", "nowrap | wrap | wrap-reverse"}, {"font-size", "<length-percentage>"}, {"height", "<length-percentage> | auto"}, {"justify-content", "flex-start | flex-end | center | space-between | space-around | space-evenly"}, {"left", "<length-percentage> | auto"}, {"letter-spacing", "<length>"}, {"margin", "[ <length-percentage> | auto ]{1,4}"}, {"margin-bottom", "<length-percentage> | auto"}, {"margin-left", "<length-percentage> | auto"}, {"margin-right", "<length-percentage> | auto"}, {"margin-top", "<length-percentage> | auto"}, {"max-height", "<length-percentage> | none"}, {"max-width", "<length-percentage> | none"}, {"min-height", "<length-percentage> | auto"}, {"min-width", "<length-percentage> | auto"}, {"opacity", "<number>"}, {"overflow", "visible | hidden | scroll"}, {"padding", "[ <length-percentage> ]{1,4}"}, {"padding-bottom", "<length-percentage>"}, {"padding-left", "<length-percentage>"}, {"padding-right", "<length-percentage>"}, {"padding-top", "<length-percentage>"}, {"position", "relative | absolute"}, {"right", "<length-percentage> | auto"}, {"rotate", "none | [ x | y | z | <number>{3} ] && <angle> | <angle>"}, {"scale", "none | <number>{1,3}"}, {"text-overflow", "clip | ellipsis"}, {"text-shadow", "<length>{2,3} && <color>?"}, {"top", "<length-percentage> | auto"}, {"transform-origin", "[ <length> | <percentage> | left | center | right | top | bottom ] | [ [ <length> | <percentage> | left | center | right ] && [ <length> | <percentage> | top | center | bottom ] ] <length>?"}, {"transition", "<single-transition>#"}, {"transition-delay", "<time>#"}, {"transition-duration", "<time>#"}, {"transition-property", "none | <single-transition-property>#"}, {"transition-timing-function", "<easing-function>#"}, {"translate", "none | [<length> | <percentage>] [ [<length> | <percentage>] <length>? ]?"}, {"-unity-background-image-tint-color", "<color>"}, {"-unity-background-scale-mode", "stretch-to-fill | scale-and-crop | scale-to-fit"}, {"-unity-font", "<resource> | <url>"}, {"-unity-font-definition", "<resource> | <url>"}, {"-unity-font-style", "normal | italic | bold | bold-and-italic"}, {"-unity-overflow-clip-box", "padding-box | content-box"}, {"-unity-paragraph-spacing", "<length>"}, {"-unity-slice-bottom", "<integer>"}, {"-unity-slice-left", "<integer>"}, {"-unity-slice-right", "<integer>"}, {"-unity-slice-scale", "<length>"}, {"-unity-slice-top", "<integer>"}, {"-unity-text-align", "upper-left | middle-left | lower-left | upper-center | middle-center | lower-center | upper-right | middle-right | lower-right"}, {"-unity-text-generator", "standard | advanced"}, {"-unity-text-outline", "<length> || <color>"}, {"-unity-text-outline-color", "<color>"}, {"-unity-text-outline-width", "<length>"}, {"-unity-text-overflow-position", "start | middle | end"}, {"visibility", "visible | hidden"}, {"white-space", "normal | nowrap"}, {"width", "<length-percentage> | auto"}, {"word-spacing", "<length>"} }; internal static readonly Dictionary<string, string> s_NonTerminalValues = new Dictionary<string, string>() { {"easing-function", "linear | <timing-function>"}, {"length-percentage", "<length> | <percentage>"}, {"single-transition", "[ none | <single-transition-property> ] || <time> || <easing-function> || <time>"}, {"single-transition-property", "all | <custom-ident>"}, {"timing-function", "ease | ease-in | ease-out | ease-in-out | ease-in-sine | ease-out-sine | ease-in-out-sine | ease-in-cubic | ease-out-cubic | ease-in-out-cubic | ease-in-circ | ease-out-circ | ease-in-out-circ | ease-in-elastic | ease-out-elastic | ease-in-out-elastic | ease-in-back | ease-out-back | ease-in-out-back | ease-in-bounce | ease-out-bounce | ease-in-out-bounce"} }; } }
UnityCsReference/Modules/UIElements/Core/Style/Generated/StylePropertyCache.cs/0
{ "file_path": "UnityCsReference/Modules/UIElements/Core/Style/Generated/StylePropertyCache.cs", "repo_id": "UnityCsReference", "token_count": 3367 }
503
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; namespace UnityEngine.UIElements { /// <summary> /// Represents a style value that can be either a <see cref="BackgroundPosition"/> or a <see cref="StyleKeyword"/>. /// </summary> public struct StyleBackgroundPosition : IStyleValue<BackgroundPosition>, IEquatable<StyleBackgroundPosition> { /// <summary> /// The <see cref="BackgroundPosition"/> value. /// </summary> public BackgroundPosition value { get { return m_Keyword == StyleKeyword.Undefined ? m_Value : default(BackgroundPosition); } set { m_Value = value; m_Keyword = StyleKeyword.Undefined; } } /// <summary> /// The style keyword. /// </summary> public StyleKeyword keyword { get { return m_Keyword; } set { m_Keyword = value; } } /// <summary> /// Creates a new StyleBackgroundPosition from either a <see cref="BackgroundPosition"/> or a <see cref="StyleKeyword"/>. /// </summary> public StyleBackgroundPosition(BackgroundPosition v) : this(v, StyleKeyword.Undefined) {} /// <summary> /// Creates a new StyleBackgroundPosition from either a <see cref="BackgroundPosition"/> or a <see cref="StyleKeyword"/>. /// </summary> public StyleBackgroundPosition(StyleKeyword keyword) : this(default(BackgroundPosition), keyword) {} internal StyleBackgroundPosition(BackgroundPosition v, StyleKeyword keyword) { m_Keyword = keyword; m_Value = v; } private BackgroundPosition m_Value; private StyleKeyword m_Keyword; /// <undoc/> public static bool operator==(StyleBackgroundPosition lhs, StyleBackgroundPosition rhs) { return lhs.m_Keyword == rhs.m_Keyword && lhs.m_Value == rhs.m_Value; } /// <undoc/> public static bool operator!=(StyleBackgroundPosition lhs, StyleBackgroundPosition rhs) { return !(lhs == rhs); } /// <undoc/> public static implicit operator StyleBackgroundPosition(StyleKeyword keyword) { return new StyleBackgroundPosition(keyword); } /// <undoc/> public static implicit operator StyleBackgroundPosition(BackgroundPosition v) { return new StyleBackgroundPosition(v); } /// <undoc/> public bool Equals(StyleBackgroundPosition other) { return other == this; } /// <undoc/> public override bool Equals(object obj) { return obj is StyleBackgroundPosition other && Equals(other); } /// <undoc/> public override int GetHashCode() { unchecked { return (m_Value.GetHashCode() * 397) ^ (int)m_Keyword; } } /// <undoc/> public override string ToString() { return this.DebugString(); } } }
UnityCsReference/Modules/UIElements/Core/Style/StyleBackgroundPosition.cs/0
{ "file_path": "UnityCsReference/Modules/UIElements/Core/Style/StyleBackgroundPosition.cs", "repo_id": "UnityCsReference", "token_count": 1445 }
504
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; namespace UnityEngine.UIElements { /// <summary> /// Style value that can be either a <see cref="Scale"/> or a <see cref="StyleKeyword"/>. /// </summary> public struct StyleScale : IStyleValue<Scale>, IEquatable<StyleScale> { /// <summary> /// The <see cref="Scale"/> value. /// </summary> public Scale value { get { // SD: Changed to provide an interpretation of Initial and Null for the debugger, that takes the StyleScale and need to display some value in the fields. // This is probably subject to change in the future. return m_Keyword switch { StyleKeyword.Undefined => m_Value, StyleKeyword.Null => Scale.None(), StyleKeyword.None => Scale.None(), StyleKeyword.Initial => Scale.Initial(), _ => throw new NotImplementedException(), }; } set { m_Value = value; m_Keyword = StyleKeyword.Undefined; } } /// <summary> /// The style keyword. /// </summary> public StyleKeyword keyword { get { return m_Keyword; } set { m_Keyword = value; } } /// <summary> /// Creates a new StyleScale from a <see cref="Scale"/>. /// </summary> public StyleScale(Scale v) : this(v, StyleKeyword.Undefined) {} /// <summary> /// Creates a new StyleScale from a <see cref="StyleKeyword"/>. /// </summary> public StyleScale(StyleKeyword keyword) : this(default(Scale), keyword) {} /// <summary> /// Creates a new StyleScale from a <see cref="Vector2"/>. /// </summary> public StyleScale(Vector2 scale) : this(new Scale(scale)) {} /// <summary> /// Creates a new StyleScale from a <see cref="Vector3"/>. /// </summary> internal StyleScale(Vector3 scale) : this(new Scale(scale)) { } internal StyleScale(Scale v, StyleKeyword keyword) { m_Keyword = keyword; m_Value = v; } private Scale m_Value; private StyleKeyword m_Keyword; /// <undoc/> public static implicit operator StyleScale(Vector2 scale) { return new Scale(scale); } /// <undoc/> public static bool operator==(StyleScale lhs, StyleScale rhs) { return lhs.m_Keyword == rhs.m_Keyword && lhs.m_Value == rhs.m_Value; } /// <undoc/> public static bool operator!=(StyleScale lhs, StyleScale rhs) { return !(lhs == rhs); } /// <undoc/> public static implicit operator StyleScale(StyleKeyword keyword) { return new StyleScale(keyword); } /// <undoc/> public static implicit operator StyleScale(Scale v) { return new StyleScale(v); } /// <undoc/> public bool Equals(StyleScale other) { return other == this; } /// <undoc/> public override bool Equals(object obj) { return obj is StyleScale other && Equals(other); } public override int GetHashCode() { unchecked { return (m_Value.GetHashCode() * 397) ^ (int)m_Keyword; } } public override string ToString() { return this.DebugString(); } } }
UnityCsReference/Modules/UIElements/Core/Style/StyleScale.cs/0
{ "file_path": "UnityCsReference/Modules/UIElements/Core/Style/StyleScale.cs", "repo_id": "UnityCsReference", "token_count": 1906 }
505
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using UnityEngine.Bindings; using UnityEngine.UIElements.StyleSheets; namespace UnityEngine.UIElements { /// <summary> /// Defines the name of a style property. /// </summary> public partial struct StylePropertyName : IEquatable<StylePropertyName> { internal StylePropertyId id { get; } private string name { get; } [VisibleToOtherModules("UnityEditor.UIBuilderModule")] internal static StylePropertyId StylePropertyIdFromString(string name) { if (StylePropertyUtil.s_NameToId.TryGetValue(name, out StylePropertyId id)) { return id; } return StylePropertyId.Unknown; } internal StylePropertyName(StylePropertyId stylePropertyId) { id = stylePropertyId; this.name = default; if (StylePropertyUtil.s_IdToName.TryGetValue(stylePropertyId, out string name)) { this.name = name; } } /// <summary> /// Initializes and returns an instance of <see cref="StylePropertyName"/> from a string. /// </summary> public StylePropertyName(string name) { id = StylePropertyIdFromString(name); this.name = default; if (id != StylePropertyId.Unknown) { this.name = name; } } /// <summary> /// Checks if the StylePropertyName is null or empty. /// </summary> /// <param name="propertyName">StylePropertyName you want to check.</param> /// <returns>True if propertyName is invalid. False otherwise.</returns> public static bool IsNullOrEmpty(StylePropertyName propertyName) { return propertyName.id == StylePropertyId.Unknown; } /// <summary> /// Determines if the StylePropertyNames are equal. /// </summary> /// <param name="lhs">First StylePropertyName.</param> /// <param name="rhs">Second StylePropertyName.</param> /// <returns>True if both StylePropertyNames are equal. False otherwise.</returns> public static bool operator==(StylePropertyName lhs, StylePropertyName rhs) { return lhs.id == rhs.id; } /// <summary> /// Determines if the StylePropertyNames are not equal. /// </summary> /// <param name="lhs">First StylePropertyName.</param> /// <param name="rhs">Second StylePropertyName.</param> /// <returns>True if the StylePropertyNames are not equal. False otherwise.</returns> public static bool operator!=(StylePropertyName lhs, StylePropertyName rhs) { return lhs.id != rhs.id; } /// <summary> /// Implicit string operator. /// </summary> /// <param name="name">Name of the property you want to create a new StylePropertyName with.</param> public static implicit operator StylePropertyName(string name) { return new StylePropertyName(name); } public override int GetHashCode() { return (int)id; } public override bool Equals(object other) { return other is StylePropertyName && Equals((StylePropertyName)other); } public bool Equals(StylePropertyName other) { return this == other; } public override string ToString() { return name; } } }
UnityCsReference/Modules/UIElements/Core/StylePropertyName.cs/0
{ "file_path": "UnityCsReference/Modules/UIElements/Core/StylePropertyName.cs", "repo_id": "UnityCsReference", "token_count": 1543 }
506
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License //#define ENABLE_STYLE_SHEET_BUILDER_LOGS using System.Collections.Generic; namespace UnityEngine.UIElements.StyleSheets { internal class StyleSheetBuilder { public struct ComplexSelectorScope : System.IDisposable { StyleSheetBuilder m_Builder; public ComplexSelectorScope(StyleSheetBuilder builder) { m_Builder = builder; } public void Dispose() { m_Builder.EndComplexSelector(); } } enum BuilderState { Init, Rule, ComplexSelector, Property } BuilderState m_BuilderState; List<float> m_Floats = new List<float>(); List<Dimension> m_Dimensions = new List<Dimension>(); List<Color> m_Colors = new List<Color>(); List<string> m_Strings = new List<string>(); List<StyleRule> m_Rules = new List<StyleRule>(); List<Object> m_Assets = new List<Object>(); List<ScalableImage> m_ScalableImages = new List<ScalableImage>(); List<StyleComplexSelector> m_ComplexSelectors = new List<StyleComplexSelector>(); List<StyleProperty> m_CurrentProperties = new List<StyleProperty>(); List<StyleValueHandle> m_CurrentValues = new List<StyleValueHandle>(); StyleComplexSelector m_CurrentComplexSelector; List<StyleSelector> m_CurrentSelectors = new List<StyleSelector>(); StyleProperty m_CurrentProperty; StyleRule m_CurrentRule; List<StyleSheet.ImportStruct> m_Imports = new List<StyleSheet.ImportStruct>(); public StyleProperty currentProperty => m_CurrentProperty; public StyleRule BeginRule(int ruleLine) { Log("Beginning rule"); Debug.Assert(m_BuilderState == BuilderState.Init); m_BuilderState = BuilderState.Rule; m_CurrentRule = new StyleRule { line = ruleLine }; return m_CurrentRule; } public ComplexSelectorScope BeginComplexSelector(int specificity) { Log("Begin complex selector with specificity " + specificity); Debug.Assert(m_BuilderState == BuilderState.Rule); m_BuilderState = BuilderState.ComplexSelector; m_CurrentComplexSelector = new StyleComplexSelector(); m_CurrentComplexSelector.specificity = specificity; m_CurrentComplexSelector.ruleIndex = m_Rules.Count; return new ComplexSelectorScope(this); } public void AddSimpleSelector(StyleSelectorPart[] parts, StyleSelectorRelationship previousRelationsip) { Debug.Assert(m_BuilderState == BuilderState.ComplexSelector); var selector = new StyleSelector(); selector.parts = parts; selector.previousRelationship = previousRelationsip; Log("Add simple selector " + selector); m_CurrentSelectors.Add(selector); } public void EndComplexSelector() { Log("Ending complex selector"); Debug.Assert(m_BuilderState == BuilderState.ComplexSelector); m_BuilderState = BuilderState.Rule; if (m_CurrentSelectors.Count > 0) { m_CurrentComplexSelector.selectors = m_CurrentSelectors.ToArray(); m_ComplexSelectors.Add(m_CurrentComplexSelector); m_CurrentSelectors.Clear(); } m_CurrentComplexSelector = null; } public StyleProperty BeginProperty(string name, int line = -1) { Log("Begin property named " + name); Debug.Assert(m_BuilderState == BuilderState.Rule); m_BuilderState = BuilderState.Property; m_CurrentProperty = new StyleProperty { name = name, line = line }; m_CurrentProperties.Add(m_CurrentProperty); return m_CurrentProperty; } public void AddImport(StyleSheet.ImportStruct importStruct) { m_Imports.Add(importStruct); } public void AddValue(float value) { RegisterValue(m_Floats, StyleValueType.Float, value); } public void AddValue(Dimension value) { RegisterValue(m_Dimensions, StyleValueType.Dimension, value); } public void AddValue(StyleValueKeyword keyword) { // for keyword we use the index to store the enum value m_CurrentValues.Add(new StyleValueHandle((int)keyword, StyleValueType.Keyword)); } public void AddValue(StyleValueFunction function) { // for function we use the index to store the enum value m_CurrentValues.Add(new StyleValueHandle((int)function, StyleValueType.Function)); } public void AddCommaSeparator() { m_CurrentValues.Add(new StyleValueHandle(0, StyleValueType.CommaSeparator)); } public void AddValue(string value, StyleValueType type) { if (type == StyleValueType.Variable) RegisterVariable(value); else RegisterValue(m_Strings, type, value); } public void AddValue(Color value) { RegisterValue(m_Colors, StyleValueType.Color, value); } public void AddValue(Object value) { RegisterValue(m_Assets, StyleValueType.AssetReference, value); } public void AddValue(ScalableImage value) { RegisterValue(m_ScalableImages, StyleValueType.ScalableImage, value); } public void EndProperty() { Log("Ending property"); Debug.Assert(m_BuilderState == BuilderState.Property); m_BuilderState = BuilderState.Rule; m_CurrentProperty.values = m_CurrentValues.ToArray(); m_CurrentProperty = null; m_CurrentValues.Clear(); } public int EndRule() { Log("Ending rule"); Debug.Assert(m_BuilderState == BuilderState.Rule); m_BuilderState = BuilderState.Init; m_CurrentRule.properties = m_CurrentProperties.ToArray(); m_Rules.Add(m_CurrentRule); m_CurrentRule = null; m_CurrentProperties.Clear(); return m_Rules.Count - 1; } public void BuildTo(StyleSheet writeTo) { Debug.Assert(m_BuilderState == BuilderState.Init); writeTo.floats = m_Floats.ToArray(); writeTo.dimensions = m_Dimensions.ToArray(); writeTo.colors = m_Colors.ToArray(); writeTo.strings = m_Strings.ToArray(); writeTo.rules = m_Rules.ToArray(); writeTo.assets = m_Assets.ToArray(); writeTo.scalableImages = m_ScalableImages.ToArray(); writeTo.complexSelectors = m_ComplexSelectors.ToArray(); writeTo.imports = m_Imports.ToArray(); if (writeTo.imports.Length > 0) writeTo.FlattenImportedStyleSheetsRecursive(); } void RegisterVariable(string value) { Log("Add variable : " + value); Debug.Assert(m_BuilderState == BuilderState.Property); int index = m_Strings.IndexOf(value); if (index < 0) { m_Strings.Add(value); index = m_Strings.Count - 1; } m_CurrentValues.Add(new StyleValueHandle(index, StyleValueType.Variable)); } void RegisterValue<T>(List<T> list, StyleValueType type, T value) { Log("Add value of type " + type + " : " + value); Debug.Assert(m_BuilderState == BuilderState.Property); list.Add(value); m_CurrentValues.Add(new StyleValueHandle(list.Count - 1, type)); } static void Log(string msg) { } } }
UnityCsReference/Modules/UIElements/Core/StyleSheets/StyleSheetBuilder.cs/0
{ "file_path": "UnityCsReference/Modules/UIElements/Core/StyleSheets/StyleSheetBuilder.cs", "repo_id": "UnityCsReference", "token_count": 3772 }
507
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; using System.Text; namespace UnityEngine.UIElements.StyleSheets { internal class StylePropertyValueParser { private string m_PropertyValue; private List<string> m_ValueList = new List<string>(); private StringBuilder m_StringBuilder = new StringBuilder(); private int m_ParseIndex = 0; public string[] Parse(string propertyValue) { m_PropertyValue = propertyValue; m_ValueList.Clear(); m_StringBuilder.Remove(0, m_StringBuilder.Length); m_ParseIndex = 0; // Split the value into parts while (m_ParseIndex < m_PropertyValue.Length) { var c = m_PropertyValue[m_ParseIndex]; switch (c) { case ' ': EatSpace(); AddValuePart(); break; case ',': EatSpace(); AddValuePart(); // comma is considered a literal value m_ValueList.Add(","); break; case '(': AppendFunction(); break; default: m_StringBuilder.Append(c); break; } ++m_ParseIndex; } var lastPart = m_StringBuilder.ToString(); if (!string.IsNullOrEmpty(lastPart)) m_ValueList.Add(lastPart); return m_ValueList.ToArray(); } private void AddValuePart() { var part = m_StringBuilder.ToString(); m_StringBuilder.Remove(0, m_StringBuilder.Length); m_ValueList.Add(part); } private void AppendFunction() { while (m_ParseIndex < m_PropertyValue.Length && m_PropertyValue[m_ParseIndex] != ')') { m_StringBuilder.Append(m_PropertyValue[m_ParseIndex]); ++m_ParseIndex; } m_StringBuilder.Append(m_PropertyValue[m_ParseIndex]); } private void EatSpace() { while (m_ParseIndex + 1 < m_PropertyValue.Length && m_PropertyValue[m_ParseIndex + 1] == ' ') { ++m_ParseIndex; } } } }
UnityCsReference/Modules/UIElements/Core/StyleSheets/Validation/StylePropertyValueParser.cs/0
{ "file_path": "UnityCsReference/Modules/UIElements/Core/StyleSheets/Validation/StylePropertyValueParser.cs", "repo_id": "UnityCsReference", "token_count": 1427 }
508
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; using Unity.Properties; using UnityEngine.Scripting; namespace UnityEngine.UIElements { static class UIElementsInitialization { [RequiredByNativeCode(optional:false)] public static void InitializeUIElementsManaged() { RegisterBuiltInPropertyBags(); } internal static void RegisterBuiltInPropertyBags() { PropertyBag.Register(new InlineStyleAccessPropertyBag()); PropertyBag.Register(new ResolvedStyleAccessPropertyBag()); PropertyBag.Register(new StyleValuePropertyBag<StyleEnum<Align>, Align>()); PropertyBag.Register(new StyleValuePropertyBag<StyleEnum<DisplayStyle>, DisplayStyle>()); PropertyBag.Register(new StyleValuePropertyBag<StyleEnum<EasingMode>, EasingMode>()); PropertyBag.Register(new StyleValuePropertyBag<StyleEnum<FlexDirection>, FlexDirection>()); PropertyBag.Register(new StyleValuePropertyBag<StyleEnum<FontStyle>, FontStyle>()); PropertyBag.Register(new StyleValuePropertyBag<StyleEnum<Justify>, Justify>()); PropertyBag.Register(new StyleValuePropertyBag<StyleEnum<Overflow>, Overflow>()); PropertyBag.Register(new StyleValuePropertyBag<StyleEnum<OverflowClipBox>, OverflowClipBox>()); PropertyBag.Register(new StyleValuePropertyBag<StyleEnum<OverflowInternal>, OverflowInternal>()); PropertyBag.Register(new StyleValuePropertyBag<StyleEnum<Position>, Position>()); PropertyBag.Register(new StyleValuePropertyBag<StyleEnum<ScaleMode>, ScaleMode>()); PropertyBag.Register(new StyleValuePropertyBag<StyleEnum<TextAnchor>, TextAnchor>()); PropertyBag.Register(new StyleValuePropertyBag<StyleEnum<TextGeneratorType>, TextGeneratorType>()); PropertyBag.Register(new StyleValuePropertyBag<StyleEnum<TextOverflow>, TextOverflow>()); PropertyBag.Register(new StyleValuePropertyBag<StyleEnum<TextOverflowPosition>, TextOverflowPosition>()); PropertyBag.Register(new StyleValuePropertyBag<StyleEnum<TransformOriginOffset>, TransformOriginOffset>()); PropertyBag.Register(new StyleValuePropertyBag<StyleEnum<Visibility>, Visibility>()); PropertyBag.Register(new StyleValuePropertyBag<StyleEnum<WhiteSpace>, WhiteSpace>()); PropertyBag.Register(new StyleValuePropertyBag<StyleEnum<Wrap>, Wrap>()); PropertyBag.Register(new StyleValuePropertyBag<StyleBackground, Background>()); PropertyBag.Register(new Length.PropertyBag()); PropertyBag.Register(new StyleValuePropertyBag<StyleBackgroundPosition, BackgroundPosition>()); PropertyBag.Register(new BackgroundPosition.PropertyBag()); PropertyBag.Register(new StyleValuePropertyBag<StyleBackgroundRepeat, BackgroundRepeat>()); PropertyBag.Register(new BackgroundRepeat.PropertyBag()); PropertyBag.Register(new StyleValuePropertyBag<StyleBackgroundSize, BackgroundSize>()); PropertyBag.Register(new BackgroundSize.PropertyBag()); PropertyBag.Register(new StyleValuePropertyBag<StyleColor, Color>()); PropertyBag.Register(new StyleValuePropertyBag<StyleCursor, Cursor>()); PropertyBag.Register(new Cursor.PropertyBag()); PropertyBag.Register(new StyleValuePropertyBag<StyleFloat, float>()); PropertyBag.Register(new StyleValuePropertyBag<StyleFont, Font>()); PropertyBag.Register(new StyleValuePropertyBag<StyleFontDefinition, FontDefinition>()); PropertyBag.Register(new FontDefinition.PropertyBag()); PropertyBag.Register(new StyleValuePropertyBag<StyleInt, int>()); PropertyBag.Register(new StyleValuePropertyBag<StyleLength, Length>()); PropertyBag.Register(new Background.PropertyBag()); PropertyBag.Register(new StyleValuePropertyBag<StyleList<EasingFunction>, List<EasingFunction>>()); PropertyBag.Register(new EasingFunction.PropertyBag()); PropertyBag.RegisterList<StyleList<EasingFunction>, EasingFunction>(); PropertyBag.Register(new StyleValuePropertyBag<StyleList<StylePropertyName>, List<StylePropertyName>>()); PropertyBag.Register(new StylePropertyName.PropertyBag()); PropertyBag.RegisterList<StyleList<StylePropertyName>, StylePropertyName>(); PropertyBag.Register(new StyleValuePropertyBag<StyleList<TimeValue>, List<TimeValue>>()); PropertyBag.Register(new TimeValue.PropertyBag()); PropertyBag.RegisterList<StyleList<TimeValue>, TimeValue>(); PropertyBag.Register(new StyleValuePropertyBag<StyleRotate, Rotate>()); PropertyBag.Register(new Rotate.PropertyBag()); PropertyBag.Register(new Angle.PropertyBag()); PropertyBag.Register(new StyleValuePropertyBag<StyleScale, Scale>()); PropertyBag.Register(new Scale.PropertyBag()); PropertyBag.Register(new StyleValuePropertyBag<StyleTransformOrigin, TransformOrigin>()); PropertyBag.Register(new TransformOrigin.PropertyBag()); PropertyBag.Register(new StyleValuePropertyBag<StyleTranslate, Translate>()); PropertyBag.Register(new Translate.PropertyBag()); PropertyBag.Register(new StyleValuePropertyBag<StyleTextShadow, TextShadow>()); PropertyBag.Register(new TextShadow.PropertyBag()); } } }
UnityCsReference/Modules/UIElements/Core/UIElementsInitialization.cs/0
{ "file_path": "UnityCsReference/Modules/UIElements/Core/UIElementsInitialization.cs", "repo_id": "UnityCsReference", "token_count": 2116 }
509
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; using UnityEngine.Bindings; namespace UnityEngine.UIElements { [Serializable] [VisibleToOtherModules("UnityEditor.UIBuilderModule")] struct UxmlNamespaceDefinition : IEquatable<UxmlNamespaceDefinition> { public static UxmlNamespaceDefinition Empty { get; } = default; public string prefix; public string resolvedNamespace; public string Export() { if (string.IsNullOrEmpty(prefix)) return $"xmlns=\"{resolvedNamespace}\""; return $"xmlns:{prefix}=\"{resolvedNamespace}\""; } public static bool operator ==(UxmlNamespaceDefinition lhs, UxmlNamespaceDefinition rhs) { return string.Compare(lhs.prefix, rhs.prefix, StringComparison.Ordinal) == 0 && string.Compare(lhs.resolvedNamespace, rhs.resolvedNamespace, StringComparison.Ordinal) == 0; } public static bool operator !=(UxmlNamespaceDefinition lhs, UxmlNamespaceDefinition rhs) { return !(lhs == rhs); } public bool Equals(UxmlNamespaceDefinition other) { return this == other; } public override bool Equals(object obj) { return obj is UxmlNamespaceDefinition other && Equals(other); } public override int GetHashCode() { return HashCode.Combine(prefix, resolvedNamespace); } } [Serializable] [VisibleToOtherModules("UnityEditor.UIBuilderModule")] internal class UxmlAsset : IUxmlAttributes { public const string NullNodeType = "null"; public UxmlAsset(string fullTypeName, UxmlNamespaceDefinition xmlNamespace = default) { m_FullTypeName = fullTypeName; m_XmlNamespace = xmlNamespace; } [SerializeField] private string m_FullTypeName; public string fullTypeName { get => m_FullTypeName; set => m_FullTypeName = value; } [SerializeField] private UxmlNamespaceDefinition m_XmlNamespace; public UxmlNamespaceDefinition xmlNamespace { get => m_XmlNamespace; set => m_XmlNamespace = value; } [SerializeField] private int m_Id; public int id { get => m_Id; set => m_Id = value; } public bool isNull => fullTypeName == NullNodeType; [SerializeField] private int m_OrderInDocument; public int orderInDocument { get => m_OrderInDocument; set => m_OrderInDocument = value; } [SerializeField] private int m_ParentId; public int parentId { get => m_ParentId; set => m_ParentId = value; } [SerializeField] private List<UxmlNamespaceDefinition> m_NamespaceDefinitions; public List<UxmlNamespaceDefinition> namespaceDefinitions => m_NamespaceDefinitions ??= new (); [SerializeField] protected List<string> m_Properties; public List<string> GetProperties() => m_Properties; int m_DirtyCount; public bool HasParent() => m_ParentId != 0; public bool HasAttribute(string attributeName) { if (m_Properties == null || m_Properties.Count <= 0) return false; for (var i = 0; i < m_Properties.Count; i += 2) { var name = m_Properties[i]; if (name == attributeName) return true; } return false; } public string GetAttributeValue(string attributeName) { TryGetAttributeValue(attributeName, out var value); return value; } public bool TryGetAttributeValue(string propertyName, out string value) { if (m_Properties == null) { value = null; return false; } for (int i = 0; i < m_Properties.Count - 1; i += 2) { if (m_Properties[i] == propertyName) { value = m_Properties[i + 1]; return true; } } value = null; return false; } public void AddUxmlNamespace(string prefix, string resolvedNamespace) { namespaceDefinitions.Add(new UxmlNamespaceDefinition { prefix = prefix, resolvedNamespace = resolvedNamespace }); } public void SetAttribute(string name, string value) { SetOrAddProperty(name, value); } public void RemoveAttribute(string attributeName) { if (m_Properties == null || m_Properties.Count <= 0) return; for (var i = 0; i < m_Properties.Count; i += 2) { var name = m_Properties[i]; if (name != attributeName) continue; m_Properties.RemoveAt(i); // Removing the name at i. m_Properties.RemoveAt(i); // Removing the value at i + 1. return; } } void SetOrAddProperty(string propertyName, string propertyValue) { if (m_Properties == null) m_Properties = new List<string>(); m_DirtyCount++; for (var i = 0; i < m_Properties.Count - 1; i += 2) { if (m_Properties[i] == propertyName) { m_Properties[i + 1] = propertyValue; return; } } m_Properties.Add(propertyName); m_Properties.Add(propertyValue); } internal int GetPropertiesDirtyCount() { return m_DirtyCount; } public override string ToString() => $"{fullTypeName}(id:{id})"; } [Serializable] [VisibleToOtherModules("UnityEditor.UIBuilderModule")] internal class UxmlObjectAsset : UxmlAsset { [SerializeField] bool m_IsField; /// <summary> /// Returns true if the field is a container for one or more UxmlObject. /// Returns false if it's itself a UxmlObject. /// </summary> public bool isField => m_IsField; public UxmlObjectAsset(string fullTypeNameOrFieldName, bool isField, UxmlNamespaceDefinition xmlNamespace = default) : base(fullTypeNameOrFieldName, xmlNamespace) { m_IsField = isField; } public override string ToString() => isField ? $"Reference: {fullTypeName} (id:{id} parent:{parentId})" : base.ToString(); } }
UnityCsReference/Modules/UIElements/Core/UXML/UxmlObjectAsset.cs/0
{ "file_path": "UnityCsReference/Modules/UIElements/Core/UXML/UxmlObjectAsset.cs", "repo_id": "UnityCsReference", "token_count": 3378 }
510
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; using System.Reflection; namespace UnityEngine.UIElements { partial class VisualElement { // Virtual methods that only react to specific event categories can use the [EventInterest] attribute to allow // UI Toolkit to skip any unrelated events. EventInterests from base classes are automatically carried over. // Applies to the "HandleEventTrickleDown" and "HandleEventBubbleUp" methods. // Since this is type-specific data, it could eventually be stored in a shared object. private readonly int m_TrickleDownHandleEventCategories; private readonly int m_BubbleUpHandleEventCategories; private int m_BubbleUpEventCallbackCategories = 0; private int m_TrickleDownEventCallbackCategories = 0; private int m_EventInterestSelfCategories = 0; private int m_CachedEventInterestParentCategories = 0; private static uint s_NextParentVersion; // The version with which this element's m_CachedNextParentWithEventInterests was computed. private uint m_NextParentCachedVersion; // The version that children need to have to use this element as their m_CachedNextParentWithEventInterests. // This should be 0 if this element has no event callback, and non-0 if it has any. private uint m_NextParentRequiredVersion; // The last computed nextParentWithEventInterests for this element. // We make sure to reset this to null when an element's panel changes, to allow the GC to do its work. // This is used in performance-critical paths so we should avoid WeakReference or GCHandle (10x slower). private VisualElement m_CachedNextParentWithEventInterests; // Call this to force any children of this element to invalidate their m_CachedNextParentWithEventInterests. // Instead of actually overwriting the children's data, which might be a costly task, we instead mark the // old shared parent as having a newer version than what the children had seen, thus forcing them to lazily // reevaluate their next parent when queried about it. private void DirtyNextParentWithEventInterests() { if (m_CachedNextParentWithEventInterests != null && m_NextParentCachedVersion == m_CachedNextParentWithEventInterests.m_NextParentRequiredVersion) { m_CachedNextParentWithEventInterests.m_NextParentRequiredVersion = ++s_NextParentVersion; } } // Makes this element appear as its children's next parent with an event callback, provided these children had // the same next parent as we did, opening a new required version for this element. // By invalidating our own nextParent's version, we also invalidate that of our children, by construction. internal void SetAsNextParentWithEventInterests() { // If I'm already a reference point for my children, then my children have nothing to retarget. if (m_NextParentRequiredVersion != 0u) return; m_NextParentRequiredVersion = ++s_NextParentVersion; // All those pointing to my old parent might now point to me, so we make their version outdated if (m_CachedNextParentWithEventInterests != null && m_NextParentCachedVersion == m_CachedNextParentWithEventInterests.m_NextParentRequiredVersion) { m_CachedNextParentWithEventInterests.m_NextParentRequiredVersion = ++s_NextParentVersion; } } // Returns the cached next parent if its cached version is up to date. internal bool GetCachedNextParentWithEventInterests(out VisualElement nextParent) { nextParent = m_CachedNextParentWithEventInterests; return nextParent != null && nextParent.m_NextParentRequiredVersion == m_NextParentCachedVersion; } // Returns or computes the exact next parent that has an event callback or HandleEvent action. // This is useful for quickly building PropagationPaths and parentEventCallbackCategories. // Panel root must always be the last parent of the chain if an element in inside a panel. internal VisualElement nextParentWithEventInterests { get { // Value is up to date, return it. This should be the most frequent case. if (GetCachedNextParentWithEventInterests(out var nextParent)) { return nextParent; } // Search for the next parent by climbing up until we find a suitable candidate for (var candidate = hierarchy.parent; candidate != null; candidate = candidate.hierarchy.parent) { // Candidate is a proper next parent if (candidate.m_NextParentRequiredVersion != 0u) { PropagateCachedNextParentWithEventInterests(candidate, candidate); return candidate; } // Candidate has a fast path to a suitable parent if (candidate.GetCachedNextParentWithEventInterests(out var candidateNextParent)) { PropagateCachedNextParentWithEventInterests(candidateNextParent, candidate); return candidateNextParent; } } // This is the top element, return null and clear the cached reference (to allow the GC to do its work) m_CachedNextParentWithEventInterests = null; return null; } } // Sets new next parent across the hierarchy between this and the new parent private void PropagateCachedNextParentWithEventInterests(VisualElement nextParent, VisualElement stopParent) { for (var ve = this; ve != stopParent; ve = ve.hierarchy.parent) { ve.m_CachedNextParentWithEventInterests = nextParent; ve.m_NextParentCachedVersion = nextParent.m_NextParentRequiredVersion; } } internal void AddEventCallbackCategories(int eventCategories, TrickleDown trickleDown) { if (trickleDown == TrickleDown.TrickleDown) m_TrickleDownEventCallbackCategories |= eventCategories; else m_BubbleUpEventCallbackCategories |= eventCategories; UpdateEventInterestSelfCategories(); } // For unit tests only internal void RemoveEventCallbackCategories(int eventCategories, TrickleDown trickleDown) { if (trickleDown == TrickleDown.TrickleDown) m_TrickleDownEventCallbackCategories &= ~eventCategories; else m_BubbleUpEventCallbackCategories &= ~eventCategories; UpdateEventInterestSelfCategories(); } // An aggregate of the EventCategory values of all the calls to RegisterCallback for this element // and overrides of HandleEventTrickleDown or HandleEventBubbleUp across this element's class hierarchy. internal int eventInterestSelfCategories => m_EventInterestSelfCategories; // Returns or computes the combined EventCategory interests of this element and all its parents. // The cached version of this property will be invalidated frequently, so this needs to be relatively cheap. internal int eventInterestParentCategories { get { if (elementPanel == null) return -1; if (isEventInterestParentCategoriesDirty) { UpdateEventInterestParentCategories(); isEventInterestParentCategoriesDirty = false; } return m_CachedEventInterestParentCategories; } } internal bool isEventInterestParentCategoriesDirty { get => (m_Flags & VisualElementFlags.EventInterestParentCategoriesDirty) == VisualElementFlags.EventInterestParentCategoriesDirty; set => m_Flags = value ? m_Flags | VisualElementFlags.EventInterestParentCategoriesDirty : m_Flags & ~VisualElementFlags.EventInterestParentCategoriesDirty; } private void UpdateEventInterestSelfCategories() { int value = m_TrickleDownHandleEventCategories | m_BubbleUpHandleEventCategories | m_TrickleDownEventCallbackCategories | m_BubbleUpEventCallbackCategories; if (m_EventInterestSelfCategories != value) { int diff = m_EventInterestSelfCategories ^ value; if ((diff & (int)~EventCategoryFlags.TargetOnly) != 0) { SetAsNextParentWithEventInterests(); IncrementVersion(VersionChangeType.EventCallbackCategories); } else { // Don't invalidate children's categories, but do maintain parentCategories >= targetCategories m_CachedEventInterestParentCategories |= value; } m_EventInterestSelfCategories = value; } } private void UpdateEventInterestParentCategories() { m_CachedEventInterestParentCategories = m_EventInterestSelfCategories; var nextParent = nextParentWithEventInterests; if (nextParent == null) return; // Recursively compute categories for next parent with event callbacks m_CachedEventInterestParentCategories |= nextParent.eventInterestParentCategories; // Fill in the gap between this and the next parent with non-identical callback info. if (hierarchy.parent != null) { for (var ve = hierarchy.parent; ve != nextParent; ve = ve.hierarchy.parent) { ve.m_CachedEventInterestParentCategories = m_CachedEventInterestParentCategories; ve.isEventInterestParentCategoriesDirty = false; } } } // Returns true if this element or any of its parents might have a RegisterCallback or a // HandleEventTrickleDown or HandleEventBubbleUp override for the given category. // Use this to skip an event that bubbles up or trickles down but with no interest from its target's hierarchy. internal bool HasParentEventInterests(EventCategory eventCategory) => 0 != (eventInterestParentCategories & (1 << (int)eventCategory)); internal bool HasParentEventInterests(int eventCategories) => 0 != (eventInterestParentCategories & eventCategories); // Returns true if this element itself has a RegisterCallback or a HandleEventTrickleDown/BubbleUp override. // Use this to skip an event that affects only its target, if the target has no interest for it. internal bool HasSelfEventInterests(EventCategory eventCategory) => 0 != (m_EventInterestSelfCategories & (1 << (int)eventCategory)); internal bool HasSelfEventInterests(int eventCategories) => 0 != (m_EventInterestSelfCategories & eventCategories); internal bool HasTrickleDownEventInterests(int eventCategories) => 0 != ((m_TrickleDownHandleEventCategories | m_TrickleDownEventCallbackCategories) & eventCategories); internal bool HasBubbleUpEventInterests(int eventCategories) => 0 != ((m_BubbleUpHandleEventCategories | m_BubbleUpEventCallbackCategories) & eventCategories); // Returns true if this element might have TrickleDown or BubbleUp callbacks on an event of the given category. // The EventDispatcher uses this to skip InvokeCallbacks. internal bool HasTrickleDownEventCallbacks(int eventCategories) => 0 != (m_TrickleDownEventCallbackCategories & eventCategories); internal bool HasBubbleUpEventCallbacks(int eventCategories) => 0 != (m_BubbleUpEventCallbackCategories & eventCategories); // Returns true if this element has HandleEventTrickleDown or HandleEventBubbleUp overrides. // The EventDispatcher uses this to skip HandleEventTrickleDown and HandleEventBubbleUp. internal bool HasTrickleDownHandleEvent(EventCategory eventCategory) => 0 != (m_TrickleDownHandleEventCategories & (1 << (int)eventCategory)); internal bool HasTrickleDownHandleEvent(int eventCategories) => 0 != (m_TrickleDownHandleEventCategories & eventCategories); internal bool HasBubbleUpHandleEvent(EventCategory eventCategory) => 0 != (m_BubbleUpHandleEventCategories & (1 << (int)eventCategory)); internal bool HasBubbleUpHandleEvent(int eventCategories) => 0 != (m_BubbleUpHandleEventCategories & eventCategories); } internal static class EventInterestReflectionUtils { // The type-specific fully-combined event interests for the 3 admissible virtual method families. private struct DefaultEventInterests { public int DefaultActionCategories; public int DefaultActionAtTargetCategories; public int HandleEventTrickleDownCategories; public int HandleEventBubbleUpCategories; } private static readonly Dictionary<Type, DefaultEventInterests> s_DefaultEventInterests = new Dictionary<Type, DefaultEventInterests>(); // Initialize this VisualElement's default categories according to its fully-resolved Type. internal static void GetDefaultEventInterests(Type elementType, out int defaultActionCategories, out int defaultActionAtTargetCategories, out int handleEventTrickleDownCategories, out int handleEventBubbleUpCategories) { if (!s_DefaultEventInterests.TryGetValue(elementType, out var categories)) { var ancestorType = elementType.BaseType; if (ancestorType != null) { GetDefaultEventInterests(ancestorType, out categories.DefaultActionCategories, out categories.DefaultActionAtTargetCategories, out categories.HandleEventTrickleDownCategories, out categories.HandleEventBubbleUpCategories); } categories.DefaultActionCategories |= ComputeDefaultEventInterests(elementType, CallbackEventHandler.ExecuteDefaultActionName) | // Disable deprecation warnings so we can access legacy method ExecuteDefaultActionDisabled #pragma warning disable 618 ComputeDefaultEventInterests(elementType, nameof(CallbackEventHandler.ExecuteDefaultActionDisabled)); #pragma warning restore 618 categories.DefaultActionAtTargetCategories |= ComputeDefaultEventInterests(elementType, CallbackEventHandler.ExecuteDefaultActionAtTargetName) | // Disable deprecation warnings so we can access legacy method ExecuteDefaultActionDisabledAtTarget #pragma warning disable 618 ComputeDefaultEventInterests(elementType, nameof(CallbackEventHandler.ExecuteDefaultActionDisabledAtTarget)); #pragma warning restore 618 categories.HandleEventTrickleDownCategories |= ComputeDefaultEventInterests(elementType, CallbackEventHandler.HandleEventTrickleDownName) | ComputeDefaultEventInterests(elementType, nameof(CallbackEventHandler.HandleEventTrickleDownDisabled)); categories.HandleEventBubbleUpCategories |= ComputeDefaultEventInterests(elementType, CallbackEventHandler.HandleEventBubbleUpName) | ComputeDefaultEventInterests(elementType, nameof(CallbackEventHandler.HandleEventBubbleUpDisabled)); s_DefaultEventInterests.Add(elementType, categories); } defaultActionCategories = categories.DefaultActionCategories; defaultActionAtTargetCategories = categories.DefaultActionAtTargetCategories; handleEventTrickleDownCategories = categories.HandleEventTrickleDownCategories; handleEventBubbleUpCategories = categories.HandleEventBubbleUpCategories; } // Compute one level of EventInterests, for the given type. Those values can be combined with that of the // derived types chain to compute the combined event interests for a given VisualElement type. private static int ComputeDefaultEventInterests(Type elementType, string methodName) { const BindingFlags flags = BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; var methodInfo = elementType.GetMethod(methodName, flags); if (methodInfo == null) return 0; bool found = false; int categories = 0; var attributes = methodInfo.GetCustomAttributes(typeof(EventInterestAttribute), false); foreach (EventInterestAttribute attribute in attributes) { found = true; if (attribute.eventTypes != null) { foreach (var eventType in attribute.eventTypes) categories |= 1 << (int)GetEventCategory(eventType); } categories |= (int)attribute.categoryFlags; } return found ? categories : -1; } private static readonly Dictionary<Type, EventCategory> s_EventCategories = new Dictionary<Type, EventCategory>(); internal static EventCategory GetEventCategory(Type eventType) { if (s_EventCategories.TryGetValue(eventType, out var category)) return category; var attributes = eventType.GetCustomAttributes(typeof(EventCategoryAttribute), true); foreach (EventCategoryAttribute attribute in attributes) { category = attribute.category; s_EventCategories.Add(eventType, category); return category; } throw new ArgumentOutOfRangeException(nameof(eventType), "Type must derive from EventBase<T>"); } } // This type is kept internal for now, but should be made public eventually, to give users access to a bit of // performance optimisation for their custom event types. /// <summary> /// Represents logical groups of events that are usually handled together by controls. /// </summary> /// <remarks> /// The <see cref="EventDispatcher"/> uses this to determine if an event needs to be fully dispatched by checking /// if its propagation path contains any callbacks to the family of events being dispatched. /// If it's determined there's no effect from the dispatching of the event, the event is likely skipped entirely. /// </remarks> /// <seealso cref="EventInterestAttribute"/> internal enum EventCategory { Default = 0, Pointer, PointerMove, PointerDown, EnterLeave, EnterLeaveWindow, Keyboard, Geometry, Style, ChangeValue, Bind, Focus, ChangePanel, StyleTransition, Navigation, Command, Tooltip, DragAndDrop, IMGUI } // Event category aggregator and useful shorthands for internal use. [Flags] internal enum EventCategoryFlags { None = 0, All = -1, // All events that have an equivalent IMGUI event TriggeredByOS = 1 << EventCategory.Pointer | 1 << EventCategory.PointerMove | 1 << EventCategory.PointerDown | 1 << EventCategory.EnterLeaveWindow | 1 << EventCategory.Keyboard | 1 << EventCategory.Command | 1 << EventCategory.DragAndDrop | 1 << EventCategory.IMGUI, // Events types that won't trigger parent callbacks TargetOnly = 1 << EventCategory.EnterLeaveWindow | 1 << EventCategory.Geometry | 1 << EventCategory.Style | 1 << EventCategory.Bind | 1 << EventCategory.ChangePanel } /// <summary> /// Options used as arguments for EventInterestAttribute when the affected method treats events in a general, /// non type-specific manner. /// </summary> public enum EventInterestOptions { /// <summary> /// Use the <see cref="Inherit"/> option when only the events needed by the base /// class are required. /// For example, a class that overrides the <see cref="CallbackEventHandler.HandleEventBubbleUp"/> /// method and checks if an enabled flag is active before calling its base.ExecuteDefaultActionAtTarget method /// would use this option. /// </summary> Inherit = EventCategoryFlags.None, /// <summary> /// Use the <see cref="EventInterestOptions.AllEventTypes"/> option when the method with an /// <see cref="EventInterestAttribute"/> doesn't have a specific filter for the event types it uses, or wants /// to receive all possible event types. /// For example, a class that overrides <see cref="CallbackEventHandler.HandleEventBubbleUp"/> and logs /// a message every time an event of any kind is received would require this option. /// </summary> AllEventTypes = EventCategoryFlags.All, } internal enum EventInterestOptionsInternal { TriggeredByOS = EventCategoryFlags.TriggeredByOS } /// <summary> /// Optional attribute on overrides of <see cref="CallbackEventHandler.HandleEventBubbleUp"/>. /// </summary> /// <remarks> /// Use this to specify all the event types that these methods require to operate. /// If an override of one of these methods doesn't have any <see cref="EventInterestAttribute"/>, UI Toolkit will /// assume that the method doesn't have enough information on what event types it needs, and will conservatively /// send all incoming events to that method. /// It is generally a good idea to use the <see cref="EventInterestAttribute"/> attribute because it allows /// UI Toolkit to perform optimizations and not calculate all the information related to an event if it isn't used /// by the method that would receive it. /// </remarks> [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] public class EventInterestAttribute : Attribute { internal Type[] eventTypes; internal EventCategoryFlags categoryFlags = EventCategoryFlags.None; /// <summary> /// Use this constructor when the affected method uses only specific event types that can easily be determined /// at compile time. /// Multiple <see cref="EventInterestAttribute"/> can be used on the same method to add more type interests. /// </summary> /// <param name="eventTypes"> /// The affected method is guaranteed to be invoked if the incoming event has any of the specified types /// in this argument. /// </param> public EventInterestAttribute(params Type[] eventTypes) { this.eventTypes = eventTypes; } /// <summary> /// Use this constructor when the affected method treats events in a general, non type-specific manner. /// See <see cref="EventInterestOptions"/> for more information on the available argument values. /// </summary> /// <param name="interests"> /// The affected method is guaranteed to be invoked if the incoming event has any of the specified types /// in this argument. /// </param> public EventInterestAttribute(EventInterestOptions interests) { categoryFlags = (EventCategoryFlags)interests; } internal EventInterestAttribute(EventInterestOptionsInternal interests) { categoryFlags = (EventCategoryFlags)interests; } } /// <summary> /// Use on any derived class of <see cref="EventBase"/> to specify what <see cref="EventCategory"/> this event /// belongs to. /// Each event belongs to exactly one category. If no attribute is used, the event will have the same category as /// its base class, or the <see cref="EventCategory.Default"/> category if no attribute exists on any base class. /// </summary> [AttributeUsage(AttributeTargets.Class)] internal class EventCategoryAttribute : Attribute { internal EventCategory category; /// <summary> /// Initializes and returns an instance of EventCategoryAttribute /// </summary> /// <param name="category">The <see cref="EventCategory"/> that this event belongs to.</param> public EventCategoryAttribute(EventCategory category) { this.category = category; } } }
UnityCsReference/Modules/UIElements/Core/VisualElementEventInterests.cs/0
{ "file_path": "UnityCsReference/Modules/UIElements/Core/VisualElementEventInterests.cs", "repo_id": "UnityCsReference", "token_count": 9572 }
511
// 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; namespace UnityEngine.UIElements { internal class VisualTreeViewDataUpdater : BaseVisualTreeUpdater { private HashSet<VisualElement> m_UpdateList = new HashSet<VisualElement>(); private HashSet<VisualElement> m_ParentList = new HashSet<VisualElement>(); private const int kMaxValidatePersistentDataCount = 5; private uint m_Version = 0; private uint m_LastVersion = 0; private static readonly string s_Description = "Update ViewData"; private static readonly ProfilerMarker s_ProfilerMarker = new ProfilerMarker(s_Description); public override ProfilerMarker profilerMarker => s_ProfilerMarker; // Only Editor panels actually do something with the ViewData of VisualElements // Skip the execution of the updater completely for Runtime UI (including when developing in the Editor) public bool enabled => panel.contextType == ContextType.Editor; public override void OnVersionChanged(VisualElement ve, VersionChangeType versionChangeType) { if (!enabled) return; if ((versionChangeType & VersionChangeType.ViewData) != VersionChangeType.ViewData) return; ++m_Version; m_UpdateList.Add(ve); PropagateToParents(ve); } public override void Update() { if (!enabled) return; if (m_Version == m_LastVersion) return; int validatePersistentDataCount = 0; while (m_LastVersion != m_Version) { m_LastVersion = m_Version; ValidateViewDataOnSubTree(visualTree, true); validatePersistentDataCount++; if (validatePersistentDataCount > kMaxValidatePersistentDataCount) { Debug.LogError("UIElements: Too many children recursively added that rely on persistent view data: " + visualTree); break; } } m_UpdateList.Clear(); m_ParentList.Clear(); } private void ValidateViewDataOnSubTree(VisualElement ve, bool enablePersistence) { // Persistence of view data is almost always enabled as long as an element has // a valid viewDataKey. The only exception is when an element is in its parent's // shadow tree, that is, not a physical child of its logical parent's contentContainer. // In this exception case, persistence is disabled on the element even if the element // does have a viewDataKey, if its logical parent does not have a viewDataKey. enablePersistence = ve.IsViewDataPersitenceSupportedOnChildren(enablePersistence); if (m_UpdateList.Contains(ve)) { m_UpdateList.Remove(ve); ve.OnViewDataReady(enablePersistence); } if (m_ParentList.Contains(ve)) { m_ParentList.Remove(ve); var childCount = ve.hierarchy.childCount; for (int i = 0; i < childCount; ++i) { ValidateViewDataOnSubTree(ve.hierarchy[i], enablePersistence); } } } private void PropagateToParents(VisualElement ve) { var parent = ve.hierarchy.parent; while (parent != null) { if (!m_ParentList.Add(parent)) { break; } parent = parent.hierarchy.parent; } } } }
UnityCsReference/Modules/UIElements/Core/VisualTreeViewDataUpdater.cs/0
{ "file_path": "UnityCsReference/Modules/UIElements/Core/VisualTreeViewDataUpdater.cs", "repo_id": "UnityCsReference", "token_count": 1735 }
512