TextBox.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580
  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 <functional>
  25. using namespace dsr;
  26. PERSISTENT_DEFINITION(TextBox)
  27. void TextBox::declareAttributes(StructureDefinition &target) const {
  28. VisualComponent::declareAttributes(target);
  29. target.declareAttribute(U"BackColor");
  30. target.declareAttribute(U"ForeColor");
  31. target.declareAttribute(U"Text");
  32. target.declareAttribute(U"MultiLine");
  33. }
  34. Persistent* TextBox::findAttribute(const ReadableString &name) {
  35. if (string_caseInsensitiveMatch(name, U"Color") || string_caseInsensitiveMatch(name, U"BackColor")) {
  36. return &(this->backColor);
  37. } else if (string_caseInsensitiveMatch(name, U"ForeColor")) {
  38. return &(this->foreColor);
  39. } else if (string_caseInsensitiveMatch(name, U"Text")) {
  40. return &(this->text);
  41. } else if (string_caseInsensitiveMatch(name, U"MultiLine")) {
  42. return &(this->multiLine);
  43. } else {
  44. return VisualComponent::findAttribute(name);
  45. }
  46. }
  47. TextBox::TextBox() {}
  48. bool TextBox::isContainer() const {
  49. return false;
  50. }
  51. // Limit exclusive indices to the text.
  52. void TextBox::limitSelection() {
  53. int64_t textLength = string_length(this->text.value);
  54. if (this->selectionStart < 0) this->selectionStart = 0;
  55. if (this->beamLocation < 0) this->beamLocation = 0;
  56. if (this->selectionStart > textLength) this->selectionStart = textLength;
  57. if (this->beamLocation > textLength) this->beamLocation = textLength;
  58. }
  59. static void tabJump(int64_t &x, int64_t tabWidth) {
  60. x += tabWidth - (x % tabWidth);
  61. }
  62. static int64_t monospacesPerTab = 4;
  63. // Pre-condition: text does not contain any linebreak.
  64. void iterateCharactersInLine(const ReadableString& text, const RasterFont &font, std::function<void(int64_t index, DsrChar code, int64_t left, int64_t right)> characterAction) {
  65. int64_t right = 0;
  66. int64_t monospaceWidth = font_getMonospaceWidth(font);
  67. int64_t tabWidth = monospaceWidth * monospacesPerTab;
  68. for (int64_t i = 0; i <= string_length(text); i++) {
  69. DsrChar code = text[i];
  70. int64_t left = right;
  71. if (code == U'\t') {
  72. tabJump(right, tabWidth);
  73. } else {
  74. right += monospaceWidth;
  75. }
  76. characterAction(i, code, left, right);
  77. }
  78. }
  79. // Iterate over the whole text once for both selection and characters.
  80. // Returns the beam's X location in pixels.
  81. int64_t printMonospaceLine(OrderedImageRgbaU8 &target, const ReadableString& text, const RasterFont &font, ColorRgbaI32 foreColor, bool focused, int64_t originX, int64_t selectionLeft, int64_t selectionRight, int64_t beamIndex, int64_t topY, int64_t bottomY) {
  82. int64_t characterHeight = bottomY - topY;
  83. int64_t beamPixelX = 0;
  84. iterateCharactersInLine(text, font, [&target, &font, &foreColor, &beamPixelX, originX, selectionLeft, selectionRight, beamIndex, topY, characterHeight, focused](int64_t index, DsrChar code, int64_t left, int64_t right) {
  85. left += originX;
  86. right += originX;
  87. if (index == beamIndex) beamPixelX = left;
  88. if (focused && selectionLeft <= index && index < selectionRight) {
  89. draw_rectangle(target, IRect(left, topY, right - left, characterHeight), ColorRgbaI32(0, 0, 100, 255));
  90. font_printCharacter(target, font, code, IVector2D(left, topY), ColorRgbaI32(255, 255, 255, 255));
  91. } else {
  92. font_printCharacter(target, font, code, IVector2D(left, topY), foreColor);
  93. }
  94. });
  95. return beamPixelX;
  96. }
  97. void TextBox::indexLines() {
  98. int64_t newLength = string_length(this->text.value);
  99. if (newLength != this->indexedAtLength) {
  100. int64_t currentLength = 0;
  101. int64_t worstCaseLength = 0;
  102. // Index the lines for fast scrolling and rendering.
  103. this->lines.clear();
  104. int64_t sectionStart = 0;
  105. for (int64_t i = 0; i <= newLength; i++) {
  106. DsrChar c = this->text.value[i];
  107. if (c == U'\n' || c == U'\0') {
  108. if (currentLength > worstCaseLength) {
  109. worstCaseLength = currentLength;
  110. }
  111. currentLength = 0;
  112. this->lines.pushConstruct(sectionStart, i);
  113. sectionStart = i + 1;
  114. } else if (c == U'\t') {
  115. currentLength += 4;
  116. } else {
  117. currentLength += 1;
  118. }
  119. }
  120. this->indexedAtLength = newLength;
  121. this->worstCaseLineMonospaces = worstCaseLength;
  122. }
  123. }
  124. LVector2D TextBox::getTextOrigin(bool includeVerticalScroll) {
  125. int64_t rowStride = font_getSize(this->font);
  126. int64_t offsetX = this->borderX - this->horizontalScrollBar.getValue();
  127. int64_t offsetY = 0;
  128. if (this->multiLine.value) {
  129. offsetY = this->borderY;
  130. } else {
  131. offsetY = (image_getHeight(this->image) - rowStride) / 2;
  132. }
  133. if (includeVerticalScroll) {
  134. offsetY -= this->verticalScrollBar.getValue() * rowStride;
  135. }
  136. return LVector2D(offsetX, offsetY);
  137. }
  138. // TODO: Reuse scaled background images as a separate layer.
  139. // TODO: Allow using different colors for beam, selection, selected text, normal text...
  140. // Maybe ask a separate color palette for specific things using the specific class of textboxes.
  141. // Color palettes can be independent of the media machine, allowing them to be mixed freely with different themes.
  142. // Color palettes can be loaded together with the layout to instantly have the requested standard colors by name.
  143. // Color palettes can have a standard column order of input to easily pack multiple color themes into the same color palette image.
  144. // Just a long list of names for the different X coordinates and the user selects a Y coordinate as the color theme.
  145. // New components will have to use existing parts of the palette by keeping the names reusable.
  146. // Separate components should be able to override any color for programmability, but default values should refer to the current color palette.
  147. // If no color is assigned, the class will give it a standard color from the theme.
  148. // Should classes be separate for themes and palettes?
  149. void TextBox::generateGraphics() {
  150. int32_t width = this->location.width();
  151. int32_t height = this->location.height();
  152. if (width < 1) { width = 1; }
  153. if (height < 1) { height = 1; }
  154. bool focused = this->isFocused();
  155. if (!this->hasImages || this->drawnAsFocused != focused) {
  156. this->hasImages = true;
  157. this->drawnAsFocused = focused;
  158. completeAssets();
  159. this->indexLines();
  160. ColorRgbaI32 foreColorRgba = ColorRgbaI32(this->foreColor.value, 255);
  161. // Create a scaled image
  162. component_generateImage(this->theme, this->textBox, width, height, this->backColor.value.red, this->backColor.value.green, this->backColor.value.blue, 0, focused ? 1 : 0)(this->image);
  163. this->limitSelection();
  164. LVector2D origin = this->getTextOrigin(false);
  165. int64_t rowStride = font_getSize(this->font);
  166. int64_t targetHeight = image_getHeight(this->image);
  167. int64_t firstVisibleLine = this->verticalScrollBar.getValue();
  168. // Find character indices for left and right sides.
  169. int64_t selectionLeft = std::min(this->selectionStart, this->beamLocation);
  170. int64_t selectionRight = std::max(this->selectionStart, this->beamLocation);
  171. bool hasSelection = selectionLeft < selectionRight;
  172. // Draw the text with selection and get the beam's pixel location.
  173. int64_t topY = origin.y;
  174. for (int64_t row = firstVisibleLine; row < this->lines.length() && topY < targetHeight; row++) {
  175. int64_t startIndex = this->lines[row].lineStartIndex;
  176. int64_t endIndex = this->lines[row].lineEndIndex;
  177. ReadableString currentLine = string_exclusiveRange(this->text.value, startIndex, endIndex);
  178. int64_t beamPixelX = printMonospaceLine(this->image, currentLine, this->font, foreColorRgba, focused, origin.x, selectionLeft - startIndex, selectionRight - startIndex, this->beamLocation - startIndex, topY, topY + rowStride);
  179. // Draw a beam if the textbox is focused.
  180. if (focused && this->beamLocation >= startIndex && this->beamLocation <= endIndex) {
  181. int64_t beamWidth = 2;
  182. draw_rectangle(this->image, IRect(beamPixelX - 1, topY - 1, beamWidth, rowStride + 2), hasSelection ? ColorRgbaI32(255, 255, 255, 255) : foreColorRgba);
  183. }
  184. topY += rowStride;
  185. }
  186. this->verticalScrollBar.draw(this->image, this->theme, this->backColor.value);
  187. this->horizontalScrollBar.draw(this->image, this->theme, this->backColor.value);
  188. }
  189. }
  190. void TextBox::drawSelf(ImageRgbaU8& targetImage, const IRect &relativeLocation) {
  191. this->generateGraphics();
  192. draw_copy(targetImage, this->image, relativeLocation.left(), relativeLocation.top());
  193. }
  194. int64_t TextBox::findBeamLocationInLine(int64_t rowIndex, int64_t pixelX) {
  195. LVector2D origin = this->getTextOrigin(true);
  196. // Clamp to the closest row if going outside.
  197. if (rowIndex < 0) rowIndex = 0;
  198. if (rowIndex >= this->lines.length()) rowIndex = this->lines.length() - 1;
  199. int64_t beamIndex = 0;
  200. int64_t closestDistance = 1000000000000;
  201. int64_t startIndex = this->lines[rowIndex].lineStartIndex;
  202. int64_t endIndex = this->lines[rowIndex].lineEndIndex;
  203. ReadableString currentLine = string_exclusiveRange(this->text.value, startIndex, endIndex);
  204. iterateCharactersInLine(currentLine, font, [&beamIndex, &closestDistance, &origin, pixelX](int64_t index, DsrChar code, int64_t left, int64_t right) {
  205. int64_t center = origin.x + (left + right) / 2;
  206. int64_t newDistance = std::abs(pixelX - center);
  207. if (newDistance < closestDistance) {
  208. beamIndex = index;
  209. closestDistance = newDistance;
  210. }
  211. });
  212. return startIndex + beamIndex;
  213. }
  214. BeamLocation TextBox::findBeamLocation(const LVector2D &pixelLocation) {
  215. LVector2D origin = this->getTextOrigin(true);
  216. int64_t rowStride = font_getSize(this->font);
  217. int64_t rowIndex = (pixelLocation.y - origin.y) / rowStride;
  218. return BeamLocation(rowIndex, this->findBeamLocationInLine(rowIndex, pixelLocation.x));
  219. }
  220. static int64_t findBeamRow(List<LineIndex> lines, int64_t beamLocation) {
  221. int64_t result = 0;
  222. for (int64_t row = 0; row < lines.length(); row++) {
  223. int64_t startIndex = lines[row].lineStartIndex;
  224. int64_t endIndex = lines[row].lineEndIndex;
  225. if (beamLocation >= startIndex && beamLocation <= endIndex) {
  226. result = row;
  227. }
  228. }
  229. return result;
  230. }
  231. // Returns the beam's pixel offset relative to the origin.
  232. static int64_t getBeamPixelOffset(const ReadableString &text, const RasterFont &font, List<LineIndex> lines, const BeamLocation &beam) {
  233. int64_t result = 0;
  234. int64_t lineStartIndex = lines[beam.rowIndex].lineStartIndex;
  235. int64_t lineEndIndex = lines[beam.rowIndex].lineEndIndex;
  236. int64_t localBeamIndex = beam.characterIndex - lineStartIndex;
  237. ReadableString currentLine = string_exclusiveRange(text, lineStartIndex, lineEndIndex);
  238. iterateCharactersInLine(currentLine, font, [&result, localBeamIndex](int64_t index, DsrChar code, int64_t left, int64_t right) {
  239. if (index == localBeamIndex) result = left;
  240. });
  241. return result;
  242. }
  243. void TextBox::receiveMouseEvent(const MouseEvent& event) {
  244. bool verticalScrollIntercepted = this->verticalScrollBar.receiveMouseEvent(this->location, event);
  245. bool horizontalScrollIntercepted = this->horizontalScrollBar.receiveMouseEvent(this->location, event);
  246. bool scrollIntercepted = verticalScrollIntercepted || horizontalScrollIntercepted;
  247. if (event.mouseEventType == MouseEventType::MouseDown && !scrollIntercepted) {
  248. this->mousePressed = true;
  249. BeamLocation newBeam = findBeamLocation(LVector2D(event.position.x - this->location.left(), event.position.y - this->location.top()));
  250. if (newBeam.characterIndex != this->selectionStart || newBeam.characterIndex != this->beamLocation) {
  251. this->selectionStart = newBeam.characterIndex;
  252. this->beamLocation = newBeam.characterIndex;
  253. this->hasImages = false;
  254. }
  255. } else if (this->mousePressed && event.mouseEventType == MouseEventType::MouseMove) {
  256. if (this->mousePressed) {
  257. BeamLocation newBeam = findBeamLocation(LVector2D(event.position.x - this->location.left(), event.position.y - this->location.top()));
  258. if (newBeam.characterIndex != this->beamLocation) {
  259. this->beamLocation = newBeam.characterIndex;
  260. this->hasImages = false;
  261. }
  262. }
  263. } else if (this->mousePressed && event.mouseEventType == MouseEventType::MouseUp) {
  264. this->mousePressed = false;
  265. }
  266. if (scrollIntercepted) {
  267. this->hasImages = false; // Force redraw on scrollbar interception
  268. } else {
  269. VisualComponent::receiveMouseEvent(event);
  270. }
  271. }
  272. ReadableString TextBox::getSelectedText() {
  273. int64_t selectionLeft = std::min(this->selectionStart, this->beamLocation);
  274. int64_t selectionRight = std::max(this->selectionStart, this->beamLocation);
  275. return string_exclusiveRange(this->text.value, selectionLeft, selectionRight);
  276. }
  277. void TextBox::replaceSelection(const ReadableString &replacingText) {
  278. int64_t selectionLeft = std::min(this->selectionStart, this->beamLocation);
  279. int64_t selectionRight = std::max(this->selectionStart, this->beamLocation);
  280. this->text.value = string_combine(string_before(this->text.value, selectionLeft), replacingText, string_from(this->text.value, selectionRight));
  281. // Place beam on the right side of the replacement without selecting anything
  282. this->selectionStart = selectionLeft + string_length(replacingText);
  283. this->beamLocation = selectionStart;
  284. this->hasImages = false;
  285. this->indexedAtLength = -1;
  286. this->indexLines();
  287. this->limitScrolling(true);
  288. }
  289. void TextBox::replaceSelection(DsrChar replacingCharacter) {
  290. int64_t selectionLeft = std::min(this->selectionStart, this->beamLocation);
  291. int64_t selectionRight = std::max(this->selectionStart, this->beamLocation);
  292. String newText = string_before(this->text.value, selectionLeft);
  293. string_appendChar(newText, replacingCharacter);
  294. string_append(newText, string_from(this->text.value, selectionRight));
  295. this->text.value = newText;
  296. // Place beam on the right side of the replacement without selecting anything
  297. this->selectionStart = selectionLeft + 1;
  298. this->beamLocation = selectionStart;
  299. this->hasImages = false;
  300. this->indexedAtLength = -1;
  301. this->indexLines();
  302. this->limitScrolling(true);
  303. }
  304. void TextBox::placeBeamAtCharacter(int64_t characterIndex, bool removeSelection) {
  305. this->beamLocation = characterIndex;
  306. if (removeSelection) {
  307. this->selectionStart = characterIndex;
  308. }
  309. this->hasImages = false;
  310. this->limitScrolling(true);
  311. }
  312. void TextBox::moveBeamVertically(int64_t rowIndexOffset, bool removeSelection) {
  313. // Find the current beam's row index.
  314. int64_t oldRowIndex = findBeamRow(this->lines, this->beamLocation);
  315. // Find another row.
  316. int64_t newRowIndex = oldRowIndex + rowIndexOffset;
  317. if (newRowIndex < 0) { newRowIndex = 0; }
  318. if (newRowIndex >= this->lines.length()) { newRowIndex = this->lines.length() - 1; }
  319. // Get old pixel offset from the beam.
  320. LVector2D origin = this->getTextOrigin(true);
  321. BeamLocation oldBeam = BeamLocation(oldRowIndex, this->beamLocation);
  322. int64_t oldPixelOffset = origin.x + getBeamPixelOffset(this->text.value, this->font, this->lines, oldBeam);
  323. // Get the closest location in the new row.
  324. int64_t newCharacterIndex = findBeamLocationInLine(newRowIndex, oldPixelOffset);
  325. placeBeamAtCharacter(newCharacterIndex, removeSelection);
  326. limitScrolling(true);
  327. }
  328. static const uint32_t combinationKey_shift = 1 << 0;
  329. static const uint32_t combinationKey_control = 1 << 1;
  330. static int64_t getLineStart(const ReadableString &text, int64_t searchStart) {
  331. for (int64_t i = searchStart - 1; i >= 0; i--) {
  332. if (text[i] == U'\n') {
  333. return i + 1;
  334. }
  335. }
  336. return 0;
  337. }
  338. static int64_t getLineEnd(const ReadableString &text, int64_t searchStart) {
  339. for (int64_t i = searchStart; i < string_length(text); i++) {
  340. if (text[i] == U'\n') {
  341. return i;
  342. }
  343. }
  344. return string_length(text);
  345. }
  346. void TextBox::receiveKeyboardEvent(const KeyboardEvent& event) {
  347. // Insert and scroll-lock is not supported.
  348. // To prevent getting stuck from missing a key event, one can reset by pressing and releasing again.
  349. // So if you press down both control keys and release one of them, it counts both as released.
  350. if (event.keyboardEventType == KeyboardEventType::KeyDown) {
  351. if (event.dsrKey == DsrKey_Shift) {
  352. this->combinationKeys |= combinationKey_shift; // Enable shift
  353. } else if (event.dsrKey == DsrKey_Control) {
  354. this->combinationKeys |= combinationKey_control; // Enable control
  355. }
  356. } else if (event.keyboardEventType == KeyboardEventType::KeyUp) {
  357. if (event.dsrKey == DsrKey_Shift) {
  358. this->combinationKeys &= ~combinationKey_shift; // Disable shift
  359. } else if (event.dsrKey == DsrKey_Control) {
  360. this->combinationKeys &= ~combinationKey_control; // Disable control
  361. }
  362. } else if (event.keyboardEventType == KeyboardEventType::KeyType) {
  363. int64_t textLength = string_length(this->text.value);
  364. bool selected = this->selectionStart != this->beamLocation;
  365. bool printable = event.character == U'\t' || (31 < event.character && event.character < 127) || 159 < event.character;
  366. bool canGoLeft = textLength > 0 && this->beamLocation > 0;
  367. bool canGoRight = textLength > 0 && this->beamLocation < textLength;
  368. bool holdShift = this->combinationKeys & combinationKey_shift;
  369. bool holdControl = this->combinationKeys & combinationKey_control;
  370. bool removeSelection = !holdShift;
  371. if (holdControl) {
  372. if (event.dsrKey == DsrKey_LeftArrow) {
  373. // Move to the line start using Ctrl + LeftArrow instead of Home
  374. this->placeBeamAtCharacter(getLineStart(this->text.value, this->beamLocation), removeSelection);
  375. } else if (event.dsrKey == DsrKey_RightArrow) {
  376. // Move to the line end using Ctrl + RightArrow instead of End
  377. this->placeBeamAtCharacter(getLineEnd(this->text.value, this->beamLocation), removeSelection);
  378. } else if (event.dsrKey == DsrKey_X) {
  379. // Cut selection using Ctrl + X
  380. if (this->window.get()) {
  381. this->window->saveToClipboard(this->getSelectedText());
  382. this->replaceSelection(U"");
  383. } else {
  384. sendWarning(U"No window handle found in TextBox when trying to cut text!");
  385. }
  386. } else if (event.dsrKey == DsrKey_C) {
  387. // Copy selection using Ctrl + C
  388. if (this->window.get()) {
  389. this->window->saveToClipboard(this->getSelectedText());
  390. } else {
  391. sendWarning(U"No window handle found in TextBox when trying to copy text!");
  392. }
  393. } else if (event.dsrKey == DsrKey_V) {
  394. // Paste selection using Ctrl + V
  395. if (this->window.get()) {
  396. this->replaceSelection(this->window->loadFromClipboard());
  397. } else {
  398. sendWarning(U"No window handle found in TextBox when trying to paste text!");
  399. }
  400. } else if (event.dsrKey == DsrKey_A) {
  401. // Select all using Ctrl + A
  402. this->selectionStart = 0;
  403. this->beamLocation = string_length(this->text.value);
  404. this->hasImages = false;
  405. } else if (event.dsrKey == DsrKey_N) {
  406. // Select nothing using Ctrl + N
  407. this->selectionStart = this->beamLocation;
  408. this->hasImages = false;
  409. }
  410. } else {
  411. if (selected && (event.dsrKey == DsrKey_BackSpace || event.dsrKey == DsrKey_Delete)) {
  412. // Remove selection
  413. this->replaceSelection(U"");
  414. } else if (event.dsrKey == DsrKey_BackSpace && canGoLeft) {
  415. // Erase left of beam
  416. this->beamLocation--;
  417. this->replaceSelection(U"");
  418. } else if (event.dsrKey == DsrKey_Delete && canGoRight) {
  419. // Erase right of beam
  420. this->beamLocation++;
  421. this->replaceSelection(U"");
  422. } else if (event.dsrKey == DsrKey_Home) {
  423. // Move to the line start using Home
  424. this->placeBeamAtCharacter(getLineStart(this->text.value, this->beamLocation), removeSelection);
  425. } else if (event.dsrKey == DsrKey_End) {
  426. // Move to the line end using End
  427. this->placeBeamAtCharacter(getLineEnd(this->text.value, this->beamLocation), removeSelection);
  428. } else if (event.dsrKey == DsrKey_LeftArrow && canGoLeft) {
  429. // Move left using LeftArrow
  430. this->placeBeamAtCharacter(this->beamLocation - 1, removeSelection);
  431. } else if (event.dsrKey == DsrKey_RightArrow && canGoRight) {
  432. // Move right using RightArrow
  433. this->placeBeamAtCharacter(this->beamLocation + 1, removeSelection);
  434. } else if (event.dsrKey == DsrKey_UpArrow) {
  435. // Move up using UpArrow
  436. this->moveBeamVertically(-1, removeSelection);
  437. } else if (event.dsrKey == DsrKey_DownArrow) {
  438. // Move down using DownArrow
  439. this->moveBeamVertically(1, removeSelection);
  440. } else if (event.dsrKey == DsrKey_Return) {
  441. if (this->multiLine.value) {
  442. this->replaceSelection(U'\n');
  443. }
  444. } else if (printable) {
  445. this->replaceSelection(event.character);
  446. }
  447. }
  448. //printText(U"KeyType char=", event.character, " key=", event.dsrKey, U"\n");
  449. }
  450. VisualComponent::receiveKeyboardEvent(event);
  451. }
  452. bool TextBox::pointIsInside(const IVector2D& pixelPosition) {
  453. this->generateGraphics();
  454. // Get the point relative to the component instead of its direct container
  455. IVector2D localPoint = pixelPosition - this->location.upperLeft();
  456. // Sample opacity at the location
  457. return dsr::image_readPixel_border(this->image, localPoint.x, localPoint.y).alpha > 127;
  458. }
  459. void TextBox::changedTheme(VisualTheme newTheme) {
  460. this->textBox = theme_getScalableImage(newTheme, U"TextBox");
  461. this->verticalScrollBar.loadTheme(newTheme, this->backColor.value);
  462. this->horizontalScrollBar.loadTheme(newTheme, this->backColor.value);
  463. this->hasImages = false;
  464. }
  465. void TextBox::loadFont() {
  466. if (!font_exists(this->font)) {
  467. this->font = font_getDefault();
  468. }
  469. if (!font_exists(this->font)) {
  470. throwError("Failed to load the default font for a ListBox!\n");
  471. }
  472. }
  473. void TextBox::completeAssets() {
  474. if (this->textBox.methodIndex == -1) {
  475. VisualTheme newTheme = theme_getDefault();
  476. this->textBox = theme_getScalableImage(newTheme, U"TextBox");
  477. this->verticalScrollBar.loadTheme(newTheme, this->backColor.value);
  478. this->horizontalScrollBar.loadTheme(newTheme, this->backColor.value);
  479. }
  480. this->loadFont();
  481. }
  482. void TextBox::changedLocation(const IRect &oldLocation, const IRect &newLocation) {
  483. // If the component has changed dimensions then redraw the image
  484. if (oldLocation.size() != newLocation.size()) {
  485. this->hasImages = false;
  486. this->limitScrolling(true);
  487. }
  488. }
  489. void TextBox::changedAttribute(const ReadableString &name) {
  490. if (!string_caseInsensitiveMatch(name, U"Visible")) {
  491. this->hasImages = false;
  492. if (string_caseInsensitiveMatch(name, U"Text")) {
  493. this->indexedAtLength = -1;
  494. this->limitSelection();
  495. this->limitScrolling(true);
  496. }
  497. }
  498. VisualComponent::changedAttribute(name);
  499. }
  500. void TextBox::updateScrollRange() {
  501. this->loadFont();
  502. // How high is one element?
  503. int64_t verticalStep = font_getSize(this->font);
  504. // How many elements are visible at the same time?
  505. int64_t visibleRangeY = (this->location.height() - this->borderY * 2) / verticalStep;
  506. if (visibleRangeY < 1) visibleRangeY = 1;
  507. // How many lines are there in total to see.
  508. int64_t itemCount = this->lines.length() + 1; // Reserve an extra line for the horizontal scroll-bar.
  509. // The range of indices that the listbox can start viewing from.
  510. int64_t maxScrollY = itemCount - visibleRangeY;
  511. // If visible range exceeds the collection, we should still allow starting element zero to get a valid range.
  512. if (maxScrollY < 0) maxScrollY = 0;
  513. // Apply the scroll range.
  514. this->verticalScrollBar.updateScrollRange(ScrollRange(0, maxScrollY, visibleRangeY));
  515. // Calculate range for horizontal scroll.
  516. int64_t monospaceWidth = font_getMonospaceWidth(this->font);
  517. int64_t rightMostPixel = this->worstCaseLineMonospaces * monospaceWidth;
  518. int64_t visibleRangeX = this->location.width() - this->borderX * 2;
  519. if (visibleRangeX < 1) visibleRangeX = 1;
  520. int64_t maxScrollX = rightMostPixel; // Allow scrolling all the way out, so that one can write left to right without constantly panorating on a long line.
  521. if (maxScrollX < 0) maxScrollX = 0;
  522. this->horizontalScrollBar.updateScrollRange(ScrollRange(0, maxScrollX, visibleRangeX));
  523. }
  524. void TextBox::limitScrolling(bool keepBeamVisible) {
  525. // Update the scroll range.
  526. this->indexLines();
  527. this->updateScrollRange();
  528. // Limit scrolling with the updated range.
  529. if (keepBeamVisible) {
  530. int64_t beamRow = findBeamRow(this->lines, this->beamLocation);
  531. BeamLocation beam = BeamLocation(beamRow, this->beamLocation);
  532. // What will origin.x be used for?
  533. int64_t pixelOffsetX = getBeamPixelOffset(this->text.value, this->font, this->lines, beam);
  534. this->verticalScrollBar.limitScrolling(this->location, true, beamRow);
  535. this->horizontalScrollBar.limitScrolling(this->location, true, pixelOffsetX);
  536. } else {
  537. this->verticalScrollBar.limitScrolling(this->location);
  538. this->horizontalScrollBar.limitScrolling(this->location);
  539. }
  540. }