Menu.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  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. target.declareAttribute(U"HeadClass");
  42. target.declareAttribute(U"ListClass");
  43. }
  44. Persistent* Menu::findAttribute(const ReadableString &name) {
  45. if (string_caseInsensitiveMatch(name, U"Color") || string_caseInsensitiveMatch(name, U"BackColor")) {
  46. // The short Color alias refers to the back color in Buttons, because most buttons use black text.
  47. return &(this->backColor);
  48. } else if (string_caseInsensitiveMatch(name, U"ForeColor")) {
  49. return &(this->foreColor);
  50. } else if (string_caseInsensitiveMatch(name, U"Text")) {
  51. return &(this->text);
  52. } else if (string_caseInsensitiveMatch(name, U"Padding")) {
  53. return &(this->padding);
  54. } else if (string_caseInsensitiveMatch(name, U"Spacing")) {
  55. return &(this->spacing);
  56. } else if (string_caseInsensitiveMatch(name, U"HeadClass") || string_caseInsensitiveMatch(name, U"Class")) {
  57. // Class is an alias for HeadClass.
  58. return &(this->headClass);
  59. } else if (string_caseInsensitiveMatch(name, U"ListClass")) {
  60. return &(this->listClass);
  61. } else {
  62. return VisualComponent::findAttribute(name);
  63. }
  64. }
  65. Menu::Menu() {}
  66. bool Menu::isContainer() const {
  67. return true;
  68. }
  69. bool Menu::hasArrow() {
  70. return this->subMenu && this->getChildCount() > 0;
  71. }
  72. static OrderedImageRgbaU8 generateHeadImage(Menu &menu, MediaMethod imageGenerator, int pressed, int width, int height, ColorRgbI32 backColor, ColorRgbI32 foreColor, const ReadableString &text, RasterFont font) {
  73. // Create a scaled image
  74. OrderedImageRgbaU8 result;
  75. component_generateImage(menu.getTheme(), imageGenerator, width, height, backColor.red, backColor.green, backColor.blue, pressed)(result);
  76. if (string_length(text) > 0) {
  77. int backWidth = image_getWidth(result);
  78. int backHeight = image_getHeight(result);
  79. int left = menu.padding.value;
  80. int top = (backHeight - font_getSize(font)) / 2;
  81. if (pressed) {
  82. top += 1;
  83. }
  84. // Print the text
  85. font_printLine(result, font, text, IVector2D(left, top), ColorRgbaI32(foreColor, 255));
  86. // Draw the arrow
  87. if (menu.hasArrow()) {
  88. int arrowWidth = image_getWidth(arrowImage);
  89. int arrowHeight = image_getHeight(arrowImage);
  90. int arrowLeft = backWidth - arrowWidth - 4;
  91. int arrowTop = (backHeight - arrowHeight) / 2;
  92. draw_silhouette(result, arrowImage, ColorRgbaI32(foreColor, 255), arrowLeft, arrowTop);
  93. }
  94. }
  95. return result;
  96. }
  97. void Menu::generateGraphics() {
  98. int headWidth = this->location.width();
  99. int headHeight = this->location.height();
  100. if (headWidth < 1) { headWidth = 1; }
  101. if (headHeight < 1) { headHeight = 1; }
  102. if (!this->hasImages) {
  103. completeAssets();
  104. this->imageUp = generateHeadImage(*this, this->headImageMethod, 0, headWidth, headHeight, this->backColor.value, this->foreColor.value, this->text.value, this->font);
  105. this->imageDown = generateHeadImage(*this, this->headImageMethod, 0, headWidth, headHeight, ColorRgbI32(0, 0, 0), ColorRgbI32(255, 255, 255), this->text.value, this->font);
  106. this->hasImages = true;
  107. }
  108. }
  109. // Fill the listBackgroundImageMethod with a solid color
  110. void Menu::drawSelf(ImageRgbaU8& targetImage, const IRect &relativeLocation) {
  111. this->generateGraphics();
  112. if (this->menuHead_filter == 1) {
  113. draw_alphaFilter(targetImage, this->showingOverlay() ? this->imageDown : this->imageUp, relativeLocation.left(), relativeLocation.top());
  114. } else {
  115. draw_copy(targetImage, this->showingOverlay() ? this->imageDown : this->imageUp, relativeLocation.left(), relativeLocation.top());
  116. }
  117. }
  118. void Menu::generateBackground() {
  119. if (!image_exists(this->listBackgroundImage)) {
  120. int listWidth = this->overlayLocation.width();
  121. int listHeight = this->overlayLocation.height();
  122. if (listWidth < 1) { listWidth = 1; }
  123. if (listHeight < 1) { listHeight = 1; }
  124. component_generateImage(this->theme, this->listBackgroundImageMethod, listWidth, listHeight, this->backColor.value.red, this->backColor.value.green, this->backColor.value.blue)(this->listBackgroundImage);
  125. }
  126. }
  127. void Menu::createOverlay() {
  128. if (!this->showingOverlay()) {
  129. this->showOverlay();
  130. this->makeFocused(); // Focus on the current menu path to make others lose focus.
  131. IRect memberBound = this->children[0]->location;
  132. for (int i = 1; i < this->getChildCount(); i++) {
  133. memberBound = IRect::merge(memberBound, this->children[i]->location);
  134. }
  135. // Calculate the new list bound.
  136. this->overlayLocation = memberBound.expanded(this->padding.value) + this->location.upperLeft();
  137. }
  138. }
  139. bool Menu::managesChildren() {
  140. return true;
  141. }
  142. bool Menu::pointIsInsideOfOverlay(const IVector2D& pixelPosition) {
  143. return pixelPosition.x > this->overlayLocation.left() && pixelPosition.x < this->overlayLocation.right() && pixelPosition.y > this->overlayLocation.top() && pixelPosition.y < this->overlayLocation.bottom();
  144. }
  145. void Menu::drawOverlay(ImageRgbaU8& targetImage, const IVector2D &absoluteOffset) {
  146. this->generateBackground();
  147. IVector2D overlayOffset = absoluteOffset + this->overlayLocation.upperLeft();
  148. if (this->menuList_filter == 1) {
  149. draw_alphaFilter(targetImage, this->listBackgroundImage, overlayOffset.x, overlayOffset.y);
  150. } else {
  151. draw_copy(targetImage, this->listBackgroundImage, overlayOffset.x, overlayOffset.y);
  152. }
  153. for (int i = 0; i < this->getChildCount(); i++) {
  154. this->children[i]->draw(targetImage, absoluteOffset + this->location.upperLeft());
  155. }
  156. }
  157. void Menu::loadTheme(const VisualTheme &theme) {
  158. // Is it a sub-menu or top menu?
  159. this->subMenu = this->parent != nullptr && dynamic_cast<Menu*>(this->parent) != nullptr;
  160. this->finalHeadClass = theme_selectClass(theme, this->headClass.value, this->subMenu ? U"MenuSub" : U"MenuTop");
  161. this->finalListClass = theme_selectClass(theme, this->listClass.value, U"MenuList");
  162. this->headImageMethod = theme_getScalableImage(theme, this->finalHeadClass);
  163. this->listBackgroundImageMethod = theme_getScalableImage(theme, this->finalListClass);
  164. // Ask the theme which parts should be drawn using alpha filtering, and fall back on solid drawing.
  165. this->menuHead_filter = theme_getInteger(theme, this->finalHeadClass, U"Filter", 0);
  166. this->menuList_filter = theme_getInteger(theme, this->finalListClass, U"Filter", 0);
  167. }
  168. void Menu::changedTheme(VisualTheme newTheme) {
  169. this->loadTheme(newTheme);
  170. this->hasImages = false;
  171. }
  172. void Menu::completeAssets() {
  173. if (this->headImageMethod.methodIndex == -1) {
  174. this->loadTheme(theme_getDefault());
  175. }
  176. if (this->font.get() == nullptr) {
  177. this->font = font_getDefault();
  178. }
  179. }
  180. void Menu::changedLocation(const IRect &oldLocation, const IRect &newLocation) {
  181. // If the component has changed dimensions then redraw the image
  182. if (oldLocation.size() != newLocation.size()) {
  183. this->hasImages = false;
  184. }
  185. }
  186. void Menu::changedAttribute(const ReadableString &name) {
  187. if (string_caseInsensitiveMatch(name, U"HeadClass")
  188. || string_caseInsensitiveMatch(name, U"ListClass")) {
  189. // Update from the theme if a theme class has changed.
  190. this->changedTheme(this->getTheme());
  191. } else if (!string_caseInsensitiveMatch(name, U"Visible")) {
  192. this->hasImages = false;
  193. }
  194. VisualComponent::changedAttribute(name);
  195. }
  196. void Menu::updateStateEvent(ComponentState oldState, ComponentState newState) {
  197. // If no longer having any type of focus, hide the overlay.
  198. if ((oldState & componentState_focus) && !(newState & componentState_focus)) {
  199. // Hide the menu when losing focus.
  200. this->hideOverlay();
  201. // State notifications are not triggered from within the same notification, so that one can handle all the updates safely in the desired order.
  202. this->listBackgroundImage = OrderedImageRgbaU8();
  203. }
  204. if (!(newState & componentState_showingOverlayDirect)) {
  205. // Clean up the background image to save memory and allow it to be regenerated in another size later.
  206. this->listBackgroundImage = OrderedImageRgbaU8();
  207. }
  208. }
  209. void Menu::updateLocationEvent(const IRect& oldLocation, const IRect& newLocation) {
  210. int left = this->padding.value;
  211. int top = this->padding.value;
  212. int overlap = 3;
  213. if (this->subMenu) {
  214. left += newLocation.width() - overlap;
  215. } else {
  216. top += newLocation.height() - overlap;
  217. }
  218. int maxWidth = 80; // Minimum usable with.
  219. // Expand list with to fit child components.
  220. for (int i = 0; i < this->getChildCount(); i++) {
  221. int width = this->children[i]->getDesiredDimensions().x;
  222. if (maxWidth < width) maxWidth = width;
  223. }
  224. // Stretch out the child components to use the whole width.
  225. for (int i = 0; i < this->getChildCount(); i++) {
  226. int height = this->children[i]->getDesiredDimensions().y;
  227. this->children[i]->applyLayout(IRect(left, top, maxWidth, height));
  228. top += height + this->spacing.value;
  229. }
  230. }
  231. static void closeEntireMenu(VisualComponent* menu) {
  232. while (menu->parent != nullptr) {
  233. // Hide the menu when closing the menu. Notifications to updateStateEvent will do the proper cleanup for each component's type.
  234. menu->hideOverlay();
  235. // Move on to the parent component.
  236. menu = menu->parent;
  237. }
  238. }
  239. void Menu::receiveMouseEvent(const MouseEvent& event) {
  240. int childCount = this->getChildCount();
  241. MouseEvent localEvent = event;
  242. localEvent.position -= this->location.upperLeft();
  243. if (this->showingOverlay() && this->pointIsInsideOfOverlay(event.position)) {
  244. for (int i = childCount - 1; i >= 0; i--) {
  245. if (this->children[i]->pointIsInside(localEvent.position)) {
  246. this->children[i]->makeFocused();
  247. MouseEvent childEvent = localEvent;
  248. childEvent.position -= this->children[i]->location.upperLeft();
  249. this->children[i]->sendMouseEvent(childEvent, true);
  250. break;
  251. }
  252. }
  253. } else if (this->pointIsInside(event.position)) {
  254. if (childCount > 0) { // Has a list of members to open, toggle expansion when clicked.
  255. if (this->subMenu) { // Menu within another menu.
  256. // Hover to expand sub-menu's list.
  257. if (event.mouseEventType == MouseEventType::MouseMove && !this->showingOverlay()) {
  258. this->createOverlay();
  259. }
  260. } else { // Top menu, which is usually placed in a toolbar.
  261. bool toggleExpansion = false;
  262. if (event.mouseEventType == MouseEventType::MouseDown) {
  263. // Toggle expansion when headImageMethod is clicked.
  264. toggleExpansion = true;
  265. } else if (event.mouseEventType == MouseEventType::MouseMove && !this->showingOverlay()) {
  266. // Automatically expand hovered top-menus neighboring an opened top menu.
  267. if (this->parent != nullptr) {
  268. VisualComponent *toolbar = this->parent;
  269. if (toolbar->ownsFocus()) {
  270. for (int i = 0; i < toolbar->getChildCount(); i++) {
  271. if (toolbar->children[i]->showingOverlay()) {
  272. toggleExpansion = true;
  273. break;
  274. }
  275. }
  276. }
  277. }
  278. }
  279. if (toggleExpansion) {
  280. // Menu components with child members will toggle visibility for its list when pressed.
  281. if (this->showingOverlay()) {
  282. closeEntireMenu(this);
  283. } else {
  284. this->createOverlay();
  285. }
  286. }
  287. }
  288. } else { // List item, because it has no children.
  289. // Childless menu components are treated as menu items that can be clicked to perform an action and close the menu.
  290. if (event.mouseEventType == MouseEventType::MouseDown) {
  291. // Hide overlays all the way to root.
  292. closeEntireMenu(this);
  293. // Call the event assigned to this menu item.
  294. this->callback_pressedEvent();
  295. }
  296. }
  297. // Because the main body was interacted with, the mouse events are passed on.
  298. VisualComponent::receiveMouseEvent(event);
  299. }
  300. }
  301. IVector2D Menu::getDesiredDimensions() {
  302. this->completeAssets();
  303. int widthAdder = this->padding.value * 2;
  304. int heightAdder = widthAdder;
  305. if (this->hasArrow()) {
  306. // Make extra space for the expansion arrowhead when containing a list of members.
  307. widthAdder += 24;
  308. }
  309. return IVector2D(font_getLineWidth(this->font, this->text.value) + widthAdder, font_getSize(this->font) + heightAdder);
  310. }