Menu.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. // zlib open source license
  2. //
  3. // Copyright (c) 2018 to 2023 David Forsgren Piuva
  4. //
  5. // This software is provided 'as-is', without any express or implied
  6. // warranty. In no event will the authors be held liable for any damages
  7. // arising from the use of this software.
  8. //
  9. // Permission is granted to anyone to use this software for any purpose,
  10. // including commercial applications, and to alter it and redistribute it
  11. // freely, subject to the following restrictions:
  12. //
  13. // 1. The origin of this software must not be misrepresented; you must not
  14. // claim that you wrote the original software. If you use this software
  15. // in a product, an acknowledgment in the product documentation would be
  16. // appreciated but is not required.
  17. //
  18. // 2. Altered source versions must be plainly marked as such, and must not be
  19. // misrepresented as being the original software.
  20. //
  21. // 3. This notice may not be removed or altered from any source
  22. // distribution.
  23. #include "Menu.h"
  24. using namespace dsr;
  25. PERSISTENT_DEFINITION(Menu)
  26. static AlignedImageU8 arrowImage = image_fromAscii(
  27. "< .xX>"
  28. "<.x. >"
  29. "< XX. >"
  30. "< xXX.>"
  31. "< XX. >"
  32. "<.x. >"
  33. );
  34. void Menu::declareAttributes(StructureDefinition &target) const {
  35. VisualComponent::declareAttributes(target);
  36. target.declareAttribute(U"BackColor");
  37. target.declareAttribute(U"ForeColor");
  38. target.declareAttribute(U"Text");
  39. target.declareAttribute(U"Padding");
  40. target.declareAttribute(U"Spacing");
  41. }
  42. Persistent* Menu::findAttribute(const ReadableString &name) {
  43. if (string_caseInsensitiveMatch(name, U"Color") || string_caseInsensitiveMatch(name, U"BackColor")) {
  44. // The short Color alias refers to the back color in Buttons, because most buttons use black text.
  45. return &(this->backColor);
  46. } else if (string_caseInsensitiveMatch(name, U"ForeColor")) {
  47. return &(this->foreColor);
  48. } else if (string_caseInsensitiveMatch(name, U"Text")) {
  49. return &(this->text);
  50. } else if (string_caseInsensitiveMatch(name, U"Padding")) {
  51. return &(this->padding);
  52. } else if (string_caseInsensitiveMatch(name, U"Spacing")) {
  53. return &(this->spacing);
  54. } else {
  55. return VisualComponent::findAttribute(name);
  56. }
  57. }
  58. Menu::Menu() {}
  59. bool Menu::isContainer() const {
  60. return true;
  61. }
  62. bool Menu::hasArrow() {
  63. return this->subMenu && this->getChildCount() > 0;
  64. }
  65. static OrderedImageRgbaU8 generateHeadImage(Menu &menu, MediaMethod imageGenerator, int pressed, int width, int height, ColorRgbI32 backColor, ColorRgbI32 foreColor, const ReadableString &text, RasterFont font) {
  66. // Create a scaled image
  67. OrderedImageRgbaU8 result;
  68. component_generateImage(menu.getTheme(), imageGenerator, width, height, backColor.red, backColor.green, backColor.blue, pressed)(result);
  69. if (string_length(text) > 0) {
  70. int backWidth = image_getWidth(result);
  71. int backHeight = image_getHeight(result);
  72. int left = menu.padding.value;
  73. int top = (backHeight - font_getSize(font)) / 2;
  74. if (pressed) {
  75. top += 1;
  76. }
  77. // Print the text
  78. font_printLine(result, font, text, IVector2D(left, top), ColorRgbaI32(foreColor, 255));
  79. // Draw the arrow
  80. if (menu.hasArrow()) {
  81. int arrowWidth = image_getWidth(arrowImage);
  82. int arrowHeight = image_getHeight(arrowImage);
  83. int arrowLeft = backWidth - arrowWidth - 4;
  84. int arrowTop = (backHeight - arrowHeight) / 2;
  85. draw_silhouette(result, arrowImage, ColorRgbaI32(foreColor, 255), arrowLeft, arrowTop);
  86. }
  87. }
  88. return result;
  89. }
  90. void Menu::generateGraphics() {
  91. int headWidth = this->location.width();
  92. int headHeight = this->location.height();
  93. if (headWidth < 1) { headWidth = 1; }
  94. if (headHeight < 1) { headHeight = 1; }
  95. if (!this->hasImages) {
  96. completeAssets();
  97. this->imageUp = generateHeadImage(*this, this->headImageMethod, 0, headWidth, headHeight, this->backColor.value, this->foreColor.value, this->text.value, this->font);
  98. this->imageDown = generateHeadImage(*this, this->headImageMethod, 0, headWidth, headHeight, ColorRgbI32(0, 0, 0), ColorRgbI32(255, 255, 255), this->text.value, this->font);
  99. this->hasImages = true;
  100. }
  101. }
  102. // Fill the listBackgroundImageMethod with a solid color
  103. void Menu::drawSelf(ImageRgbaU8& targetImage, const IRect &relativeLocation) {
  104. this->generateGraphics();
  105. draw_alphaFilter(targetImage, this->showingOverlay() ? this->imageDown : this->imageUp, relativeLocation.left(), relativeLocation.top());
  106. }
  107. void Menu::generateBackground() {
  108. if (!image_exists(this->listBackgroundImage)) {
  109. int listWidth = this->overlayLocation.width();
  110. int listHeight = this->overlayLocation.height();
  111. if (listWidth < 1) { listWidth = 1; }
  112. if (listHeight < 1) { listHeight = 1; }
  113. component_generateImage(this->theme, this->listBackgroundImageMethod, listWidth, listHeight, this->backColor.value.red, this->backColor.value.green, this->backColor.value.blue)(this->listBackgroundImage);
  114. }
  115. }
  116. void Menu::createOverlay() {
  117. if (!this->showingOverlay()) {
  118. this->showOverlay();
  119. this->makeFocused(); // Focus on the current menu path to make others lose focus.
  120. IRect memberBound = this->children[0]->location;
  121. for (int i = 1; i < this->getChildCount(); i++) {
  122. memberBound = IRect::merge(memberBound, this->children[i]->location);
  123. }
  124. // Calculate the new list bound.
  125. this->overlayLocation = memberBound.expanded(this->padding.value) + this->location.upperLeft();
  126. }
  127. }
  128. bool Menu::managesChildren() {
  129. return true;
  130. }
  131. bool Menu::pointIsInsideOfOverlay(const IVector2D& pixelPosition) {
  132. return pixelPosition.x > this->overlayLocation.left() && pixelPosition.x < this->overlayLocation.right() && pixelPosition.y > this->overlayLocation.top() && pixelPosition.y < this->overlayLocation.bottom();
  133. }
  134. void Menu::drawOverlay(ImageRgbaU8& targetImage, const IVector2D &absoluteOffset) {
  135. this->generateBackground();
  136. // TODO: Let the theme select between solid and alpha filtered drawing.
  137. IVector2D overlayOffset = absoluteOffset + this->overlayLocation.upperLeft();
  138. draw_copy(targetImage, this->listBackgroundImage, overlayOffset.x, overlayOffset.y);
  139. for (int i = 0; i < this->getChildCount(); i++) {
  140. this->children[i]->draw(targetImage, absoluteOffset + this->location.upperLeft());
  141. }
  142. }
  143. void Menu::changedTheme(VisualTheme newTheme) {
  144. this->headImageMethod = theme_getScalableImage(newTheme, this->subMenu ? U"MenuSub" : U"MenuTop");
  145. this->listBackgroundImageMethod = theme_getScalableImage(newTheme, U"MenuList");
  146. this->hasImages = false;
  147. }
  148. void Menu::completeAssets() {
  149. if (this->headImageMethod.methodIndex == -1) {
  150. // Work as a sub-menu if the direct parent is also a menu.
  151. this->subMenu = this->parent != nullptr && dynamic_cast<Menu*>(this->parent) != nullptr;
  152. this->headImageMethod = theme_getScalableImage(theme_getDefault(), this->subMenu ? U"MenuSub" : U"MenuTop");
  153. this->listBackgroundImageMethod = theme_getScalableImage(theme_getDefault(), U"MenuList");
  154. }
  155. if (this->font.get() == nullptr) {
  156. this->font = font_getDefault();
  157. }
  158. }
  159. void Menu::changedLocation(const IRect &oldLocation, const IRect &newLocation) {
  160. // If the component has changed dimensions then redraw the image
  161. if (oldLocation.size() != newLocation.size()) {
  162. this->hasImages = false;
  163. }
  164. }
  165. void Menu::changedAttribute(const ReadableString &name) {
  166. if (!string_caseInsensitiveMatch(name, U"Visible")) {
  167. this->hasImages = false;
  168. }
  169. VisualComponent::changedAttribute(name);
  170. }
  171. void Menu::updateStateEvent(ComponentState oldState, ComponentState newState) {
  172. // If no longer having any type of focus, hide the overlay.
  173. if ((oldState & componentState_focus) && !(newState & componentState_focus)) {
  174. // Hide the menu when losing focus.
  175. this->hideOverlay();
  176. // State notifications are not triggered from within the same notification, so that one can handle all the updates safely in the desired order.
  177. this->listBackgroundImage = OrderedImageRgbaU8();
  178. }
  179. if (!(newState & componentState_showingOverlayDirect)) {
  180. // Clean up the background image to save memory and allow it to be regenerated in another size later.
  181. this->listBackgroundImage = OrderedImageRgbaU8();
  182. }
  183. }
  184. void Menu::updateLocationEvent(const IRect& oldLocation, const IRect& newLocation) {
  185. int left = this->padding.value;
  186. int top = this->padding.value;
  187. int overlap = 3;
  188. if (this->subMenu) {
  189. left += newLocation.width() - overlap;
  190. } else {
  191. top += newLocation.height() - overlap;
  192. }
  193. int maxWidth = 80; // Minimum usable with.
  194. // Expand list with to fit child components.
  195. for (int i = 0; i < this->getChildCount(); i++) {
  196. int width = this->children[i]->getDesiredDimensions().x;
  197. if (maxWidth < width) maxWidth = width;
  198. }
  199. // Stretch out the child components to use the whole width.
  200. for (int i = 0; i < this->getChildCount(); i++) {
  201. int height = this->children[i]->getDesiredDimensions().y;
  202. this->children[i]->applyLayout(IRect(left, top, maxWidth, height));
  203. top += height + this->spacing.value;
  204. }
  205. }
  206. static void closeEntireMenu(VisualComponent* menu) {
  207. while (menu->parent != nullptr) {
  208. // Hide the menu when closing the menu. Notifications to updateStateEvent will do the proper cleanup for each component's type.
  209. menu->hideOverlay();
  210. // Move on to the parent component.
  211. menu = menu->parent;
  212. }
  213. }
  214. void Menu::receiveMouseEvent(const MouseEvent& event) {
  215. int childCount = this->getChildCount();
  216. IVector2D positionFromParent = event.position;
  217. MouseEvent localEvent = event;
  218. localEvent.position -= this->location.upperLeft();
  219. if (this->showingOverlay() && this->pointIsInsideOfOverlay(event.position)) {
  220. for (int i = childCount - 1; i >= 0; i--) {
  221. if (this->children[i]->pointIsInside(localEvent.position)) {
  222. this->children[i]->makeFocused();
  223. MouseEvent childEvent = localEvent;
  224. childEvent.position -= this->children[i]->location.upperLeft();
  225. this->children[i]->sendMouseEvent(childEvent, true);
  226. break;
  227. }
  228. }
  229. } else if (this->pointIsInside(event.position)) {
  230. if (childCount > 0) { // Has a list of members to open, toggle expansion when clicked.
  231. if (this->subMenu) { // Menu within another menu.
  232. // Hover to expand sub-menu's list.
  233. if (event.mouseEventType == MouseEventType::MouseMove && !this->showingOverlay()) {
  234. this->createOverlay();
  235. }
  236. } else { // Top menu, which is usually placed in a toolbar.
  237. bool toggleExpansion = false;
  238. if (event.mouseEventType == MouseEventType::MouseDown) {
  239. // Toggle expansion when headImageMethod is clicked.
  240. toggleExpansion = true;
  241. } else if (event.mouseEventType == MouseEventType::MouseMove && !this->showingOverlay()) {
  242. // Automatically expand hovered top-menus neighboring an opened top menu.
  243. if (this->parent != nullptr) {
  244. VisualComponent *toolbar = this->parent;
  245. if (toolbar->ownsFocus()) {
  246. for (int i = 0; i < toolbar->getChildCount(); i++) {
  247. if (toolbar->children[i]->showingOverlay()) {
  248. toggleExpansion = true;
  249. break;
  250. }
  251. }
  252. }
  253. }
  254. }
  255. if (toggleExpansion) {
  256. // Menu components with child members will toggle visibility for its list when pressed.
  257. if (this->showingOverlay()) {
  258. closeEntireMenu(this);
  259. } else {
  260. this->createOverlay();
  261. }
  262. }
  263. }
  264. } else { // List item, because it has no children.
  265. // Childless menu components are treated as menu items that can be clicked to perform an action and close the menu.
  266. if (event.mouseEventType == MouseEventType::MouseDown) {
  267. // Hide overlays all the way to root.
  268. closeEntireMenu(this);
  269. // Call the event assigned to this menu item.
  270. this->callback_pressedEvent();
  271. }
  272. }
  273. // Because the main body was interacted with, the mouse events are passed on.
  274. VisualComponent::receiveMouseEvent(event);
  275. }
  276. }
  277. IVector2D Menu::getDesiredDimensions() {
  278. this->completeAssets();
  279. int widthAdder = this->padding.value * 2;
  280. int heightAdder = widthAdder;
  281. if (this->hasArrow()) {
  282. // Make extra space for the expansion arrowhead when containing a list of members.
  283. widthAdder += 24;
  284. }
  285. return IVector2D(font_getLineWidth(this->font, this->text.value) + widthAdder, font_getSize(this->font) + heightAdder);
  286. }