ListBox.cpp 15 KB

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