ListBox.cpp 15 KB

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