ListBox.cpp 16 KB

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