StyleManager.cs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using UnityEditor.Experimental;
  5. using UnityEditor.StyleSheets;
  6. using UnityEngine;
  7. using UnityEngine.Timeline;
  8. namespace UnityEditor.Timeline
  9. {
  10. static class StyleManager
  11. {
  12. static readonly StyleState[] k_StyleStates = { StyleState.any };
  13. static readonly string k_ErrorCannotFindStyle = L10n.Tr("Cannot find style {0} for {1}");
  14. static Dictionary<Type, GUIStyle> s_CustomStyles = new Dictionary<Type, GUIStyle>();
  15. static GUISkin s_CurrentSkin;
  16. public static GUIStyle UssStyleForType(Type type)
  17. {
  18. ClearCacheIfInvalid();
  19. GUIStyle cachedStyle;
  20. if (s_CustomStyles.TryGetValue(type, out cachedStyle))
  21. return cachedStyle;
  22. var style = DirectorStyles.GetGUIStyle(DirectorStyles.markerDefaultStyle);
  23. var customStyleForType = CustomStyleForType(type);
  24. if (customStyleForType != null)
  25. {
  26. if (IsStyleValid(customStyleForType))
  27. style = DirectorStyles.GetGUIStyle(customStyleForType);
  28. else
  29. Debug.LogWarningFormat(k_ErrorCannotFindStyle, customStyleForType, type.Name);
  30. }
  31. s_CustomStyles.Add(type, style);
  32. return style;
  33. }
  34. static string CustomStyleForType(Type type)
  35. {
  36. var attr = (CustomStyleAttribute)type.GetCustomAttributes(typeof(CustomStyleAttribute), true).FirstOrDefault();
  37. return attr != null ? attr.ussStyle : null;
  38. }
  39. static bool IsStyleValid(string ussStyle)
  40. {
  41. return GUISkin.current.FindStyle(ussStyle) != null || EditorResources.styleCatalog.GetStyle(ussStyle, k_StyleStates).IsValid();
  42. }
  43. static void ClearCacheIfInvalid()
  44. {
  45. if (s_CurrentSkin != GUISkin.current)
  46. s_CustomStyles.Clear();
  47. s_CurrentSkin = GUISkin.current;
  48. }
  49. }
  50. }