TextBox.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587
  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. // TODO: Move stub implementation to an API and allow system wrappers to override it with a real implementation copying and pasting across different applications.
  273. String pasteBinStub;
  274. void saveToClipBoard(const ReadableString &text) {
  275. pasteBinStub = text;
  276. }
  277. ReadableString readFromClipBoard() {
  278. return pasteBinStub;
  279. }
  280. ReadableString TextBox::getSelectedText() {
  281. int64_t selectionLeft = std::min(this->selectionStart, this->beamLocation);
  282. int64_t selectionRight = std::max(this->selectionStart, this->beamLocation);
  283. return string_exclusiveRange(this->text.value, selectionLeft, selectionRight);
  284. }
  285. void TextBox::replaceSelection(const ReadableString &replacingText) {
  286. int64_t selectionLeft = std::min(this->selectionStart, this->beamLocation);
  287. int64_t selectionRight = std::max(this->selectionStart, this->beamLocation);
  288. this->text.value = string_combine(string_before(this->text.value, selectionLeft), replacingText, string_from(this->text.value, selectionRight));
  289. // Place beam on the right side of the replacement without selecting anything
  290. this->selectionStart = selectionLeft + string_length(replacingText);
  291. this->beamLocation = selectionStart;
  292. this->hasImages = false;
  293. this->indexedAtLength = -1;
  294. this->indexLines();
  295. this->limitScrolling(true);
  296. }
  297. void TextBox::replaceSelection(DsrChar replacingCharacter) {
  298. int64_t selectionLeft = std::min(this->selectionStart, this->beamLocation);
  299. int64_t selectionRight = std::max(this->selectionStart, this->beamLocation);
  300. String newText = string_before(this->text.value, selectionLeft);
  301. string_appendChar(newText, replacingCharacter);
  302. string_append(newText, string_from(this->text.value, selectionRight));
  303. this->text.value = newText;
  304. // Place beam on the right side of the replacement without selecting anything
  305. this->selectionStart = selectionLeft + 1;
  306. this->beamLocation = selectionStart;
  307. this->hasImages = false;
  308. this->indexedAtLength = -1;
  309. this->indexLines();
  310. this->limitScrolling(true);
  311. }
  312. void TextBox::placeBeamAtCharacter(int64_t characterIndex, bool removeSelection) {
  313. this->beamLocation = characterIndex;
  314. if (removeSelection) {
  315. this->selectionStart = characterIndex;
  316. }
  317. this->hasImages = false;
  318. this->limitScrolling(true);
  319. }
  320. void TextBox::moveBeamVertically(int64_t rowIndexOffset, bool removeSelection) {
  321. // Find the current beam's row index.
  322. int64_t oldRowIndex = findBeamRow(this->lines, this->beamLocation);
  323. // Find another row.
  324. int64_t newRowIndex = oldRowIndex + rowIndexOffset;
  325. if (newRowIndex < 0) { newRowIndex = 0; }
  326. if (newRowIndex >= this->lines.length()) { newRowIndex = this->lines.length() - 1; }
  327. // Get old pixel offset from the beam.
  328. LVector2D origin = this->getTextOrigin(true);
  329. BeamLocation oldBeam = BeamLocation(oldRowIndex, this->beamLocation);
  330. int64_t oldPixelOffset = origin.x + getBeamPixelOffset(this->text.value, this->font, this->lines, oldBeam);
  331. // Get the closest location in the new row.
  332. int64_t newCharacterIndex = findBeamLocationInLine(newRowIndex, oldPixelOffset);
  333. placeBeamAtCharacter(newCharacterIndex, removeSelection);
  334. limitScrolling(true);
  335. }
  336. static const uint32_t combinationKey_leftShift = 1 << 0;
  337. static const uint32_t combinationKey_rightShift = 1 << 1;
  338. static const uint32_t combinationKey_shift = combinationKey_leftShift | combinationKey_rightShift;
  339. static const uint32_t combinationKey_leftControl = 1 << 2;
  340. static const uint32_t combinationKey_rightControl = 1 << 3;
  341. static const uint32_t combinationKey_control = combinationKey_leftControl | combinationKey_rightControl;
  342. static int64_t getLineStart(const ReadableString &text, int64_t searchStart) {
  343. for (int64_t i = searchStart - 1; i >= 0; i--) {
  344. if (text[i] == U'\n') {
  345. return i + 1;
  346. }
  347. }
  348. return 0;
  349. }
  350. static int64_t getLineEnd(const ReadableString &text, int64_t searchStart) {
  351. for (int64_t i = searchStart; i < string_length(text); i++) {
  352. if (text[i] == U'\n') {
  353. return i;
  354. }
  355. }
  356. return string_length(text);
  357. }
  358. void TextBox::receiveKeyboardEvent(const KeyboardEvent& event) {
  359. // Insert and scroll-lock is not supported.
  360. if (event.keyboardEventType == KeyboardEventType::KeyDown) {
  361. if (event.dsrKey == DsrKey_LeftShift) {
  362. this->combinationKeys |= combinationKey_leftShift;
  363. } else if (event.dsrKey == DsrKey_RightShift) {
  364. this->combinationKeys |= combinationKey_rightShift;
  365. } else if (event.dsrKey == DsrKey_LeftControl) {
  366. this->combinationKeys |= combinationKey_leftControl;
  367. } else if (event.dsrKey == DsrKey_RightControl) {
  368. this->combinationKeys |= combinationKey_rightControl;
  369. }
  370. } else if (event.keyboardEventType == KeyboardEventType::KeyUp) {
  371. if (event.dsrKey == DsrKey_LeftShift) {
  372. this->combinationKeys &= ~combinationKey_leftShift;
  373. } else if (event.dsrKey == DsrKey_RightShift) {
  374. this->combinationKeys &= ~combinationKey_rightShift;
  375. } else if (event.dsrKey == DsrKey_LeftControl) {
  376. this->combinationKeys &= ~combinationKey_leftControl;
  377. } else if (event.dsrKey == DsrKey_RightControl) {
  378. this->combinationKeys &= ~combinationKey_rightControl;
  379. }
  380. } else if (event.keyboardEventType == KeyboardEventType::KeyType) {
  381. int64_t textLength = string_length(this->text.value);
  382. bool selected = this->selectionStart != this->beamLocation;
  383. bool printable = event.character == U'\t' || (31 < event.character && event.character < 127) || 159 < event.character;
  384. bool canGoLeft = textLength > 0 && this->beamLocation > 0;
  385. bool canGoRight = textLength > 0 && this->beamLocation < textLength;
  386. bool holdShift = this->combinationKeys & combinationKey_shift;
  387. bool holdControl = this->combinationKeys & combinationKey_control;
  388. bool removeSelection = !holdShift;
  389. if (holdControl) {
  390. if (event.dsrKey == DsrKey_LeftArrow) {
  391. // Move to the line start using Ctrl + LeftArrow instead of Home
  392. this->placeBeamAtCharacter(getLineStart(this->text.value, this->beamLocation), removeSelection);
  393. } else if (event.dsrKey == DsrKey_RightArrow) {
  394. // Move to the line end using Ctrl + RightArrow instead of End
  395. this->placeBeamAtCharacter(getLineEnd(this->text.value, this->beamLocation), removeSelection);
  396. } else if (event.dsrKey == DsrKey_X) {
  397. // Cut selection using Ctrl + X
  398. saveToClipBoard(this->getSelectedText());
  399. this->replaceSelection(U"");
  400. } else if (event.dsrKey == DsrKey_C) {
  401. // Copy selection using Ctrl + C
  402. saveToClipBoard(this->getSelectedText());
  403. } else if (event.dsrKey == DsrKey_V) {
  404. // Paste selection using Ctrl + V
  405. this->replaceSelection(readFromClipBoard());
  406. } else if (event.dsrKey == DsrKey_A) {
  407. // Select all using Ctrl + A
  408. this->selectionStart = 0;
  409. this->beamLocation = string_length(this->text.value);
  410. this->hasImages = false;
  411. } else if (event.dsrKey == DsrKey_N) {
  412. // Select nothing using Ctrl + N
  413. this->selectionStart = this->beamLocation;
  414. this->hasImages = false;
  415. }
  416. } else {
  417. if (selected && (event.dsrKey == DsrKey_BackSpace || event.dsrKey == DsrKey_Delete)) {
  418. // Remove selection
  419. this->replaceSelection(U"");
  420. } else if (event.dsrKey == DsrKey_BackSpace && canGoLeft) {
  421. // Erase left of beam
  422. this->beamLocation--;
  423. this->replaceSelection(U"");
  424. } else if (event.dsrKey == DsrKey_Delete && canGoRight) {
  425. // Erase right of beam
  426. this->beamLocation++;
  427. this->replaceSelection(U"");
  428. } else if (event.dsrKey == DsrKey_Home) {
  429. // Move to the line start using Home
  430. this->placeBeamAtCharacter(getLineStart(this->text.value, this->beamLocation), removeSelection);
  431. } else if (event.dsrKey == DsrKey_End) {
  432. // Move to the line end using End
  433. this->placeBeamAtCharacter(getLineEnd(this->text.value, this->beamLocation), removeSelection);
  434. } else if (event.dsrKey == DsrKey_LeftArrow && canGoLeft) {
  435. // Move left using LeftArrow
  436. this->placeBeamAtCharacter(this->beamLocation - 1, removeSelection);
  437. } else if (event.dsrKey == DsrKey_RightArrow && canGoRight) {
  438. // Move right using RightArrow
  439. this->placeBeamAtCharacter(this->beamLocation + 1, removeSelection);
  440. } else if (event.dsrKey == DsrKey_UpArrow) {
  441. // Move up using UpArrow
  442. this->moveBeamVertically(-1, removeSelection);
  443. } else if (event.dsrKey == DsrKey_DownArrow) {
  444. // Move down using DownArrow
  445. this->moveBeamVertically(1, removeSelection);
  446. } else if (event.dsrKey == DsrKey_Return) {
  447. if (this->multiLine.value) {
  448. this->replaceSelection(U'\n');
  449. }
  450. } else if (printable) {
  451. this->replaceSelection(event.character);
  452. }
  453. }
  454. //printText(U"KeyType char=", event.character, " key=", event.dsrKey, U"\n");
  455. }
  456. VisualComponent::receiveKeyboardEvent(event);
  457. }
  458. bool TextBox::pointIsInside(const IVector2D& pixelPosition) {
  459. this->generateGraphics();
  460. // Get the point relative to the component instead of its direct container
  461. IVector2D localPoint = pixelPosition - this->location.upperLeft();
  462. // Sample opacity at the location
  463. return dsr::image_readPixel_border(this->image, localPoint.x, localPoint.y).alpha > 127;
  464. }
  465. void TextBox::changedTheme(VisualTheme newTheme) {
  466. this->textBox = theme_getScalableImage(newTheme, U"TextBox");
  467. this->verticalScrollBar.loadTheme(newTheme, this->backColor.value);
  468. this->horizontalScrollBar.loadTheme(newTheme, this->backColor.value);
  469. this->hasImages = false;
  470. }
  471. void TextBox::loadFont() {
  472. if (!font_exists(this->font)) {
  473. this->font = font_getDefault();
  474. }
  475. if (!font_exists(this->font)) {
  476. throwError("Failed to load the default font for a ListBox!\n");
  477. }
  478. }
  479. void TextBox::completeAssets() {
  480. if (this->textBox.methodIndex == -1) {
  481. VisualTheme newTheme = theme_getDefault();
  482. this->textBox = theme_getScalableImage(newTheme, U"TextBox");
  483. this->verticalScrollBar.loadTheme(newTheme, this->backColor.value);
  484. this->horizontalScrollBar.loadTheme(newTheme, this->backColor.value);
  485. }
  486. this->loadFont();
  487. }
  488. void TextBox::changedLocation(const IRect &oldLocation, const IRect &newLocation) {
  489. // If the component has changed dimensions then redraw the image
  490. if (oldLocation.size() != newLocation.size()) {
  491. this->hasImages = false;
  492. this->limitScrolling(true);
  493. }
  494. }
  495. void TextBox::changedAttribute(const ReadableString &name) {
  496. if (!string_caseInsensitiveMatch(name, U"Visible")) {
  497. this->hasImages = false;
  498. if (string_caseInsensitiveMatch(name, U"Text")) {
  499. this->indexedAtLength = -1;
  500. this->limitSelection();
  501. this->limitScrolling(true);
  502. }
  503. }
  504. VisualComponent::changedAttribute(name);
  505. }
  506. void TextBox::updateScrollRange() {
  507. this->loadFont();
  508. // How high is one element?
  509. int64_t verticalStep = font_getSize(this->font);
  510. // How many elements are visible at the same time?
  511. int64_t visibleRangeY = (this->location.height() - this->borderY * 2) / verticalStep;
  512. if (visibleRangeY < 1) visibleRangeY = 1;
  513. // How many lines are there in total to see.
  514. int64_t itemCount = this->lines.length() + 1; // Reserve an extra line for the horizontal scroll-bar.
  515. // The range of indices that the listbox can start viewing from.
  516. int64_t maxScrollY = itemCount - visibleRangeY;
  517. // If visible range exceeds the collection, we should still allow starting element zero to get a valid range.
  518. if (maxScrollY < 0) maxScrollY = 0;
  519. // Apply the scroll range.
  520. this->verticalScrollBar.updateScrollRange(ScrollRange(0, maxScrollY, visibleRangeY));
  521. // Calculate range for horizontal scroll.
  522. int64_t monospaceWidth = font_getMonospaceWidth(this->font);
  523. int64_t rightMostPixel = this->worstCaseLineMonospaces * monospaceWidth;
  524. int64_t visibleRangeX = this->location.width() - this->borderX * 2;
  525. if (visibleRangeX < 1) visibleRangeX = 1;
  526. 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.
  527. if (maxScrollX < 0) maxScrollX = 0;
  528. this->horizontalScrollBar.updateScrollRange(ScrollRange(0, maxScrollX, visibleRangeX));
  529. }
  530. void TextBox::limitScrolling(bool keepBeamVisible) {
  531. // Update the scroll range.
  532. this->indexLines();
  533. this->updateScrollRange();
  534. // Limit scrolling with the updated range.
  535. if (keepBeamVisible) {
  536. int64_t beamRow = findBeamRow(this->lines, this->beamLocation);
  537. BeamLocation beam = BeamLocation(beamRow, this->beamLocation);
  538. // What will origin.x be used for?
  539. int64_t pixelOffsetX = getBeamPixelOffset(this->text.value, this->font, this->lines, beam);
  540. this->verticalScrollBar.limitScrolling(this->location, true, beamRow);
  541. this->horizontalScrollBar.limitScrolling(this->location, true, pixelOffsetX);
  542. } else {
  543. this->verticalScrollBar.limitScrolling(this->location);
  544. this->horizontalScrollBar.limitScrolling(this->location);
  545. }
  546. }