DropdownGUI.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. using System.Collections.Generic;
  2. using UnityEngine;
  3. namespace XUnity.AutoTranslator.Plugin.Core.UI
  4. {
  5. internal class DropdownGUI<TDropdownOptionViewModel, TSelection>
  6. where TDropdownOptionViewModel : DropdownOptionViewModel<TSelection>
  7. {
  8. private const int MaxHeight = GUIUtil.RowHeight * 5;
  9. private GUIContent _noSelection;
  10. private List<TDropdownOptionViewModel> _options;
  11. private TDropdownOptionViewModel _currentSelection;
  12. private int _x;
  13. private int _y;
  14. private int _width;
  15. private bool _isShown;
  16. private Vector2 _scrollPosition;
  17. public DropdownGUI( int x, int y, int width, IEnumerable<TDropdownOptionViewModel> options )
  18. {
  19. _x = x;
  20. _y = y;
  21. _width = width;
  22. _noSelection = new GUIContent( "----", "SELECT TRANSLATOR. No translator is currently selected, which means no new translations will be performed. Please select one from the dropdown." );
  23. _options = new List<TDropdownOptionViewModel>();
  24. foreach( var item in options )
  25. {
  26. if( item.IsSelected() )
  27. {
  28. _currentSelection = item;
  29. }
  30. _options.Add( item );
  31. }
  32. }
  33. public void Select( TDropdownOptionViewModel option )
  34. {
  35. if( option.IsSelected() ) return;
  36. _currentSelection = option;
  37. _currentSelection.OnSelected?.Invoke( _currentSelection.Selection );
  38. }
  39. public void OnGUI()
  40. {
  41. bool clicked = GUI.Button( GUIUtil.R( _x, _y, _width, GUIUtil.RowHeight ), _currentSelection?.Text ?? _noSelection, _isShown ? GUIUtil.NoMarginButtonPressedStyle : GUI.skin.button );
  42. if( clicked )
  43. {
  44. _isShown = !_isShown;
  45. }
  46. if( _isShown )
  47. {
  48. _scrollPosition = ShowDropdown( _x, _y + GUIUtil.RowHeight, _width, GUI.skin.button, _scrollPosition );
  49. }
  50. if( !clicked && Event.current.isMouse )
  51. {
  52. _isShown = false;
  53. }
  54. }
  55. private Vector2 ShowDropdown( int x, int y, int width, GUIStyle buttonStyle, Vector2 scrollPosition )
  56. {
  57. var rect = GUIUtil.R( x, y, width, _options.Count * GUIUtil.RowHeight > MaxHeight ? MaxHeight : _options.Count * GUIUtil.RowHeight );
  58. GUILayout.BeginArea( rect, GUIUtil.NoSpacingBoxStyle );
  59. scrollPosition = GUILayout.BeginScrollView( scrollPosition );
  60. foreach( var option in _options )
  61. {
  62. var style = option.IsSelected() ? GUIUtil.NoMarginButtonPressedStyle : GUIUtil.NoMarginButtonStyle;
  63. GUI.enabled = option?.IsEnabled() ?? true;
  64. if( GUILayout.Button( option.Text, style ) )
  65. {
  66. Select( option );
  67. _isShown = false;
  68. }
  69. GUI.enabled = true;
  70. }
  71. GUILayout.EndScrollView();
  72. GUILayout.EndArea();
  73. return scrollPosition;
  74. }
  75. }
  76. }