menu_item.dart 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. import 'dart:math' as math;
  2. import 'menu.dart';
  3. // Max value for a 16-bit unsigned integer. Chosen because it is the lowest
  4. // common denominator for menu item ids between Linux, Windows, and macOS.
  5. const int _maxMenuItemId = 65535;
  6. // Some parts of the win32 API pass data that is ambiguous about whether it is
  7. // the id of a menu item or its index in the menu. This sets a reasonable floor
  8. // to distinguish between the two by assuming that no menu will have more than
  9. // 1024 items in it.
  10. const int _minMenuItemId = 1024;
  11. int _nextMenuItemId = _minMenuItemId;
  12. _generateMenuItemId() {
  13. final newId = _nextMenuItemId;
  14. _nextMenuItemId = math.max(
  15. _minMenuItemId,
  16. (_nextMenuItemId + 1) % _maxMenuItemId,
  17. );
  18. return newId;
  19. }
  20. class MenuItem {
  21. int id = -1;
  22. String? key;
  23. String type;
  24. String? label;
  25. String? sublabel;
  26. String? toolTip;
  27. String? icon;
  28. bool? checked;
  29. bool disabled;
  30. Menu? submenu;
  31. void Function(MenuItem menuItem)? onClick;
  32. void Function(MenuItem menuItem)? onHighlight;
  33. void Function(MenuItem menuItem)? onLoseHighlight;
  34. MenuItem.separator()
  35. : id = _generateMenuItemId(),
  36. type = 'separator',
  37. disabled = true;
  38. MenuItem.submenu({
  39. this.key,
  40. this.label,
  41. this.sublabel,
  42. this.toolTip,
  43. this.icon,
  44. this.disabled = false,
  45. this.submenu,
  46. this.onClick,
  47. this.onHighlight,
  48. this.onLoseHighlight,
  49. }) : id = _generateMenuItemId(),
  50. type = 'submenu';
  51. MenuItem.checkbox({
  52. this.key,
  53. this.label,
  54. this.sublabel,
  55. this.toolTip,
  56. this.icon,
  57. required this.checked,
  58. this.disabled = false,
  59. this.onClick,
  60. this.onHighlight,
  61. this.onLoseHighlight,
  62. }) : id = _generateMenuItemId(),
  63. type = 'checkbox';
  64. MenuItem({
  65. this.key,
  66. this.type = 'normal',
  67. this.label,
  68. this.sublabel,
  69. this.toolTip,
  70. this.icon,
  71. this.checked,
  72. this.disabled = false,
  73. this.submenu,
  74. this.onClick,
  75. this.onHighlight,
  76. this.onLoseHighlight,
  77. }) : id = _generateMenuItemId();
  78. Map<String, dynamic> toJson() {
  79. return {
  80. 'id': id,
  81. 'key': key,
  82. 'type': type,
  83. 'label': label ?? '',
  84. 'toolTip': toolTip,
  85. 'icon': icon,
  86. 'checked': checked,
  87. 'disabled': disabled,
  88. 'submenu': submenu?.toJson(),
  89. }..removeWhere((key, value) => value == null);
  90. }
  91. }