OpenTTD Source 20261112-master-gbcbec5e63f
textbuf.cpp
Go to the documentation of this file.
1/*
2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <https://www.gnu.org/licenses/old-licenses/gpl-2.0>.
6 */
7
9
10#include "stdafx.h"
11
12#include "textbuf_type.h"
13#include "string_func.h"
14#include "strings_func.h"
15#include "core/utf8.hpp"
16#include "gfx_type.h"
17#include "gfx_func.h"
18#include "gfx_layout.h"
19
20#include "safeguards.h"
21
28std::optional<std::string> GetClipboardContents();
29
30int _caret_timer;
31
32
39bool Textbuf::CanDelChar(bool backspace)
40{
41 return backspace ? this->caretpos != 0 : this->caretpos < this->buf.size();
42}
43
50bool Textbuf::DeleteChar(uint16_t keycode)
51{
52 bool word = (keycode & WKC_CTRL) != 0;
53
54 keycode &= ~WKC_SPECIAL_KEYS;
55 if (keycode != WKC_BACKSPACE && keycode != WKC_DELETE) return false;
56
57 bool backspace = keycode == WKC_BACKSPACE;
58
59 if (!CanDelChar(backspace)) return false;
60
61 size_t start;
62 size_t len;
63 if (word) {
64 /* Delete a complete word. */
65 if (backspace) {
66 /* Delete whitespace and word in front of the caret. */
67 start = this->char_iter->Prev(StringIterator::ITER_WORD);
68 len = this->caretpos - start;
69 } else {
70 /* Delete word and following whitespace following the caret. */
71 start = this->caretpos;
72 len = this->char_iter->Next(StringIterator::ITER_WORD) - start;
73 }
74 /* Update character count. */
75 this->chars -= static_cast<uint16_t>(Utf8StringLength(std::string_view(this->buf).substr(start, len)));
76 } else {
77 /* Delete a single character. */
78 if (backspace) {
79 /* Delete the last code point in front of the caret. */
80 Utf8View view(this->buf);
81 auto it = view.GetIterAtByte(this->caretpos);
82 --it;
83 start = it.GetByteOffset();
84 len = this->caretpos - start;
85 this->chars--;
86 } else {
87 /* Delete the complete character following the caret. */
88 start = this->caretpos;
89 len = this->char_iter->Next(StringIterator::ITER_CHARACTER) - start;
90 /* Update character count. */
91 this->chars -= static_cast<uint16_t>(Utf8StringLength(std::string_view(this->buf).substr(start, len)));
92 }
93 }
94
95 /* Move the remaining characters over the marker */
96 this->buf.erase(start, len);
97
98 if (backspace) this->caretpos -= static_cast<uint16_t>(len);
99
100 this->UpdateStringIter();
101 this->UpdateWidth();
102 this->UpdateCaretPosition();
103 this->UpdateMarkedText();
104
105 return true;
106}
107
112{
113 this->buf.clear();
114 this->chars = 1;
115 this->pixels = this->caretpos = this->caretxoffs = 0;
116 this->markpos = this->markend = this->markxoffs = this->marklength = 0;
117 this->UpdateStringIter();
118}
119
127bool Textbuf::InsertChar(char32_t key)
128{
129 auto [src, len] = EncodeUtf8(key);
130 if (this->buf.size() + len < this->max_bytes && this->chars + 1 <= this->max_chars) {
131 /* Make space in the string, then overwrite it with the Utf8 encoded character. */
132 this->buf.insert(this->caretpos, src, len);
133 this->chars++;
134 this->caretpos += len;
135
136 this->UpdateStringIter();
137 this->UpdateWidth();
138 this->UpdateCaretPosition();
139 this->UpdateMarkedText();
140 return true;
141 }
142 return false;
143}
144
156bool Textbuf::InsertString(std::string_view str, bool marked, std::optional<size_t> caret, std::optional<size_t> insert_location, std::optional<size_t> replacement_end)
157{
158 uint16_t insertpos = (marked && this->marklength != 0) ? this->markpos : this->caretpos;
159 if (insert_location.has_value()) {
160 insertpos = static_cast<uint16_t>(*insert_location);
161 if (insertpos >= this->buf.size()) return false;
162
163 if (replacement_end.has_value()) {
164 this->DeleteText(insertpos, static_cast<uint16_t>(*replacement_end), str.empty());
165 }
166 } else {
167 if (marked) this->DiscardMarkedText(str.empty());
168 }
169
170 if (str.empty()) return false;
171
172 uint16_t chars = 0;
173 uint16_t bytes;
174 {
175 Utf8View view(str);
176 auto cur = view.begin();
177 const auto end = view.end();
178 while (cur != end) {
179 if (!IsValidChar(*cur, this->afilter)) break;
180
181 auto next = cur;
182 ++next;
183 if (this->buf.size() + next.GetByteOffset() >= this->max_bytes) break;
184 if (this->chars + chars + 1 > this->max_chars) break;
185
186 cur = next;
187 chars++;
188 }
189 bytes = static_cast<uint16_t>(cur.GetByteOffset());
190 }
191 if (bytes == 0) return false;
192
193 /* Move caret if needed. */
194 if (caret.has_value()) this->caretpos = insertpos + static_cast<uint16_t>(*caret);
195
196 if (marked) {
197 this->markpos = insertpos;
198 this->markend = insertpos + bytes;
199 }
200
201 this->buf.insert(insertpos, str.substr(0, bytes));
202
203 this->chars += chars;
204 if (!marked && !caret.has_value()) this->caretpos += bytes;
205 assert(this->buf.size() < this->max_bytes);
206 assert(this->chars <= this->max_chars);
207
208 this->UpdateStringIter();
209 this->UpdateWidth();
210 this->UpdateCaretPosition();
211 this->UpdateMarkedText();
212
213 return true;
214}
215
223{
224 auto contents = GetClipboardContents();
225 if (!contents.has_value()) return false;
226
227 return this->InsertString(contents.value(), false);
228}
229
236void Textbuf::DeleteText(uint16_t from, uint16_t to, bool update)
237{
238 assert(from <= to);
239
240 /* Strip marked characters from buffer. */
241 this->chars -= static_cast<uint16_t>(Utf8StringLength(std::string_view(this->buf).substr(from, to - from)));
242 this->buf.erase(from, to - from);
243
244 auto fixup = [&](uint16_t &pos) {
245 if (pos <= from) return;
246 if (pos <= to) {
247 pos = from;
248 } else {
249 pos -= to - from;
250 }
251 };
252
253 /* Fixup caret if needed. */
254 fixup(this->caretpos);
255
256 /* Fixup marked text if needed. */
257 fixup(this->markpos);
258 fixup(this->markend);
259
260 if (update) {
261 this->UpdateStringIter();
262 this->UpdateCaretPosition();
263 this->UpdateMarkedText();
264 }
265}
266
272{
273 if (this->markend == 0) return;
274
275 this->DeleteText(this->markpos, this->markend, update);
276 this->markpos = this->markend = this->markxoffs = this->marklength = 0;
277}
278
283std::string_view Textbuf::GetText() const
284{
285 return this->buf;
286}
287
290{
291 this->char_iter->SetString(this->buf);
292 size_t pos = this->char_iter->SetCurPosition(this->caretpos);
293 this->caretpos = pos == StringIterator::END ? 0 : (uint16_t)pos;
294}
295
301
304{
305 const auto pos = GetCharPosInString(this->buf, this->caretpos, FontSize::Normal);
306 this->caretxoffs = _current_text_dir == TD_LTR ? pos.left : pos.right;
307}
308
311{
312 if (this->markend != 0) {
313 const auto pos = GetCharPosInString(this->buf, this->markpos, FontSize::Normal);
314 const auto end = GetCharPosInString(this->buf, this->markend, FontSize::Normal);
315 this->markxoffs = std::min(pos.left, end.left);
316 this->marklength = std::max(pos.right, end.right) - this->markxoffs;
317 } else {
318 this->markxoffs = this->marklength = 0;
319 }
320}
321
328{
329 if (this->caretpos == 0) return false;
330
331 size_t pos = this->char_iter->Prev(what);
332 if (pos == StringIterator::END) return true;
333
334 this->caretpos = static_cast<uint16_t>(pos);
335 this->UpdateCaretPosition();
336 return true;
337}
338
345{
346 if (this->caretpos >= this->buf.size()) return false;
347
348 size_t pos = this->char_iter->Next(what);
349 if (pos == StringIterator::END) return true;
350
351 this->caretpos = static_cast<uint16_t>(pos);
352 this->UpdateCaretPosition();
353 return true;
354}
355
362bool Textbuf::MovePos(uint16_t keycode)
363{
364 switch (keycode) {
365 case WKC_LEFT:
366 case WKC_CTRL | WKC_LEFT: {
367 auto move_type = (keycode & WKC_CTRL) != 0 ? StringIterator::ITER_WORD : StringIterator::ITER_CHARACTER;
368 return (_current_text_dir == TD_LTR) ? this->MovePrev(move_type) : this->MoveNext(move_type);
369 }
370
371 case WKC_RIGHT:
372 case WKC_CTRL | WKC_RIGHT: {
373 auto move_type = (keycode & WKC_CTRL) != 0 ? StringIterator::ITER_WORD : StringIterator::ITER_CHARACTER;
374 return (_current_text_dir == TD_LTR) ? this->MoveNext(move_type) : this->MovePrev(move_type);
375 }
376
377 case WKC_HOME:
378 this->caretpos = 0;
379 this->char_iter->SetCurPosition(this->caretpos);
380 this->UpdateCaretPosition();
381 return true;
382
383 case WKC_END:
384 this->caretpos = static_cast<uint16_t>(this->buf.size());
385 this->char_iter->SetCurPosition(this->caretpos);
386 this->UpdateCaretPosition();
387 return true;
388
389 default:
390 break;
391 }
392
393 return false;
394}
395
403 : char_iter(StringIterator::Create())
404{
405 assert(max_bytes != 0);
406 assert(max_chars != 0);
407
408 this->afilter = CS_ALPHANUMERAL;
409 this->max_bytes = max_bytes;
410 this->max_chars = max_chars == UINT16_MAX ? max_bytes : max_chars;
411 this->caret = true;
412 this->DeleteAll();
413}
414
419void Textbuf::Assign(std::string_view text)
420{
421 size_t bytes = std::min<size_t>(this->max_bytes - 1, text.size());
422 this->buf = StrMakeValid(text.substr(0, bytes));
423
424 /* Make sure the name isn't too long for the text buffer in the number of
425 * characters (not bytes). max_chars also counts the '\0' characters. */
426 Utf8View view(text);
427 auto it = view.begin();
428 const auto end = view.end();
429 for (size_t len = 1; len < this->max_chars && it != end; ++len) ++it;
430
431 if (it != end) {
432 this->buf.erase(it.GetByteOffset(), std::string::npos);
433 }
434
435 this->UpdateSize();
436}
437
438
445{
446 this->chars = static_cast<uint16_t>(Utf8StringLength(this->buf) + 1); // terminating zero
447 assert(this->buf.size() < this->max_bytes);
448 assert(this->chars <= this->max_chars);
449
450 this->caretpos = static_cast<uint16_t>(this->buf.size());
451 this->UpdateStringIter();
452 this->UpdateWidth();
453 this->UpdateMarkedText();
454
455 this->UpdateCaretPosition();
456}
457
463{
464 /* caret changed? */
465 bool b = !!(_caret_timer & 0x20);
466
467 if (b != this->caret) {
468 this->caret = b;
469 return true;
470 }
471 return false;
472}
473
474HandleKeyPressResult Textbuf::HandleKeyPress(char32_t key, uint16_t keycode)
475{
476 bool edited = false;
477
478 switch (keycode) {
479 case WKC_ESC:
481
482 case WKC_RETURN:
483 case WKC_NUM_ENTER:
485
486 case (WKC_CTRL | 'V'):
487 case (WKC_SHIFT | WKC_INSERT):
488 edited = this->InsertClipboard();
489 break;
490
491 case (WKC_CTRL | 'U'):
492 this->DeleteAll();
493 edited = true;
494 break;
495
496 case WKC_BACKSPACE: case WKC_DELETE:
497 case WKC_CTRL | WKC_BACKSPACE: case WKC_CTRL | WKC_DELETE:
498 edited = this->DeleteChar(keycode);
499 break;
500
501 case WKC_LEFT: case WKC_RIGHT: case WKC_END: case WKC_HOME:
502 case WKC_CTRL | WKC_LEFT: case WKC_CTRL | WKC_RIGHT:
503 this->MovePos(keycode);
504 break;
505
506 default:
507 if (IsValidChar(key, this->afilter)) {
508 edited = this->InsertChar(key);
509 } else {
511 }
512 break;
513 }
514
516}
Class for iterating over different kind of parts of a string.
Definition string_base.h:14
static const size_t END
Sentinel to indicate end-of-iteration.
Definition string_base.h:23
IterType
Type of the iterator.
Definition string_base.h:17
@ ITER_WORD
Iterate over words.
Definition string_base.h:19
@ ITER_CHARACTER
Iterate over characters (or more exactly grapheme clusters).
Definition string_base.h:18
Constant span of UTF-8 encoded data.
Definition utf8.hpp:28
iterator GetIterAtByte(size_t offset) const
Create iterator pointing at codepoint, which occupies the byte position "offset".
Definition utf8.cpp:81
Dimension GetStringBoundingBox(std::string_view str, FontSize start_fontsize)
Return the string dimension in pixels.
Definition gfx.cpp:894
Functions related to the gfx engine.
ParagraphLayouter::Position GetCharPosInString(std::string_view str, size_t pos, FontSize start_fontsize)
Get the leading corner of a character in a single-line string relative to the start of the string.
Functions related to laying out the texts.
Types related to the graphics and/or input devices.
@ Normal
Index of the normal font in the font tables.
Definition gfx_type.h:249
A number of safeguards to prevent using unsafe methods.
Definition of base types and functions in a cross-platform compatible way.
size_t Utf8StringLength(std::string_view str)
Get the length of an UTF-8 encoded string in number of characters and thus not the number of bytes th...
Definition string.cpp:350
bool IsValidChar(char32_t key, CharSetFilter afilter)
Only allow certain keys.
Definition string.cpp:374
static void StrMakeValid(Builder &builder, StringConsumer &consumer, StringValidationSettings settings)
Copies the valid (UTF-8) characters from consumer to the builder.
Definition string.cpp:118
Functions related to low-level strings.
@ CS_ALPHANUMERAL
Both numeric and alphabetic and spaces and stuff.
Definition string_type.h:25
TextDirection _current_text_dir
Text direction of the currently selected language.
Definition strings.cpp:55
Functions related to OTTD's strings.
@ TD_LTR
Text is written left-to-right by default.
value_type width
The width of the rectangle.
uint16_t pixels
the current size of the string in pixels
uint16_t caretpos
the current position of the caret in the buffer, in bytes
void UpdateSize()
Update Textbuf type with its actual physical character and screenlength Get the count of characters i...
Definition textbuf.cpp:444
bool MovePos(uint16_t keycode)
Handle text navigation with arrow keys left/right.
Definition textbuf.cpp:362
uint16_t markxoffs
the start position of the marked area in pixels
void UpdateMarkedText()
Update pixel positions of the marked text area.
Definition textbuf.cpp:310
void UpdateWidth()
Update pixel width of the text.
Definition textbuf.cpp:297
bool DeleteChar(uint16_t keycode)
Delete a character from a textbuffer, either with 'Delete' or 'Backspace' The character is delete fro...
Definition textbuf.cpp:50
void DeleteAll()
Delete every character in the textbuffer.
Definition textbuf.cpp:111
uint16_t max_bytes
the maximum size of the buffer in bytes (including terminating '\0')
std::string_view GetText() const
Get the current text.
Definition textbuf.cpp:283
uint16_t chars
the current size of the string in characters (including terminating '\0')
bool MovePrev(StringIterator::IterType what)
Move to previous character position.
Definition textbuf.cpp:327
uint16_t max_chars
the maximum size of the buffer in characters (including terminating '\0')
uint16_t markend
the end position of the marked area in the buffer, in bytes
void DeleteText(uint16_t from, uint16_t to, bool update)
Delete a part of the text.
Definition textbuf.cpp:236
bool MoveNext(StringIterator::IterType what)
Move to next character position.
Definition textbuf.cpp:344
bool InsertClipboard()
Insert a chunk of text from the clipboard onto the textbuffer.
Definition textbuf.cpp:222
bool InsertString(std::string_view str, bool marked, std::optional< size_t > caret=std::nullopt, std::optional< size_t > insert_location=std::nullopt, std::optional< size_t > replacement_end=std::nullopt)
Insert a string into the text buffer.
Definition textbuf.cpp:156
uint16_t caretxoffs
the current position of the caret in pixels
uint16_t marklength
the length of the marked area in pixels
uint16_t markpos
the start position of the marked area in the buffer, in bytes
bool CanDelChar(bool backspace)
Checks if it is possible to delete a character.
Definition textbuf.cpp:39
void Assign(std::string_view text)
Copy a string into the textbuffer.
Definition textbuf.cpp:419
void DiscardMarkedText(bool update=true)
Discard any marked text.
Definition textbuf.cpp:271
bool caret
is the caret ("_") visible or not
CharSetFilter afilter
Allowed characters.
bool InsertChar(char32_t key)
Insert a character to a textbuffer.
Definition textbuf.cpp:127
void UpdateStringIter()
Update the character iter after the text has changed.
Definition textbuf.cpp:289
bool HandleCaret()
Handle the flashing of the caret.
Definition textbuf.cpp:462
Textbuf(uint16_t max_bytes, uint16_t max_chars=UINT16_MAX)
Initialize the textbuffer by supplying it the buffer to write into and the maximum length of this buf...
Definition textbuf.cpp:402
std::string buf
buffer in which text is saved
void UpdateCaretPosition()
Update pixel position of the caret.
Definition textbuf.cpp:303
std::optional< std::string > GetClipboardContents()
Try to retrieve the current clipboard contents.
Definition unix.cpp:205
Stuff related to text buffers.
HandleKeyPressResult
Return values for Textbuf::HandleKeypress.
@ Confirm
Return or enter key pressed.
@ Cursor
Non-text change, e.g. cursor position.
@ Editing
Textbuf content changed.
@ NotHandled
Key does not affect editboxes.
@ Cancel
Escape key pressed.
std::optional< std::string > GetClipboardContents()
Try to retrieve the current clipboard contents.
Definition unix.cpp:205
std::pair< char[4], size_t > EncodeUtf8(char32_t c)
Encode a character to UTF-8.
Definition utf8.cpp:19
Handling of UTF-8 encoded data.