Menu.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  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 focused, int hover, 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, focused, hover)(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. // headImage is set to an empty handle when something used as input changes.
  103. if (!image_exists(this->headImage)) {
  104. completeAssets();
  105. bool focus = this->isFocused();
  106. bool hover = this->isHovered();
  107. bool press = this->pressed && hover;
  108. this->headImage = generateHeadImage(*this, this->headImageMethod, press, focus, hover, headWidth, headHeight, this->backColor.value, this->foreColor.value, this->text.value, this->font);
  109. }
  110. }
  111. // Fill the listBackgroundImageMethod with a solid color
  112. void Menu::drawSelf(ImageRgbaU8& targetImage, const IRect &relativeLocation) {
  113. this->generateGraphics();
  114. if (this->menuHead_filter == 1) {
  115. draw_alphaFilter(targetImage, this->headImage, relativeLocation.left(), relativeLocation.top());
  116. } else {
  117. draw_copy(targetImage, this->headImage, relativeLocation.left(), relativeLocation.top());
  118. }
  119. }
  120. void Menu::generateBackground() {
  121. if (!image_exists(this->listBackgroundImage)) {
  122. int listWidth = this->overlayLocation.width();
  123. int listHeight = this->overlayLocation.height();
  124. if (listWidth < 1) { listWidth = 1; }
  125. if (listHeight < 1) { listHeight = 1; }
  126. component_generateImage(this->theme, this->listBackgroundImageMethod, listWidth, listHeight, this->backColor.value.red, this->backColor.value.green, this->backColor.value.blue)(this->listBackgroundImage);
  127. }
  128. }
  129. void Menu::createOverlay() {
  130. if (!this->showingOverlay()) {
  131. this->showOverlay();
  132. this->makeFocused(); // Focus on the current menu path to make others lose focus.
  133. IRect memberBound = this->children[0]->location;
  134. for (int i = 1; i < this->getChildCount(); i++) {
  135. memberBound = IRect::merge(memberBound, this->children[i]->location);
  136. }
  137. // Calculate the new list bound.
  138. this->overlayLocation = memberBound.expanded(this->padding.value) + this->location.upperLeft();
  139. }
  140. }
  141. bool Menu::managesChildren() {
  142. return true;
  143. }
  144. bool Menu::pointIsInsideOfOverlay(const IVector2D& pixelPosition) {
  145. return pixelPosition.x > this->overlayLocation.left() && pixelPosition.x < this->overlayLocation.right() && pixelPosition.y > this->overlayLocation.top() && pixelPosition.y < this->overlayLocation.bottom();
  146. }
  147. void Menu::drawOverlay(ImageRgbaU8& targetImage, const IVector2D &absoluteOffset) {
  148. this->generateBackground();
  149. IVector2D overlayOffset = absoluteOffset + this->overlayLocation.upperLeft();
  150. if (this->menuList_filter == 1) {
  151. draw_alphaFilter(targetImage, this->listBackgroundImage, overlayOffset.x, overlayOffset.y);
  152. } else {
  153. draw_copy(targetImage, this->listBackgroundImage, overlayOffset.x, overlayOffset.y);
  154. }
  155. for (int i = 0; i < this->getChildCount(); i++) {
  156. this->children[i]->draw(targetImage, absoluteOffset + this->location.upperLeft());
  157. }
  158. }
  159. void Menu::loadTheme(const VisualTheme &theme) {
  160. // Is it a sub-menu or top menu?
  161. this->subMenu = this->parent != nullptr && dynamic_cast<Menu*>(this->parent) != nullptr;
  162. this->finalHeadClass = theme_selectClass(theme, this->headClass.value, this->subMenu ? U"MenuSub" : U"MenuTop");
  163. this->finalListClass = theme_selectClass(theme, this->listClass.value, U"MenuList");
  164. this->headImageMethod = theme_getScalableImage(theme, this->finalHeadClass);
  165. // Check which states the scalable head image is listening to.
  166. this->headStateListenerMask = theme_getStateListenerMask(this->headImageMethod);
  167. this->listBackgroundImageMethod = theme_getScalableImage(theme, this->finalListClass);
  168. // Ask the theme which parts should be drawn using alpha filtering, and fall back on solid drawing.
  169. this->menuHead_filter = theme_getInteger(theme, this->finalHeadClass, U"Filter", 0);
  170. this->menuList_filter = theme_getInteger(theme, this->finalListClass, U"Filter", 0);
  171. }
  172. void Menu::changedTheme(VisualTheme newTheme) {
  173. this->loadTheme(newTheme);
  174. this->headImage = OrderedImageRgbaU8();
  175. }
  176. void Menu::completeAssets() {
  177. if (this->headImageMethod.methodIndex == -1) {
  178. this->loadTheme(theme_getDefault());
  179. }
  180. if (this->font.isNull()) {
  181. this->font = font_getDefault();
  182. }
  183. }
  184. void Menu::changedLocation(const IRect &oldLocation, const IRect &newLocation) {
  185. // If the component has changed dimensions then redraw the image
  186. if (oldLocation.size() != newLocation.size()) {
  187. this->headImage = OrderedImageRgbaU8();
  188. }
  189. }
  190. void Menu::changedAttribute(const ReadableString &name) {
  191. if (string_caseInsensitiveMatch(name, U"HeadClass")
  192. || string_caseInsensitiveMatch(name, U"ListClass")) {
  193. // Update from the theme if a theme class has changed.
  194. this->changedTheme(this->getTheme());
  195. } else if (!string_caseInsensitiveMatch(name, U"Visible")) {
  196. this->headImage = OrderedImageRgbaU8();
  197. }
  198. VisualComponent::changedAttribute(name);
  199. }
  200. void Menu::updateStateEvent(ComponentState oldState, ComponentState newState) {
  201. // If no longer having any type of focus, hide the overlay.
  202. if ((oldState & componentState_focus) && !(newState & componentState_focus)) {
  203. // Hide the menu when losing focus.
  204. this->hideOverlay();
  205. // State notifications are not triggered from within the same notification, so that one can handle all the updates safely in the desired order.
  206. this->listBackgroundImage = OrderedImageRgbaU8();
  207. }
  208. if (!(newState & componentState_showingOverlayDirect)) {
  209. // Clean up the background image to save memory and allow it to be regenerated in another size later.
  210. this->listBackgroundImage = OrderedImageRgbaU8();
  211. }
  212. // Check which states have changed.
  213. ComponentState changedStates = newState ^ oldState;
  214. // TODO: Debug print to see if this works and create themes that respond to direct focus and hover states using color modifications as a simple start.
  215. // Check if any of the changed bits overlap with the states that the head's scalable image generator uses as input.
  216. if (changedStates & this->headStateListenerMask) {
  217. // If a state affecting the input has changed, the image should be updated.
  218. // The pressed argument can also be requested by the scalable images, but that is handled by components themselves.
  219. this->headImage = OrderedImageRgbaU8();
  220. }
  221. // When pressed, changes in hover will affect if the component will appear pressed,
  222. // so show that one can safely abort a press done by mistake by releasing outside.
  223. if (this->pressed && (changedStates & componentState_hoverDirect)) {
  224. // If a state affecting the input has changed, the image should be updated.
  225. // The pressed argument can also be requested by the scalable images, but that is handled by components themselves.
  226. this->headImage = OrderedImageRgbaU8();
  227. }
  228. }
  229. void Menu::updateLocationEvent(const IRect& oldLocation, const IRect& newLocation) {
  230. int left = this->padding.value;
  231. int top = this->padding.value;
  232. int overlap = 3;
  233. if (this->subMenu) {
  234. left += newLocation.width() - overlap;
  235. } else {
  236. top += newLocation.height() - overlap;
  237. }
  238. int maxWidth = 80; // Minimum usable with.
  239. // Expand list with to fit child components.
  240. for (int i = 0; i < this->getChildCount(); i++) {
  241. int width = this->children[i]->getDesiredDimensions().x;
  242. if (maxWidth < width) maxWidth = width;
  243. }
  244. // Stretch out the child components to use the whole width.
  245. for (int i = 0; i < this->getChildCount(); i++) {
  246. int height = this->children[i]->getDesiredDimensions().y;
  247. this->children[i]->applyLayout(IRect(left, top, maxWidth, height));
  248. top += height + this->spacing.value;
  249. }
  250. }
  251. static void closeEntireMenu(VisualComponent* menu) {
  252. while (menu->parent != nullptr) {
  253. // Hide the menu when closing the menu. Notifications to updateStateEvent will do the proper cleanup for each component's type.
  254. menu->hideOverlay();
  255. // Move on to the parent component.
  256. menu = menu->parent;
  257. }
  258. }
  259. void Menu::receiveMouseEvent(const MouseEvent& event) {
  260. int childCount = this->getChildCount();
  261. MouseEvent localEvent = event;
  262. localEvent.position -= this->location.upperLeft();
  263. bool inOverlay = this->showingOverlay() && this->pointIsInsideOfOverlay(event.position);
  264. bool inHead = this->pointIsInside(event.position);
  265. if (event.mouseEventType == MouseEventType::MouseUp) {
  266. // Pass on mouse up events to dragged components, even if not inside of them.
  267. if (this->dragComponent.isNotNull()) {
  268. MouseEvent childEvent = localEvent;
  269. childEvent.position -= this->dragComponent->location.upperLeft();
  270. this->dragComponent->sendMouseEvent(childEvent, true);
  271. }
  272. } else if (inOverlay) {
  273. // Pass on down and move events to a child component that the cursor is inside of.
  274. for (int i = childCount - 1; i >= 0; i--) {
  275. if (this->children[i]->pointIsInside(localEvent.position)) {
  276. MouseEvent childEvent = localEvent;
  277. childEvent.position -= this->children[i]->location.upperLeft();
  278. if (event.mouseEventType == MouseEventType::MouseDown) {
  279. this->dragComponent = this->children[i];
  280. this->dragComponent->makeFocused();
  281. }
  282. this->children[i]->sendMouseEvent(childEvent, true);
  283. break;
  284. }
  285. }
  286. }
  287. // If not interacting with the overlay and the cursor is within the head.
  288. if (!inOverlay && inHead) {
  289. if (childCount > 0) { // Has a list of members to open, toggle expansion when clicked.
  290. if (this->subMenu) { // Menu within another menu.
  291. // Hover to expand sub-menu's list.
  292. if (event.mouseEventType == MouseEventType::MouseMove && !this->showingOverlay()) {
  293. this->createOverlay();
  294. }
  295. } else { // Top menu, which is usually placed in a toolbar.
  296. bool toggleExpansion = false;
  297. if (event.mouseEventType == MouseEventType::MouseDown) {
  298. // Toggle expansion when headImageMethod is clicked.
  299. toggleExpansion = true;
  300. } else if (event.mouseEventType == MouseEventType::MouseMove && !this->showingOverlay()) {
  301. // Automatically expand hovered top-menus neighboring an opened top menu.
  302. if (this->parent != nullptr) {
  303. VisualComponent *toolbar = this->parent;
  304. if (toolbar->ownsFocus()) {
  305. for (int i = 0; i < toolbar->getChildCount(); i++) {
  306. if (toolbar->children[i]->showingOverlay()) {
  307. toggleExpansion = true;
  308. break;
  309. }
  310. }
  311. }
  312. }
  313. }
  314. if (toggleExpansion) {
  315. // Menu components with child members will toggle visibility for its list when pressed.
  316. if (this->showingOverlay()) {
  317. closeEntireMenu(this);
  318. } else {
  319. this->createOverlay();
  320. }
  321. }
  322. }
  323. } else { // List item, because it has no children.
  324. // Childless menu components are treated as menu items that can be clicked to perform an action and close the menu.
  325. if ((event.mouseEventType == MouseEventType::MouseDown) && !this->pressed) {
  326. // Show that the event is about to be triggered.
  327. this->pressed = true;
  328. // Update the head image.
  329. this->headImage = OrderedImageRgbaU8();
  330. } else if ((event.mouseEventType == MouseEventType::MouseUp) && this->pressed) {
  331. // Released a press inside, confirming the event.
  332. // Hide overlays all the way to root.
  333. closeEntireMenu(this);
  334. // Call the event assigned to this menu item.
  335. this->callback_pressedEvent();
  336. }
  337. }
  338. // Because the main body was interacted with, the basic up/down/move/scroll mouse events are triggered.
  339. VisualComponent::receiveMouseEvent(event);
  340. }
  341. // Releasing anywhere should stop pressing.
  342. if (event.mouseEventType == MouseEventType::MouseUp) {
  343. this->dragComponent = Handle<VisualComponent>();
  344. if (this->pressed) {
  345. // No longer pressed.
  346. this->pressed = false;
  347. // Update the head image.
  348. this->headImage = OrderedImageRgbaU8();
  349. }
  350. }
  351. }
  352. IVector2D Menu::getDesiredDimensions() {
  353. this->completeAssets();
  354. int widthAdder = this->padding.value * 2;
  355. int heightAdder = widthAdder;
  356. if (this->hasArrow()) {
  357. // Make extra space for the expansion arrowhead when containing a list of members.
  358. widthAdder += 24;
  359. }
  360. return IVector2D(font_getLineWidth(this->font, this->text.value) + widthAdder, font_getSize(this->font) + heightAdder);
  361. }