ModuleToolGroup.cs 3.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using UnityEngine;
  5. namespace UnityEditor.U2D.Animation
  6. {
  7. internal class ModuleToolGroup
  8. {
  9. class ToolGroupEntry
  10. {
  11. public BaseTool tool;
  12. public Action activateCallback;
  13. }
  14. class ToolGroup
  15. {
  16. public int groupId;
  17. public List<ToolGroupEntry> tools = new List<ToolGroupEntry>();
  18. public int previousToolIndex;
  19. }
  20. List<ToolGroup> m_ToolGroups = new List<ToolGroup>();
  21. public void AddToolToGroup(int groupId, BaseTool tool, Action toolActivatedCallback)
  22. {
  23. List<ToolGroupEntry> tools = null;
  24. for (int i = 0; i < m_ToolGroups.Count; ++i)
  25. {
  26. if (m_ToolGroups[i].groupId == groupId)
  27. {
  28. tools = m_ToolGroups[i].tools;
  29. }
  30. var toolIndex = m_ToolGroups[i].tools.FindIndex(x => x.tool == tool);
  31. if (toolIndex != -1)
  32. {
  33. Debug.LogError(string.Format("{0} already exist in group.", tool.name));
  34. return;
  35. }
  36. }
  37. if (tools == null)
  38. {
  39. var toolGroup = new ToolGroup()
  40. {
  41. groupId = groupId
  42. };
  43. tools = toolGroup.tools;
  44. m_ToolGroups.Add(toolGroup);
  45. }
  46. tools.Add(new ToolGroupEntry()
  47. {
  48. tool = tool,
  49. activateCallback = toolActivatedCallback
  50. });
  51. }
  52. public void ActivateTool(BaseTool tool)
  53. {
  54. var toolGroupIndex = -1;
  55. var groupTool = m_ToolGroups.FirstOrDefault(x =>
  56. {
  57. toolGroupIndex = x.tools.FindIndex(y => y.tool == tool);
  58. return toolGroupIndex >= 0;
  59. });
  60. if (groupTool != null && toolGroupIndex >= 0)
  61. {
  62. var previousTool = groupTool.previousToolIndex >= 0 ? groupTool.tools[groupTool.previousToolIndex] : null;
  63. if (tool.isActive) // we want to deactivate the tool and switch to original
  64. {
  65. tool.Deactivate();
  66. if (previousTool != null && previousTool.tool != tool && previousTool.tool != null)
  67. {
  68. previousTool.tool.Activate();
  69. groupTool.previousToolIndex = toolGroupIndex;
  70. }
  71. }
  72. else
  73. {
  74. for (int i = 0; i < groupTool.tools.Count; ++i)
  75. {
  76. var gt = groupTool.tools[i];
  77. if (gt.tool.isActive)
  78. {
  79. groupTool.previousToolIndex = i;
  80. gt.tool.Deactivate();
  81. }
  82. }
  83. tool.Activate();
  84. if (groupTool.tools[toolGroupIndex].activateCallback != null)
  85. groupTool.tools[toolGroupIndex].activateCallback();
  86. }
  87. }
  88. }
  89. }
  90. }