FR2_TabView.cs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. using System;
  2. using System.Collections.Generic;
  3. using UnityEditor;
  4. using UnityEngine;
  5. namespace vietlabs.fr2
  6. {
  7. public class DrawCallback
  8. {
  9. public Action BeforeDraw;
  10. public Action AfterDraw;
  11. }
  12. public class FR2_TabView
  13. {
  14. public int current;
  15. public GUIContent[] labels;
  16. public IWindow window;
  17. public Action onTabChange;
  18. public DrawCallback callback;
  19. public bool canDeselectAll; // can there be no active tabs
  20. public FR2_TabView(IWindow w, bool canDeselectAll)
  21. {
  22. this.window = w;
  23. this.canDeselectAll = canDeselectAll;
  24. }
  25. public bool DrawLayout()
  26. {
  27. bool result = false;
  28. GUILayout.BeginHorizontal(EditorStyles.toolbar);
  29. {
  30. if (callback != null && callback.BeforeDraw != null) callback.BeforeDraw();
  31. for (var i = 0; i < labels.Length; i++)
  32. {
  33. var isActive = (i == current);
  34. var lb = labels[i];
  35. var clicked = (lb.image != null)
  36. ? GUI2.ToolbarToggle(ref isActive, lb.image, Vector2.zero, lb.tooltip)
  37. : GUI2.Toggle(ref isActive, lb, EditorStyles.toolbarButton);
  38. if (!clicked) continue;
  39. current = (!isActive && canDeselectAll) ? -1 : i;
  40. result = true;
  41. if (onTabChange != null) onTabChange();
  42. if (window == null) continue;
  43. window.OnSelectionChange(); // force refresh tabs
  44. window.WillRepaint = true;
  45. }
  46. if (callback != null && callback.AfterDraw != null) callback.AfterDraw();
  47. }
  48. GUILayout.EndHorizontal();
  49. return result;
  50. }
  51. public static FR2_TabView FromEnum(Type enumType, IWindow w, bool canDeselectAll = false)
  52. {
  53. var values = Enum.GetValues(enumType);
  54. var labels = new List<GUIContent>();
  55. foreach (var item in values)
  56. {
  57. labels.Add(new GUIContent(item.ToString()));
  58. }
  59. return new FR2_TabView( w, canDeselectAll) {current = 0, labels = labels.ToArray()};
  60. }
  61. public static GUIContent GetGUIContent(object tex)
  62. {
  63. if (tex is GUIContent) return (GUIContent) tex;
  64. if (tex is Texture) return new GUIContent((Texture)tex);
  65. if (tex is string) return new GUIContent((string)tex);
  66. return GUIContent.none;
  67. }
  68. public static FR2_TabView Create(IWindow w, bool canDeselectAll = false, params object[] titles)
  69. {
  70. var labels = new List<GUIContent>();
  71. foreach (var item in titles)
  72. {
  73. labels.Add(GetGUIContent(item));
  74. }
  75. return new FR2_TabView(w, canDeselectAll) {current = 0, labels = labels.ToArray()};
  76. }
  77. }
  78. }