Menu.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  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::showOverlay() {
  117. // Both showingOverlay and makeFocused are currently required for the overlay to be visible.
  118. this->showingOverlay = true;
  119. this->makeFocused();
  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. this->overlayLocation = memberBound.expanded(this->padding.value) + this->location.upperLeft();
  125. }
  126. bool Menu::managesChildren() {
  127. return true;
  128. }
  129. bool Menu::pointIsInsideOfOverlay(const IVector2D& pixelPosition) {
  130. return pixelPosition.x > this->overlayLocation.left() && pixelPosition.x < this->overlayLocation.right() && pixelPosition.y > this->overlayLocation.top() && pixelPosition.y < this->overlayLocation.bottom();
  131. }
  132. // TODO: Draw decorations using headImage.
  133. void Menu::drawOverlay(ImageRgbaU8& targetImage, const IVector2D &absoluteOffset) {
  134. if (this->showingOverlay) {
  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. }
  144. void Menu::changedTheme(VisualTheme newTheme) {
  145. this->headImageMethod = theme_getScalableImage(newTheme, this->subMenu ? U"MenuSub" : U"MenuTop");
  146. this->listBackgroundImageMethod = theme_getScalableImage(newTheme, U"MenuList");
  147. this->hasImages = false;
  148. }
  149. void Menu::completeAssets() {
  150. if (this->headImageMethod.methodIndex == -1) {
  151. // Work as a sub-menu if the direct parent is also a menu.
  152. this->subMenu = this->parent != nullptr && dynamic_cast<Menu*>(this->parent) != nullptr;
  153. this->headImageMethod = theme_getScalableImage(theme_getDefault(), this->subMenu ? U"MenuSub" : U"MenuTop");
  154. this->listBackgroundImageMethod = theme_getScalableImage(theme_getDefault(), U"MenuList");
  155. }
  156. if (this->font.get() == nullptr) {
  157. this->font = font_getDefault();
  158. }
  159. }
  160. void Menu::changedLocation(const IRect &oldLocation, const IRect &newLocation) {
  161. // If the component has changed dimensions then redraw the image
  162. if (oldLocation.size() != newLocation.size()) {
  163. this->hasImages = false;
  164. }
  165. }
  166. void Menu::changedAttribute(const ReadableString &name) {
  167. if (!string_caseInsensitiveMatch(name, U"Visible")) {
  168. this->hasImages = false;
  169. }
  170. }
  171. void Menu::lostFocus() {
  172. // Hide the menu when losing focus.
  173. this->showingOverlay = false;
  174. // Erase the list image to save memory.
  175. this->listBackgroundImage = OrderedImageRgbaU8();
  176. }
  177. void Menu::updateLocationEvent(const IRect& oldLocation, const IRect& newLocation) {
  178. int left = this->padding.value;
  179. int top = this->padding.value;
  180. int overlap = 3;
  181. if (this->subMenu) {
  182. left += newLocation.width() - overlap;
  183. } else {
  184. top += newLocation.height() - overlap;
  185. }
  186. int maxWidth = 80; // Minimum usable with.
  187. // Expand list with to fit child components.
  188. for (int i = 0; i < this->getChildCount(); i++) {
  189. int width = this->children[i]->getDesiredDimensions().x;
  190. if (maxWidth < width) maxWidth = width;
  191. }
  192. // Stretch out the child components to use the whole width.
  193. for (int i = 0; i < this->getChildCount(); i++) {
  194. int height = this->children[i]->getDesiredDimensions().y;
  195. this->children[i]->applyLayout(IRect(left, top, maxWidth, height));
  196. top += height + this->spacing.value;
  197. }
  198. }
  199. static void closeEntireMenu(VisualComponent* menu) {
  200. while (menu->parent != nullptr) {
  201. menu->showingOverlay = false;
  202. menu = menu->parent;
  203. }
  204. }
  205. void Menu::receiveMouseEvent(const MouseEvent& event) {
  206. int childCount = this->getChildCount();
  207. IVector2D positionFromParent = event.position;
  208. MouseEvent localEvent = event;
  209. localEvent.position -= this->location.upperLeft();
  210. if (this->showingOverlay && this->pointIsInsideOfOverlay(event.position)) {
  211. for (int i = childCount - 1; i >= 0; i--) {
  212. if (this->children[i]->pointIsInside(localEvent.position)) {
  213. this->children[i]->makeFocused();
  214. MouseEvent childEvent = localEvent;
  215. childEvent.position -= this->children[i]->location.upperLeft();
  216. this->children[i]->sendMouseEvent(childEvent, true);
  217. break;
  218. }
  219. }
  220. } else if (this->pointIsInside(event.position)) {
  221. if (childCount > 0) { // Has a list of members to open, toggle expansion when clicked.
  222. if (this->subMenu) { // Menu within another menu.
  223. // Hover to expand sub-menu's list.
  224. if (event.mouseEventType == MouseEventType::MouseMove && !this->showingOverlay) {
  225. this->showOverlay();
  226. }
  227. } else { // Top menu, which is usually placed in a toolbar.
  228. bool toggleExpansion = false;
  229. if (event.mouseEventType == MouseEventType::MouseDown) {
  230. // Toggle expansion when headImageMethod is clicked.
  231. toggleExpansion = true;
  232. } else if (event.mouseEventType == MouseEventType::MouseMove && !this->showingOverlay) {
  233. // Automatically expand hovered top-menus neighboring an opened top menu.
  234. if (this->parent != nullptr) {
  235. if (this->parent->focusComponent.get() != nullptr && this->parent->focusComponent->showingOverlay) {
  236. toggleExpansion = true;
  237. }
  238. }
  239. }
  240. if (toggleExpansion) {
  241. // Menu components with child members will toggle visibility for its list when pressed.
  242. if (this->showingOverlay) {
  243. closeEntireMenu(this);
  244. } else {
  245. this->showOverlay();
  246. }
  247. }
  248. }
  249. } else { // List item, because it has no children.
  250. // Childless menu components are treated as menu items that can be clicked to perform an action and close the menu.
  251. if (event.mouseEventType == MouseEventType::MouseDown) {
  252. // Hide overlays all the way to root.
  253. closeEntireMenu(this);
  254. // Call the event assigned to this menu item.
  255. this->callback_pressedEvent();
  256. }
  257. }
  258. // Because the main body was interacted with, the mouse events are passed on.
  259. VisualComponent::receiveMouseEvent(event);
  260. }
  261. }
  262. IVector2D Menu::getDesiredDimensions() {
  263. this->completeAssets();
  264. int widthAdder = this->padding.value * 2;
  265. int heightAdder = widthAdder;
  266. if (this->hasArrow()) {
  267. // Make extra space for the expansion arrowhead when containing a list of members.
  268. widthAdder += 24;
  269. }
  270. return IVector2D(font_getLineWidth(this->font, this->text.value) + widthAdder, font_getSize(this->font) + heightAdder);
  271. }