ListBox.cpp 16 KB

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