ListBox.cpp 16 KB

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