ListBox.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  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. completeAssets();
  61. this->listBox(width, height, this->color.value.red, this->color.value.green, this->color.value.blue)(this->image);
  62. int verticalStep = this->font->size;
  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. this->font->printLine(this->image, 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() + border, whole.top() + border, whole.width() - border * 2, scrollEndHeight - border * 2);
  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() + border, whole.bottom() - scrollEndHeight + border, whole.width() - border * 2, scrollEndHeight - border * 2);
  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. }
  96. this->hasImages = true;
  97. }
  98. }
  99. void ListBox::drawSelf(ImageRgbaU8& targetImage, const IRect &relativeLocation) {
  100. this->generateGraphics();
  101. draw_copy(targetImage, this->image, relativeLocation.left(), relativeLocation.top());
  102. }
  103. void ListBox::pressScrollBar(int64_t localY) {
  104. int64_t maxScroll = this->list.value.length() - this->getVisibleScrollRange();
  105. int64_t knobHeight = this->getKnobLocation().height();
  106. int64_t endDistance = scrollEndHeight + knobHeight / 2;
  107. int64_t barHeight = this->location.height() - (endDistance * 2);
  108. this->firstVisible = ((localY - endDistance) * maxScroll) / barHeight;
  109. this->limitScrolling();
  110. this->hasImages = false; // Force redraw
  111. }
  112. void ListBox::receiveMouseEvent(const MouseEvent& event) {
  113. bool supressEvent = false;
  114. this->inside = this->pointIsInside(event.position);
  115. bool onScrollBar = this->hasVerticalScroll && event.position.x >= this->location.width() - scrollWidth;
  116. int64_t maxIndex = this->list.value.length() - 1;
  117. int64_t hoverIndex = this->firstVisible + ((event.position.y - this->location.top() - textBorderTop) / this->font->size);
  118. if (hoverIndex > maxIndex) {
  119. hoverIndex = -1;
  120. }
  121. if (event.mouseEventType == MouseEventType::MouseDown) {
  122. if (onScrollBar) {
  123. this->pressedIndex = -1;
  124. if (event.position.y < scrollEndHeight) {
  125. // Upper scroll button
  126. this->firstVisible--;
  127. } else if (event.position.y > this->location.height() - scrollEndHeight) {
  128. // Lower scroll button
  129. this->firstVisible++;
  130. } else {
  131. // Start scrolling with the mouse using the relative height on the scroll bar.
  132. this->pressScrollBar(event.position.y);
  133. // Repeat on mouse move
  134. this->holdingScrollBar = true;
  135. }
  136. } else {
  137. this->pressedIndex = hoverIndex;
  138. }
  139. this->limitScrolling();
  140. this->hasImages = false; // Force redraw
  141. } else if (event.mouseEventType == MouseEventType::MouseUp) {
  142. if (this->pressedIndex > -1 && this->inside && !onScrollBar && hoverIndex == this->pressedIndex) {
  143. this->selectedIndex.value = hoverIndex;
  144. this->limitScrolling(true);
  145. this->callback_pressedEvent();
  146. }
  147. this->pressedIndex = -1;
  148. this->holdingScrollBar = false;
  149. this->hasImages = false; // Force redraw
  150. } else if (event.mouseEventType == MouseEventType::Scroll) {
  151. if (event.key == MouseKeyEnum::ScrollUp) {
  152. this->firstVisible--;
  153. } else if (event.key == MouseKeyEnum::ScrollDown) {
  154. this->firstVisible++;
  155. }
  156. this->holdingScrollBar = false;
  157. this->limitScrolling();
  158. this->hasImages = false; // Force redraw
  159. } else if (event.mouseEventType == MouseEventType::MouseMove) {
  160. if (this->holdingScrollBar) {
  161. supressEvent = true;
  162. this->pressScrollBar(event.position.y);
  163. }
  164. }
  165. if (!supressEvent) {
  166. VisualComponent::receiveMouseEvent(event);
  167. }
  168. }
  169. void ListBox::changedTheme(VisualTheme newTheme) {
  170. this->listBox = theme_getScalableImage(newTheme, U"Panel");
  171. this->hasImages = false; // Force redraw
  172. }
  173. void ListBox::completeAssets() {
  174. if (this->listBox.methodIndex == -1) {
  175. this->listBox = theme_getScalableImage(theme_getDefault(), U"Panel");
  176. }
  177. if (this->font.get() == nullptr) {
  178. this->font = font_getDefault();
  179. }
  180. }
  181. void ListBox::changedLocation(IRect &oldLocation, IRect &newLocation) {
  182. // If the component has changed dimensions then redraw the image
  183. if (oldLocation.size() != newLocation.size()) {
  184. this->hasImages = false;
  185. this->limitScrolling();
  186. }
  187. }
  188. void ListBox::changedAttribute(const ReadableString &name) {
  189. // If an attribute has changed then force the image to be redrawn
  190. this->hasImages = false;
  191. if (string_caseInsensitiveMatch(name, U"List")) {
  192. // Reset selection on full list updates
  193. this->selectedIndex.value = 0;
  194. }
  195. this->limitSelection();
  196. this->limitScrolling();
  197. }
  198. int64_t ListBox::getSelectedIndex() {
  199. int64_t index = this->selectedIndex.value;
  200. if (this->selectedIndex.value < 0 || this->selectedIndex.value >= this->list.value.length()) {
  201. index = -1;
  202. }
  203. return index;
  204. }
  205. void ListBox::limitSelection() {
  206. // Get the maximum index
  207. int64_t maxIndex = this->list.value.length() - 1;
  208. if (maxIndex < 0) {
  209. maxIndex = 0;
  210. }
  211. // Reset selection on out of bound
  212. if (this->selectedIndex.value < 0 || this->selectedIndex.value > maxIndex) {
  213. this->selectedIndex.value = 0;
  214. }
  215. }
  216. int64_t ListBox::getVisibleScrollRange() {
  217. int64_t verticalStep = this->font->size;
  218. return (this->location.height() - textBorderTop * 2) / verticalStep;
  219. }
  220. IRect ListBox::getScrollBarLocation_includingButtons() {
  221. return IRect(this->location.width() - scrollWidth, 0, scrollWidth, this->location.height());
  222. }
  223. IRect ListBox::getScrollBarLocation_excludingButtons() {
  224. return IRect(this->location.width() - scrollWidth, scrollEndHeight, scrollWidth, this->location.height() - (scrollEndHeight * 2));
  225. }
  226. IRect ListBox::getKnobLocation() {
  227. // Eroded scroll-bar excluding buttons
  228. // The final knob is a sub-set of this region corresponding to the visibility
  229. IRect erodedBar = this->getScrollBarLocation_excludingButtons().expanded(-knobErosion);
  230. // Item ranges
  231. int64_t visibleRange = this->getVisibleScrollRange(); // 0..visibleRange-1
  232. int64_t itemCount = this->list.value.length(); // 0..itemCount-1
  233. int64_t maxScroll = itemCount - visibleRange; // 0..maxScroll
  234. // Dimensions
  235. int64_t knobHeight = (erodedBar.height() * visibleRange) / itemCount;
  236. // Visual range for center
  237. int64_t scrollStart = erodedBar.top() + knobHeight / 2;
  238. int64_t scrollDistance = erodedBar.height() - knobHeight;
  239. int64_t knobCenterY = scrollStart + ((this->firstVisible * scrollDistance) / maxScroll);
  240. return IRect(erodedBar.left(), knobCenterY - (knobHeight / 2), erodedBar.width(), knobHeight);
  241. }
  242. // Optional limit of scrolling, to be applied when the user don't explicitly scroll away from the selection
  243. // limitSelection should be called before limitScrolling, because scrolling limits depend on selection
  244. void ListBox::limitScrolling(bool keepSelectedVisible) {
  245. // Try to load the font before estimating how big the view is
  246. this->completeAssets();
  247. if (this->font.get() == nullptr) {
  248. throwError("Cannot get the font size because ListBox failed to get a font!\n");
  249. }
  250. int64_t itemCount = this->list.value.length();
  251. int64_t visibleRange = this->getVisibleScrollRange();
  252. int64_t maxScroll;
  253. int64_t minScroll;
  254. // Big enough list to need scrolling but big enough list-box to fit two buttons inside
  255. this->hasVerticalScroll = itemCount > visibleRange && this->location.width() >= scrollWidth * 2 && this->location.height() >= scrollEndHeight * 2;
  256. if (keepSelectedVisible) {
  257. maxScroll = this->selectedIndex.value;
  258. minScroll = maxScroll + 1 - visibleRange;
  259. } else {
  260. maxScroll = itemCount - visibleRange;
  261. minScroll = 0;
  262. }
  263. if (this->firstVisible > maxScroll) {
  264. this->firstVisible = maxScroll;
  265. }
  266. if (this->firstVisible < minScroll) {
  267. this->firstVisible = minScroll;
  268. }
  269. }
  270. String ListBox::call(const ReadableString &methodName, const ReadableString &arguments) {
  271. if (string_caseInsensitiveMatch(methodName, U"ClearAll")) {
  272. // Remove all elements from the list
  273. this->list.value.clear();
  274. this->hasImages = false;
  275. this->selectedIndex.value = 0;
  276. this->limitScrolling();
  277. this->firstVisible = 0;
  278. return U"";
  279. } else if (string_caseInsensitiveMatch(methodName, U"PushElement")) {
  280. // Push a new element to the list
  281. // No quote mangling needed for this single argument.
  282. this->list.value.push(arguments);
  283. this->selectedIndex.value = this->list.value.length() - 1;
  284. this->limitScrolling(true);
  285. this->hasImages = false;
  286. return U"";
  287. } else if (string_caseInsensitiveMatch(methodName, U"RemoveElement")) {
  288. // Remove an element who's index is given in the only input argument
  289. int64_t index = string_parseInteger(arguments);
  290. if (index < 0 || index >= this->list.value.length()) {
  291. throwError("Index (", arguments, " = ", index, ") out of bound in RemoveElement!\n");
  292. }
  293. this->list.value.remove(index);
  294. this->limitSelection();
  295. this->limitScrolling(true);
  296. this->hasImages = false;
  297. return U"";
  298. } else if (string_caseInsensitiveMatch(methodName, U"GetLength")) {
  299. // Returns the length of the list
  300. return string_combine(this->list.value.length());
  301. } else if (string_caseInsensitiveMatch(methodName, U"GetSelectedIndex")) {
  302. // Returns the selected index or -1 if nothing is selected
  303. return string_combine(this->getSelectedIndex());
  304. } else if (string_caseInsensitiveMatch(methodName, U"GetSelectedText")) {
  305. // Returns the selected element's text or an empty string if nothing is selected
  306. int64_t index = getSelectedIndex();
  307. if (index > -1) {
  308. return this->list.value[index];
  309. } else {
  310. return U"";
  311. }
  312. } else {
  313. return VisualComponent::call(methodName, arguments);
  314. }
  315. }