TextBox.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. // zlib open source license
  2. //
  3. // Copyright (c) 2022 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 "TextBox.h"
  24. #include <math.h>
  25. #include <functional>
  26. using namespace dsr;
  27. PERSISTENT_DEFINITION(TextBox)
  28. void TextBox::declareAttributes(StructureDefinition &target) const {
  29. VisualComponent::declareAttributes(target);
  30. target.declareAttribute(U"Color");
  31. target.declareAttribute(U"Text");
  32. }
  33. Persistent* TextBox::findAttribute(const ReadableString &name) {
  34. if (string_caseInsensitiveMatch(name, U"Color")) {
  35. return &(this->color);
  36. } else if (string_caseInsensitiveMatch(name, U"Text")) {
  37. return &(this->text);
  38. } else {
  39. return VisualComponent::findAttribute(name);
  40. }
  41. }
  42. TextBox::TextBox() {}
  43. bool TextBox::isContainer() const {
  44. return false;
  45. }
  46. // Limit exclusive indices to the text.
  47. void TextBox::limitSelection() {
  48. int64_t textLength = string_length(this->text.value);
  49. if (this->selectionStart < 0) this->selectionStart = 0;
  50. if (this->beamLocation < 0) this->beamLocation = 0;
  51. if (this->selectionStart > textLength) this->selectionStart = textLength;
  52. if (this->beamLocation > textLength) this->beamLocation = textLength;
  53. }
  54. static void tabJump(int64_t &x, int64_t leftOrigin, int64_t tabWidth) {
  55. x += tabWidth - ((x - leftOrigin) % tabWidth);
  56. }
  57. // TODO: Make a separate version for multi-line textboxes.
  58. // To have a stable tab alignment, the whole text must be given when iterating.
  59. void iterateCharacters(const ReadableString& text, const RasterFont &font, int64_t originX, std::function<void(int64_t index, DsrChar code, int64_t left, int64_t right)> characterAction) {
  60. int64_t right = originX;
  61. int64_t tabWidth = font_getTabWidth(font);
  62. int64_t monospaceWidth = font_getMonospaceWidth(font);
  63. for (int64_t i = 0; i <= string_length(text); i++) {
  64. DsrChar code = text[i];
  65. int64_t left = right;
  66. if (code == U'\t') {
  67. tabJump(right, originX, tabWidth);
  68. } else {
  69. right += monospaceWidth;
  70. }
  71. characterAction(i, code, left, right);
  72. }
  73. }
  74. int64_t findBeamLocation(const ReadableString& text, const RasterFont &font, int64_t originX, int64_t findPixelX) {
  75. int64_t beamIndex = 0;
  76. int64_t closestDistance = 1000000000000;
  77. iterateCharacters(text, font, originX, [&beamIndex, &closestDistance, findPixelX](int64_t index, DsrChar code, int64_t left, int64_t right) {
  78. // TODO: Why is selection not centered? Is it the origin handled differently?
  79. int64_t center = (left + right) / 2;
  80. int64_t newDistance = std::abs(findPixelX - center);
  81. if (newDistance < closestDistance) {
  82. beamIndex = index;
  83. closestDistance = newDistance;
  84. }
  85. });
  86. return beamIndex;
  87. }
  88. // Iterate over the whole text once for both selection and characters.
  89. // Returns the beam's X location in pixels relative to the parent of originX.
  90. int64_t printMonospace(OrderedImageRgbaU8 &target, const ReadableString& text, const RasterFont &font, bool focused, int64_t originX, int64_t selectionLeft, int64_t selectionRight, int64_t beamIndex, int64_t topY, int64_t bottomY) {
  91. int64_t characterHeight = bottomY - topY;
  92. int64_t beamPixelX = originX;
  93. iterateCharacters(text, font, originX, [&target, &font, &beamPixelX, selectionLeft, selectionRight, beamIndex, topY, characterHeight, focused](int64_t index, DsrChar code, int64_t left, int64_t right) {
  94. if (index == beamIndex) beamPixelX = left;
  95. if (focused && selectionLeft <= index && index < selectionRight) {
  96. draw_rectangle(target, IRect(left, topY, right - left, characterHeight), ColorRgbaI32(0, 0, 100, 255));
  97. font_printCharacter(target, font, code, IVector2D(left, topY), ColorRgbaI32(255, 255, 255, 255));
  98. } else {
  99. font_printCharacter(target, font, code, IVector2D(left, topY), ColorRgbaI32(0, 0, 0, 255));
  100. }
  101. });
  102. return beamPixelX;
  103. }
  104. // TODO: Reuse scaled background images as a separate layer.
  105. // TODO: Allow using different colors for beam, selection, selected text, normal text...
  106. // Maybe ask a separate color palette for specific things using the specific class of textboxes.
  107. // Color palettes can be independent of the media machine, allowing them to be mixed freely with different themes.
  108. // Color palettes can be loaded together with the layout to instantly have the requested standard colors by name.
  109. // Color palettes can have a standard column order of input to easily pack multiple color themes into the same color palette image.
  110. // Just a long list of names for the different X coordinates and the user selects a Y coordinate as the color theme.
  111. // New components will have to use existing parts of the palette by keeping the names reusable.
  112. // Separate components should be able to override any color for programmability, but default values should refer to the current color palette.
  113. // If no color is assigned, the class will give it a standard color from the theme.
  114. // Should classes be separate for themes and palettes?
  115. static OrderedImageRgbaU8 generateBoxImage(TextBox &textBox, MediaMethod imageGenerator, bool focused, int width, int height, ColorRgbI32 backColor, const ReadableString &text, const RasterFont &font) {
  116. // Create a scaled image
  117. OrderedImageRgbaU8 result;
  118. textBox.generateImage(imageGenerator, width, height, backColor.red, backColor.green, backColor.blue, 0, focused ? 1 : 0)(result);
  119. textBox.limitSelection();
  120. // TODO: Allow moving the viewport to follow longer input.
  121. // TODO: Allow multi-line textboxes with scrollbars.
  122. // The logic of scrollbars must be reused as value allocated objects across components, but with different settings.
  123. int64_t halfFontSize = font_getSize(font) / 2;
  124. int64_t originX = halfFontSize;
  125. int64_t center = image_getHeight(result) / 2;
  126. int64_t topY = center - halfFontSize;
  127. int64_t bottomY = center + halfFontSize;
  128. // Find character indices for left and right sides.
  129. int64_t selectionLeft = std::min(textBox.selectionStart, textBox.beamLocation);
  130. int64_t selectionRight = std::max(textBox.selectionStart, textBox.beamLocation);
  131. bool hasSelection = selectionLeft < selectionRight;
  132. // Draw the text with selection and get the beam's pixel location.
  133. int64_t beamPixelX = printMonospace(result, text, font, focused, originX, selectionLeft, selectionRight, textBox.beamLocation, topY, bottomY);
  134. // Draw a beam if the textbox is focused.
  135. if (focused) {
  136. int64_t beamWidth = 2;
  137. draw_rectangle(result, IRect(beamPixelX - 1, topY - 1, beamWidth, bottomY - topY + 2), hasSelection ? ColorRgbaI32(255, 255, 255, 255) : ColorRgbaI32(0, 0, 0, 255));
  138. }
  139. return result;
  140. }
  141. void TextBox::generateGraphics() {
  142. int width = this->location.width();
  143. int height = this->location.height();
  144. if (width < 1) { width = 1; }
  145. if (height < 1) { height = 1; }
  146. bool currentlyFocused = this->isFocused();
  147. if (!this->hasImages || this->drawnAsFocused != currentlyFocused) {
  148. completeAssets();
  149. this->image = generateBoxImage(*this, this->textBox, currentlyFocused, width, height, this->color.value, this->text.value, this->font);
  150. this->hasImages = true;
  151. this->drawnAsFocused = currentlyFocused;
  152. }
  153. }
  154. void TextBox::drawSelf(ImageRgbaU8& targetImage, const IRect &relativeLocation) {
  155. this->generateGraphics();
  156. draw_copy(targetImage, this->image, relativeLocation.left(), relativeLocation.top());
  157. }
  158. void TextBox::receiveMouseEvent(const MouseEvent& event) {
  159. int64_t originX = font_getSize(this->font) / 2;
  160. int32_t localMouseX = event.position.x - this->location.left();
  161. if (event.mouseEventType == MouseEventType::MouseDown) {
  162. this->mousePressed = true;
  163. int64_t newBeamIndex = findBeamLocation(this->text.value, this->font, originX, localMouseX);
  164. if (newBeamIndex != this->selectionStart || newBeamIndex != this->beamLocation) {
  165. this->selectionStart = newBeamIndex;
  166. this->beamLocation = newBeamIndex;
  167. this->hasImages = false;
  168. }
  169. } else if (this->mousePressed && event.mouseEventType == MouseEventType::MouseMove) {
  170. if (this->mousePressed) {
  171. int64_t newBeamIndex = findBeamLocation(this->text.value, this->font, originX, localMouseX);
  172. if (newBeamIndex != this->beamLocation) {
  173. this->beamLocation = newBeamIndex;
  174. this->hasImages = false;
  175. }
  176. }
  177. } else if (this->mousePressed && event.mouseEventType == MouseEventType::MouseUp) {
  178. this->mousePressed = false;
  179. }
  180. VisualComponent::receiveMouseEvent(event);
  181. }
  182. void TextBox::replaceSelection(const ReadableString replacingText) {
  183. int64_t selectionLeft = std::min(this->selectionStart, this->beamLocation);
  184. int64_t selectionRight = std::max(this->selectionStart, this->beamLocation);
  185. this->text.value = string_combine(string_before(this->text.value, selectionLeft), replacingText, string_from(this->text.value, selectionRight));
  186. // Place beam on the right side of the replacement without selecting anything
  187. this->selectionStart = selectionLeft + string_length(replacingText);
  188. this->beamLocation = selectionStart;
  189. this->hasImages = false;
  190. }
  191. void TextBox::replaceSelection(DsrChar replacingCharacter) {
  192. int64_t selectionLeft = std::min(this->selectionStart, this->beamLocation);
  193. int64_t selectionRight = std::max(this->selectionStart, this->beamLocation);
  194. String newText = string_before(this->text.value, selectionLeft);
  195. string_appendChar(newText, replacingCharacter);
  196. string_append(newText, string_from(this->text.value, selectionRight));
  197. this->text.value = newText;
  198. // Place beam on the right side of the replacement without selecting anything
  199. this->selectionStart = selectionLeft + 1;
  200. this->beamLocation = selectionStart;
  201. this->hasImages = false;
  202. }
  203. void TextBox::placeBeam(int64_t index, bool removeSelection) {
  204. this->beamLocation = index;
  205. if (removeSelection) {
  206. this->selectionStart = index;
  207. }
  208. this->hasImages = false;
  209. }
  210. static const uint32_t combinationKey_leftShift = 1 << 0;
  211. static const uint32_t combinationKey_rightShift = 1 << 1;
  212. static const uint32_t combinationKey_shift = combinationKey_leftShift | combinationKey_rightShift;
  213. static const uint32_t combinationKey_leftControl = 1 << 2;
  214. static const uint32_t combinationKey_rightControl = 1 << 3;
  215. static const uint32_t combinationKey_control = combinationKey_leftControl | combinationKey_rightControl;
  216. // TODO: Copy and paste using a clipboard.
  217. void TextBox::receiveKeyboardEvent(const KeyboardEvent& event) {
  218. // Insert and scroll-lock is not supported.
  219. if (event.keyboardEventType == KeyboardEventType::KeyDown) {
  220. if (event.dsrKey == DsrKey_LeftShift) {
  221. this->combinationKeys |= combinationKey_leftShift;
  222. } else if (event.dsrKey == DsrKey_RightShift) {
  223. this->combinationKeys |= combinationKey_rightShift;
  224. } else if (event.dsrKey == DsrKey_LeftControl) {
  225. this->combinationKeys |= combinationKey_leftControl;
  226. } else if (event.dsrKey == DsrKey_RightControl) {
  227. this->combinationKeys |= combinationKey_rightControl;
  228. }
  229. } else if (event.keyboardEventType == KeyboardEventType::KeyUp) {
  230. if (event.dsrKey == DsrKey_LeftShift) {
  231. this->combinationKeys &= ~combinationKey_leftShift;
  232. } else if (event.dsrKey == DsrKey_RightShift) {
  233. this->combinationKeys &= ~combinationKey_rightShift;
  234. } else if (event.dsrKey == DsrKey_LeftControl) {
  235. this->combinationKeys &= ~combinationKey_leftControl;
  236. } else if (event.dsrKey == DsrKey_RightControl) {
  237. this->combinationKeys &= ~combinationKey_rightControl;
  238. }
  239. } else if (event.keyboardEventType == KeyboardEventType::KeyType) {
  240. int64_t textLength = string_length(this->text.value);
  241. bool selected = this->selectionStart != this->beamLocation;
  242. bool printable = event.character == U'\t' || (31 < event.character && event.character < 127) || 159 < event.character;
  243. bool canGoLeft = textLength > 0 && this->beamLocation > 0;
  244. bool canGoRight = textLength > 0 && this->beamLocation < textLength;
  245. bool holdShift = this->combinationKeys & combinationKey_shift;
  246. bool holdControl = this->combinationKeys & combinationKey_control;
  247. bool removeSelection = !holdShift;
  248. if (selected && (event.dsrKey == DsrKey_BackSpace || event.dsrKey == DsrKey_Delete)) {
  249. // Remove selection
  250. this->replaceSelection(U"");
  251. } else if (event.dsrKey == DsrKey_BackSpace && canGoLeft) {
  252. // Erase left of beam
  253. this->beamLocation--;
  254. this->replaceSelection(U"");
  255. } else if (event.dsrKey == DsrKey_Delete && canGoRight) {
  256. // Erase right of beam
  257. this->beamLocation++;
  258. this->replaceSelection(U"");
  259. } else if (event.dsrKey == DsrKey_Home || (event.dsrKey == DsrKey_LeftArrow && holdControl)) {
  260. // Move to the start using Home or Ctrl + LeftArrow
  261. this->placeBeam(0, removeSelection);
  262. } else if (event.dsrKey == DsrKey_End || (event.dsrKey == DsrKey_RightArrow && holdControl)) {
  263. // Move to the end using End or Ctrl + RightArrow
  264. this->placeBeam(textLength, removeSelection);
  265. } else if (event.dsrKey == DsrKey_LeftArrow && canGoLeft) {
  266. // Move left using LeftArrow
  267. this->placeBeam(this->beamLocation - 1, removeSelection);
  268. } else if (event.dsrKey == DsrKey_RightArrow && canGoRight) {
  269. // Move right using RightArrow
  270. this->placeBeam(this->beamLocation + 1, removeSelection);
  271. } else if (printable) {
  272. this->replaceSelection(event.character);
  273. }
  274. //printText(U"KeyType char=", event.character, " key=", event.dsrKey, U"\n");
  275. }
  276. VisualComponent::receiveKeyboardEvent(event);
  277. }
  278. bool TextBox::pointIsInside(const IVector2D& pixelPosition) {
  279. this->generateGraphics();
  280. // Get the point relative to the component instead of its direct container
  281. IVector2D localPoint = pixelPosition - this->location.upperLeft();
  282. // Sample opacity at the location
  283. return dsr::image_readPixel_border(this->image, localPoint.x, localPoint.y).alpha > 127;
  284. }
  285. void TextBox::changedTheme(VisualTheme newTheme) {
  286. this->textBox = theme_getScalableImage(newTheme, U"TextBox");
  287. this->hasImages = false;
  288. }
  289. void TextBox::completeAssets() {
  290. if (this->textBox.methodIndex == -1) {
  291. this->textBox = theme_getScalableImage(theme_getDefault(), U"TextBox");
  292. }
  293. if (this->font.get() == nullptr) {
  294. this->font = font_getDefault();
  295. }
  296. }
  297. void TextBox::changedLocation(const IRect &oldLocation, const IRect &newLocation) {
  298. // If the component has changed dimensions then redraw the image
  299. if (oldLocation.size() != newLocation.size()) {
  300. this->hasImages = false;
  301. }
  302. }
  303. void TextBox::changedAttribute(const ReadableString &name) {
  304. if (!string_caseInsensitiveMatch(name, U"Visible")) {
  305. this->hasImages = false;
  306. if (string_caseInsensitiveMatch(name, U"Text")) {
  307. this->limitSelection();
  308. }
  309. }
  310. }