ListBox.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. // zlib open source license
  2. //
  3. // Copyright (c) 2020 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 "ListBox.h"
  24. #include <math.h>
  25. using namespace dsr;
  26. PERSISTENT_DEFINITION(ListBox)
  27. void ListBox::declareAttributes(StructureDefinition &target) const {
  28. VisualComponent::declareAttributes(target);
  29. target.declareAttribute(U"Color");
  30. target.declareAttribute(U"List");
  31. target.declareAttribute(U"SelectedIndex");
  32. }
  33. Persistent* ListBox::findAttribute(const ReadableString &name) {
  34. if (string_caseInsensitiveMatch(name, U"Color")) {
  35. return &(this->color);
  36. } else if (string_caseInsensitiveMatch(name, U"List")) {
  37. return &(this->list);
  38. } else if (string_caseInsensitiveMatch(name, U"SelectedIndex")) {
  39. return &(this->selectedIndex);
  40. } else {
  41. return VisualComponent::findAttribute(name);
  42. }
  43. }
  44. ListBox::ListBox() {}
  45. bool ListBox::isContainer() const {
  46. return true;
  47. }
  48. static const int textBorderLeft = 6;
  49. static const int textBorderTop = 4;
  50. static const int scrollWidth = 16; // The width of the scroll bar
  51. static const int scrollEndHeight = 14; // The height of upper and lower scroll buttons
  52. static const int border = 1; // Scroll-bar edge thickness
  53. static const int knobErosion = border; // Scroll-bar knob erosion
  54. void ListBox::generateGraphics() {
  55. int width = this->location.width();
  56. int height = this->location.height();
  57. if (width < 1) { width = 1; }
  58. if (height < 1) { height = 1; }
  59. if (!this->hasImages) {
  60. this->completeAssets();
  61. this->scalableImage_listBox(width, height, this->color.value.red, this->color.value.green, this->color.value.blue)(this->image);
  62. int verticalStep = font_getSize(this->font);
  63. int left = textBorderLeft;
  64. int top = textBorderTop;
  65. for (int64_t i = this->firstVisible; i < this->list.value.length() && top < height; i++) {
  66. ColorRgbaI32 textColor;
  67. if (i == this->pressedIndex) {
  68. textColor = ColorRgbaI32(255, 255, 255, 255);
  69. } else if (i == this->selectedIndex.value) {
  70. textColor = ColorRgbaI32(255, 255, 255, 255);
  71. } else {
  72. textColor = ColorRgbaI32(0, 0, 0, 255);
  73. }
  74. if (i == this->selectedIndex.value) {
  75. draw_rectangle(this->image, IRect(left, top, width - (textBorderLeft * 2), verticalStep), ColorRgbaI32(0, 0, 0, 255));
  76. }
  77. font_printLine(this->image, this->font, this->list.value[i], IVector2D(left, top), textColor);
  78. top += verticalStep;
  79. }
  80. if (this->hasVerticalScroll) {
  81. ColorRgbaI32 buttonColor = ColorRgbaI32(this->color.value, 255);
  82. ColorRgbaI32 barColor = ColorRgbaI32(this->color.value.red / 2, this->color.value.green / 2, this->color.value.blue / 2, 255);
  83. ColorRgbaI32 borderColor = ColorRgbaI32(0, 0, 0, 255);
  84. IRect whole = IRect(this->location.width() - scrollWidth, 0, scrollWidth, this->location.height());
  85. IRect upper = IRect(whole.left(), whole.top(), whole.width(), scrollEndHeight);
  86. IRect middle = IRect(whole.left() + border, whole.top() + scrollEndHeight + border, whole.width() - border * 2, whole.height() - (border + scrollEndHeight) * 2);
  87. IRect lower = IRect(whole.left(), whole.bottom() - scrollEndHeight, whole.width(), scrollEndHeight);
  88. IRect knob = this->getKnobLocation();
  89. // Scroll-bar
  90. draw_rectangle(this->image, whole, borderColor);
  91. draw_rectangle(this->image, upper, buttonColor);
  92. draw_rectangle(this->image, middle, barColor);
  93. draw_rectangle(this->image, lower, buttonColor);
  94. draw_rectangle(this->image, knob, buttonColor);
  95. draw_copy(this->image, (this->pressScrollUp) ? this->scrollButtonTop_pressed : this->scrollButtonTop_normal, upper.left(), upper.top());
  96. draw_copy(this->image, (this->pressScrollDown && this->inside) ? this->scrollButtonBottom_pressed : this->scrollButtonBottom_normal, lower.left(), lower.top());
  97. }
  98. this->hasImages = true;
  99. }
  100. }
  101. void ListBox::drawSelf(ImageRgbaU8& targetImage, const IRect &relativeLocation) {
  102. this->generateGraphics();
  103. draw_copy(targetImage, this->image, relativeLocation.left(), relativeLocation.top());
  104. }
  105. void ListBox::pressScrollBar(int64_t localY) {
  106. int64_t oldIndex = this->firstVisible;
  107. int64_t maxScroll = this->list.value.length() - this->getVisibleScrollRange();
  108. int64_t knobHeight = this->getKnobLocation().height();
  109. int64_t endDistance = scrollEndHeight + knobHeight / 2;
  110. int64_t barHeight = this->location.height() - (endDistance * 2);
  111. this->firstVisible = ((localY - endDistance) * maxScroll) / barHeight;
  112. this->limitScrolling();
  113. // Avoid expensive redrawing if the index did not change
  114. if (this->firstVisible != oldIndex) {
  115. this->hasImages = false; // Force redraw
  116. }
  117. }
  118. void ListBox::receiveMouseEvent(const MouseEvent& event) {
  119. bool supressEvent = false;
  120. this->inside = this->pointIsInside(event.position);
  121. bool onScrollBar = this->hasVerticalScroll && event.position.x >= this->location.width() - scrollWidth;
  122. int64_t maxIndex = this->list.value.length() - 1;
  123. int64_t hoverIndex = this->firstVisible + ((event.position.y - this->location.top() - textBorderTop) / font_getSize(this->font));
  124. if (hoverIndex > maxIndex) {
  125. hoverIndex = -1;
  126. }
  127. if (event.mouseEventType == MouseEventType::MouseDown) {
  128. if (onScrollBar) {
  129. this->pressedIndex = -1;
  130. if (event.position.y < scrollEndHeight) {
  131. // Upper scroll button
  132. this->pressScrollUp = true;
  133. this->firstVisible--;
  134. } else if (event.position.y > this->location.height() - scrollEndHeight) {
  135. // Lower scroll button
  136. this->pressScrollDown = true;
  137. this->firstVisible++;
  138. } else {
  139. // Start scrolling with the mouse using the relative height on the scroll bar.
  140. IRect knobLocation = this->getKnobLocation();
  141. int64_t halfKnobHeight = knobLocation.height() / 2;
  142. this->knobHoldOffset = event.position.y - (knobLocation.top() + halfKnobHeight);
  143. if (this->knobHoldOffset < -halfKnobHeight || this->knobHoldOffset > halfKnobHeight) {
  144. // If pressing outside of the knob, pull it directly to the pressed location before pulling from the center.
  145. this->knobHoldOffset = 0;
  146. this->pressScrollBar(event.position.y - this->knobHoldOffset);
  147. }
  148. this->holdingScrollBar = true;
  149. }
  150. } else {
  151. this->pressedIndex = hoverIndex;
  152. }
  153. this->limitScrolling();
  154. this->hasImages = false; // Force redraw
  155. } else if (event.mouseEventType == MouseEventType::MouseUp) {
  156. if (this->pressedIndex > -1 && this->inside && !onScrollBar && hoverIndex == this->pressedIndex) {
  157. this->selectedIndex.value = hoverIndex;
  158. this->limitScrolling(true);
  159. this->callback_pressedEvent();
  160. }
  161. this->pressScrollUp = false;
  162. this->pressScrollDown = false;
  163. this->pressedIndex = -1;
  164. this->holdingScrollBar = false;
  165. this->hasImages = false; // Force redraw
  166. } else if (event.mouseEventType == MouseEventType::Scroll) {
  167. if (event.key == MouseKeyEnum::ScrollUp) {
  168. this->firstVisible--;
  169. } else if (event.key == MouseKeyEnum::ScrollDown) {
  170. this->firstVisible++;
  171. }
  172. this->holdingScrollBar = false;
  173. this->limitScrolling();
  174. this->hasImages = false; // Force redraw
  175. } else if (event.mouseEventType == MouseEventType::MouseMove) {
  176. if (this->holdingScrollBar) {
  177. supressEvent = true;
  178. this->pressScrollBar(event.position.y - this->knobHoldOffset);
  179. }
  180. }
  181. if (!supressEvent) {
  182. VisualComponent::receiveMouseEvent(event);
  183. }
  184. }
  185. void ListBox::loadTheme(VisualTheme theme) {
  186. this->scalableImage_listBox = theme_getScalableImage(theme, U"ListBox");
  187. this->scalableImage_scrollButton = theme_getScalableImage(theme, U"ScrollButton");
  188. // Generate fixed size buttons for the scroll buttons (because their size is currently given by constants)
  189. ColorRgbI32 color = this->color.value;
  190. this->scalableImage_scrollButton(scrollWidth, scrollEndHeight, false, color.red, color.green, color.blue)(this->scrollButtonTop_normal);
  191. this->scalableImage_scrollButton(scrollWidth, scrollEndHeight, true, color.red, color.green, color.blue)(this->scrollButtonTop_pressed);
  192. this->scalableImage_scrollButton(scrollWidth, scrollEndHeight, false, color.red, color.green, color.blue)(this->scrollButtonBottom_normal);
  193. this->scalableImage_scrollButton(scrollWidth, scrollEndHeight, true, color.red, color.green, color.blue)(this->scrollButtonBottom_pressed);
  194. }
  195. void ListBox::changedTheme(VisualTheme newTheme) {
  196. this->loadTheme(newTheme);
  197. this->hasImages = false; // Force redraw
  198. }
  199. void ListBox::completeAssets() {
  200. if (this->scalableImage_listBox.methodIndex == -1) {
  201. this->loadTheme(theme_getDefault());
  202. }
  203. if (!font_exists(this->font)) {
  204. this->font = font_getDefault();
  205. }
  206. if (!font_exists(this->font)) {
  207. throwError("Failed to load the default font for a ListBox!\n");
  208. }
  209. }
  210. void ListBox::changedLocation(const IRect &oldLocation, const IRect &newLocation) {
  211. // If the component has changed dimensions then redraw the image
  212. if (oldLocation.size() != newLocation.size()) {
  213. this->hasImages = false;
  214. this->limitScrolling();
  215. }
  216. }
  217. void ListBox::changedAttribute(const ReadableString &name) {
  218. // If an attribute has changed then force the image to be redrawn
  219. this->hasImages = false;
  220. if (string_caseInsensitiveMatch(name, U"List")) {
  221. // Reset selection on full list updates
  222. this->selectedIndex.value = 0;
  223. }
  224. this->limitSelection();
  225. this->limitScrolling();
  226. }
  227. int64_t ListBox::getSelectedIndex() {
  228. int64_t index = this->selectedIndex.value;
  229. if (this->selectedIndex.value < 0 || this->selectedIndex.value >= this->list.value.length()) {
  230. index = -1;
  231. }
  232. return index;
  233. }
  234. void ListBox::limitSelection() {
  235. // Get the maximum index
  236. int64_t maxIndex = this->list.value.length() - 1;
  237. if (maxIndex < 0) {
  238. maxIndex = 0;
  239. }
  240. // Reset selection on out of bound
  241. if (this->selectedIndex.value < 0 || this->selectedIndex.value > maxIndex) {
  242. this->selectedIndex.value = 0;
  243. }
  244. }
  245. int64_t ListBox::getVisibleScrollRange() {
  246. this->completeAssets();
  247. int64_t verticalStep = font_getSize(this->font);
  248. return (this->location.height() - textBorderTop * 2) / verticalStep;
  249. }
  250. IRect ListBox::getScrollBarLocation_includingButtons() {
  251. return IRect(this->location.width() - scrollWidth, 0, scrollWidth, this->location.height());
  252. }
  253. IRect ListBox::getScrollBarLocation_excludingButtons() {
  254. return IRect(this->location.width() - scrollWidth, scrollEndHeight, scrollWidth, this->location.height() - (scrollEndHeight * 2));
  255. }
  256. IRect ListBox::getKnobLocation() {
  257. // Eroded scroll-bar excluding buttons
  258. // The final knob is a sub-set of this region corresponding to the visibility
  259. IRect erodedBar = this->getScrollBarLocation_excludingButtons().expanded(-knobErosion);
  260. // Item ranges
  261. int64_t visibleRange = this->getVisibleScrollRange(); // 0..visibleRange-1
  262. int64_t itemCount = this->list.value.length(); // 0..itemCount-1
  263. int64_t maxScroll = itemCount - visibleRange; // 0..maxScroll
  264. // Dimensions
  265. int64_t knobHeight = (erodedBar.height() * visibleRange) / itemCount;
  266. // Visual range for center
  267. int64_t scrollStart = erodedBar.top() + knobHeight / 2;
  268. int64_t scrollDistance = erodedBar.height() - knobHeight;
  269. int64_t knobCenterY = scrollStart + ((this->firstVisible * scrollDistance) / maxScroll);
  270. return IRect(erodedBar.left(), knobCenterY - (knobHeight / 2), erodedBar.width(), knobHeight);
  271. }
  272. // Optional limit of scrolling, to be applied when the user don't explicitly scroll away from the selection
  273. // limitSelection should be called before limitScrolling, because scrolling limits depend on selection
  274. void ListBox::limitScrolling(bool keepSelectedVisible) {
  275. // Try to load the font before estimating how big the view is
  276. this->completeAssets();
  277. int64_t itemCount = this->list.value.length();
  278. int64_t visibleRange = this->getVisibleScrollRange();
  279. int64_t maxScroll;
  280. int64_t minScroll;
  281. // Big enough list to need scrolling but big enough list-box to fit two buttons inside
  282. this->hasVerticalScroll = itemCount > visibleRange && this->location.width() >= scrollWidth * 2 && this->location.height() >= scrollEndHeight * 2;
  283. if (keepSelectedVisible) {
  284. maxScroll = this->selectedIndex.value;
  285. minScroll = maxScroll + 1 - visibleRange;
  286. } else {
  287. maxScroll = itemCount - visibleRange;
  288. minScroll = 0;
  289. }
  290. if (this->firstVisible > maxScroll) {
  291. this->firstVisible = maxScroll;
  292. }
  293. if (this->firstVisible < minScroll) {
  294. this->firstVisible = minScroll;
  295. }
  296. }
  297. String ListBox::call(const ReadableString &methodName, const ReadableString &arguments) {
  298. if (string_caseInsensitiveMatch(methodName, U"ClearAll")) {
  299. // Remove all elements from the list
  300. this->list.value.clear();
  301. this->hasImages = false;
  302. this->selectedIndex.value = 0;
  303. this->limitScrolling();
  304. this->firstVisible = 0;
  305. return U"";
  306. } else if (string_caseInsensitiveMatch(methodName, U"PushElement")) {
  307. // Push a new element to the list
  308. // No quote mangling needed for this single argument.
  309. this->list.value.push(arguments);
  310. this->selectedIndex.value = this->list.value.length() - 1;
  311. this->limitScrolling(true);
  312. this->hasImages = false;
  313. return U"";
  314. } else if (string_caseInsensitiveMatch(methodName, U"RemoveElement")) {
  315. // Remove an element who's index is given in the only input argument
  316. int64_t index = string_parseInteger(arguments);
  317. if (index < 0 || index >= this->list.value.length()) {
  318. throwError("Index (", arguments, " = ", index, ") out of bound in RemoveElement!\n");
  319. }
  320. this->list.value.remove(index);
  321. this->limitSelection();
  322. this->limitScrolling(true);
  323. this->hasImages = false;
  324. return U"";
  325. } else if (string_caseInsensitiveMatch(methodName, U"GetLength")) {
  326. // Returns the length of the list
  327. return string_combine(this->list.value.length());
  328. } else if (string_caseInsensitiveMatch(methodName, U"GetSelectedIndex")) {
  329. // Returns the selected index or -1 if nothing is selected
  330. return string_combine(this->getSelectedIndex());
  331. } else if (string_caseInsensitiveMatch(methodName, U"GetSelectedText")) {
  332. // Returns the selected element's text or an empty string if nothing is selected
  333. int64_t index = getSelectedIndex();
  334. if (index > -1) {
  335. return this->list.value[index];
  336. } else {
  337. return U"";
  338. }
  339. } else {
  340. return VisualComponent::call(methodName, arguments);
  341. }
  342. }