OpenTTD Source  14.0-beta1
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 <http://www.gnu.org/licenses/>.
6  */
7 
10 #include "stdafx.h"
11 
12 #include "textbuf_type.h"
13 #include "string_func.h"
14 #include "strings_func.h"
15 #include "gfx_type.h"
16 #include "gfx_func.h"
17 #include "window_func.h"
18 #include "core/alloc_func.hpp"
19 
20 #include "safeguards.h"
21 
28 std::optional<std::string> GetClipboardContents();
29 
30 int _caret_timer;
31 
32 
39 bool Textbuf::CanDelChar(bool backspace)
40 {
41  return backspace ? this->caretpos != 0 : this->caretpos < this->bytes - 1;
42 }
43 
50 bool 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  char *s = this->buf + this->caretpos;
62  uint16_t len = 0;
63 
64  if (word) {
65  /* Delete a complete word. */
66  if (backspace) {
67  /* Delete whitespace and word in front of the caret. */
68  len = this->caretpos - (uint16_t)this->char_iter->Prev(StringIterator::ITER_WORD);
69  s -= len;
70  } else {
71  /* Delete word and following whitespace following the caret. */
72  len = (uint16_t)this->char_iter->Next(StringIterator::ITER_WORD) - this->caretpos;
73  }
74  /* Update character count. */
75  for (const char *ss = s; ss < s + len; Utf8Consume(&ss)) {
76  this->chars--;
77  }
78  } else {
79  /* Delete a single character. */
80  if (backspace) {
81  /* Delete the last code point in front of the caret. */
82  s = Utf8PrevChar(s);
83  char32_t c;
84  len = (uint16_t)Utf8Decode(&c, s);
85  this->chars--;
86  } else {
87  /* Delete the complete character following the caret. */
88  len = (uint16_t)this->char_iter->Next(StringIterator::ITER_CHARACTER) - this->caretpos;
89  /* Update character count. */
90  for (const char *ss = s; ss < s + len; Utf8Consume(&ss)) {
91  this->chars--;
92  }
93  }
94  }
95 
96  /* Move the remaining characters over the marker */
97  memmove(s, s + len, this->bytes - (s - this->buf) - len);
98  this->bytes -= len;
99 
100  if (backspace) this->caretpos -= len;
101 
102  this->UpdateStringIter();
103  this->UpdateWidth();
104  this->UpdateCaretPosition();
105  this->UpdateMarkedText();
106 
107  return true;
108 }
109 
114 {
115  memset(this->buf, 0, this->max_bytes);
116  this->bytes = this->chars = 1;
117  this->pixels = this->caretpos = this->caretxoffs = 0;
118  this->markpos = this->markend = this->markxoffs = this->marklength = 0;
119  this->UpdateStringIter();
120 }
121 
129 bool Textbuf::InsertChar(char32_t key)
130 {
131  uint16_t len = (uint16_t)Utf8CharLen(key);
132  if (this->bytes + len <= this->max_bytes && this->chars + 1 <= this->max_chars) {
133  memmove(this->buf + this->caretpos + len, this->buf + this->caretpos, this->bytes - this->caretpos);
134  Utf8Encode(this->buf + this->caretpos, key);
135  this->chars++;
136  this->bytes += len;
137  this->caretpos += len;
138 
139  this->UpdateStringIter();
140  this->UpdateWidth();
141  this->UpdateCaretPosition();
142  this->UpdateMarkedText();
143  return true;
144  }
145  return false;
146 }
147 
159 bool Textbuf::InsertString(const char *str, bool marked, const char *caret, const char *insert_location, const char *replacement_end)
160 {
161  uint16_t insertpos = (marked && this->marklength != 0) ? this->markpos : this->caretpos;
162  if (insert_location != nullptr) {
163  insertpos = insert_location - this->buf;
164  if (insertpos > this->bytes) return false;
165 
166  if (replacement_end != nullptr) {
167  this->DeleteText(insertpos, replacement_end - this->buf, str == nullptr);
168  }
169  } else {
170  if (marked) this->DiscardMarkedText(str == nullptr);
171  }
172 
173  if (str == nullptr) return false;
174 
175  uint16_t bytes = 0, chars = 0;
176  char32_t c;
177  for (const char *ptr = str; (c = Utf8Consume(&ptr)) != '\0';) {
178  if (!IsValidChar(c, this->afilter)) break;
179 
180  byte len = Utf8CharLen(c);
181  if (this->bytes + bytes + len > this->max_bytes) break;
182  if (this->chars + chars + 1 > this->max_chars) break;
183 
184  bytes += len;
185  chars++;
186 
187  /* Move caret if needed. */
188  if (ptr == caret) this->caretpos = insertpos + bytes;
189  }
190 
191  if (bytes == 0) return false;
192 
193  if (marked) {
194  this->markpos = insertpos;
195  this->markend = insertpos + bytes;
196  }
197 
198  memmove(this->buf + insertpos + bytes, this->buf + insertpos, this->bytes - insertpos);
199  memcpy(this->buf + insertpos, str, bytes);
200 
201  this->bytes += bytes;
202  this->chars += chars;
203  if (!marked && caret == nullptr) this->caretpos += bytes;
204  assert(this->bytes <= this->max_bytes);
205  assert(this->chars <= this->max_chars);
206  this->buf[this->bytes - 1] = '\0'; // terminating zero
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().c_str(), false);
228 }
229 
236 void Textbuf::DeleteText(uint16_t from, uint16_t to, bool update)
237 {
238  uint c = 0;
239  const char *s = this->buf + from;
240  while (s < this->buf + to) {
241  Utf8Consume(&s);
242  c++;
243  }
244 
245  /* Strip marked characters from buffer. */
246  memmove(this->buf + from, this->buf + to, this->bytes - to);
247  this->bytes -= to - from;
248  this->chars -= c;
249 
250  auto fixup = [&](uint16_t &pos) {
251  if (pos <= from) return;
252  if (pos <= to) {
253  pos = from;
254  } else {
255  pos -= to - from;
256  }
257  };
258 
259  /* Fixup caret if needed. */
260  fixup(this->caretpos);
261 
262  /* Fixup marked text if needed. */
263  fixup(this->markpos);
264  fixup(this->markend);
265 
266  if (update) {
267  this->UpdateStringIter();
268  this->UpdateCaretPosition();
269  this->UpdateMarkedText();
270  }
271 }
272 
277 void Textbuf::DiscardMarkedText(bool update)
278 {
279  if (this->markend == 0) return;
280 
281  this->DeleteText(this->markpos, this->markend, update);
282  this->markpos = this->markend = this->markxoffs = this->marklength = 0;
283 }
284 
289 const char *Textbuf::GetText() const
290 {
291  return this->buf;
292 }
293 
296 {
297  this->char_iter->SetString(this->buf);
298  size_t pos = this->char_iter->SetCurPosition(this->caretpos);
299  this->caretpos = pos == StringIterator::END ? 0 : (uint16_t)pos;
300 }
301 
304 {
305  this->pixels = GetStringBoundingBox(this->buf, FS_NORMAL).width;
306 }
307 
310 {
311  this->caretxoffs = this->chars > 1 ? GetCharPosInString(this->buf, this->buf + this->caretpos, FS_NORMAL).x : 0;
312 }
313 
316 {
317  if (this->markend != 0) {
318  this->markxoffs = GetCharPosInString(this->buf, this->buf + this->markpos, FS_NORMAL).x;
319  this->marklength = GetCharPosInString(this->buf, this->buf + this->markend, FS_NORMAL).x - this->markxoffs;
320  } else {
321  this->markxoffs = this->marklength = 0;
322  }
323 }
324 
331 bool Textbuf::MovePos(uint16_t keycode)
332 {
333  switch (keycode) {
334  case WKC_LEFT:
335  case WKC_CTRL | WKC_LEFT: {
336  if (this->caretpos == 0) break;
337 
338  size_t pos = this->char_iter->Prev(keycode & WKC_CTRL ? StringIterator::ITER_WORD : StringIterator::ITER_CHARACTER);
339  if (pos == StringIterator::END) return true;
340 
341  this->caretpos = (uint16_t)pos;
342  this->UpdateCaretPosition();
343  return true;
344  }
345 
346  case WKC_RIGHT:
347  case WKC_CTRL | WKC_RIGHT: {
348  if (this->caretpos >= this->bytes - 1) break;
349 
350  size_t pos = this->char_iter->Next(keycode & WKC_CTRL ? StringIterator::ITER_WORD : StringIterator::ITER_CHARACTER);
351  if (pos == StringIterator::END) return true;
352 
353  this->caretpos = (uint16_t)pos;
354  this->UpdateCaretPosition();
355  return true;
356  }
357 
358  case WKC_HOME:
359  this->caretpos = 0;
360  this->char_iter->SetCurPosition(this->caretpos);
361  this->UpdateCaretPosition();
362  return true;
363 
364  case WKC_END:
365  this->caretpos = this->bytes - 1;
366  this->char_iter->SetCurPosition(this->caretpos);
367  this->UpdateCaretPosition();
368  return true;
369 
370  default:
371  break;
372  }
373 
374  return false;
375 }
376 
383 Textbuf::Textbuf(uint16_t max_bytes, uint16_t max_chars)
384  : buf(MallocT<char>(max_bytes)), char_iter(StringIterator::Create())
385 {
386  assert(max_bytes != 0);
387  assert(max_chars != 0);
388 
389  this->afilter = CS_ALPHANUMERAL;
390  this->max_bytes = max_bytes;
391  this->max_chars = max_chars == UINT16_MAX ? max_bytes : max_chars;
392  this->caret = true;
393  this->DeleteAll();
394 }
395 
396 Textbuf::~Textbuf()
397 {
398  free(this->buf);
399 }
400 
406 {
407  this->Assign(GetString(string));
408 }
409 
414 void Textbuf::Assign(const std::string_view text)
415 {
416  const char *last_of = &this->buf[this->max_bytes - 1];
417  strecpy(this->buf, text.data(), last_of);
418  StrMakeValidInPlace(this->buf, last_of, SVS_NONE);
419 
420  /* Make sure the name isn't too long for the text buffer in the number of
421  * characters (not bytes). max_chars also counts the '\0' characters. */
422  while (Utf8StringLength(this->buf) + 1 > this->max_chars) {
423  *Utf8PrevChar(this->buf + strlen(this->buf)) = '\0';
424  }
425 
426  this->UpdateSize();
427 }
428 
429 
436 {
437  const char *buf = this->buf;
438 
439  this->chars = this->bytes = 1; // terminating zero
440 
441  char32_t c;
442  while ((c = Utf8Consume(&buf)) != '\0') {
443  this->bytes += Utf8CharLen(c);
444  this->chars++;
445  }
446  assert(this->bytes <= this->max_bytes);
447  assert(this->chars <= this->max_chars);
448 
449  this->caretpos = this->bytes - 1;
450  this->UpdateStringIter();
451  this->UpdateWidth();
452  this->UpdateMarkedText();
453 
454  this->UpdateCaretPosition();
455 }
456 
462 {
463  /* caret changed? */
464  bool b = !!(_caret_timer & 0x20);
465 
466  if (b != this->caret) {
467  this->caret = b;
468  return true;
469  }
470  return false;
471 }
472 
473 HandleKeyPressResult Textbuf::HandleKeyPress(char32_t key, uint16_t keycode)
474 {
475  bool edited = false;
476 
477  switch (keycode) {
478  case WKC_ESC: return HKPR_CANCEL;
479 
480  case WKC_RETURN: case WKC_NUM_ENTER: return HKPR_CONFIRM;
481 
482  case (WKC_CTRL | 'V'):
483  case (WKC_SHIFT | WKC_INSERT):
484  edited = this->InsertClipboard();
485  break;
486 
487  case (WKC_CTRL | 'U'):
488  this->DeleteAll();
489  edited = true;
490  break;
491 
492  case WKC_BACKSPACE: case WKC_DELETE:
493  case WKC_CTRL | WKC_BACKSPACE: case WKC_CTRL | WKC_DELETE:
494  edited = this->DeleteChar(keycode);
495  break;
496 
497  case WKC_LEFT: case WKC_RIGHT: case WKC_END: case WKC_HOME:
498  case WKC_CTRL | WKC_LEFT: case WKC_CTRL | WKC_RIGHT:
499  this->MovePos(keycode);
500  break;
501 
502  default:
503  if (IsValidChar(key, this->afilter)) {
504  edited = this->InsertChar(key);
505  } else {
506  return HKPR_NOT_HANDLED;
507  }
508  break;
509  }
510 
511  return edited ? HKPR_EDITING : HKPR_CURSOR;
512 }
HKPR_EDITING
@ HKPR_EDITING
Textbuf content changed.
Definition: textbuf_type.h:22
Textbuf::InsertChar
bool InsertChar(char32_t key)
Insert a character to a textbuffer.
Definition: textbuf.cpp:129
HKPR_CONFIRM
@ HKPR_CONFIRM
Return or enter key pressed.
Definition: textbuf_type.h:24
textbuf_type.h
Textbuf::markend
uint16_t markend
the end position of the marked area in the buffer, in bytes
Definition: textbuf_type.h:42
Utf8CharLen
int8_t Utf8CharLen(char32_t c)
Return the length of a UTF-8 encoded character.
Definition: string_func.h:104
StringID
uint32_t StringID
Numeric value that represents a string, independent of the selected language.
Definition: strings_type.h:16
StringIterator::END
static const size_t END
Sentinel to indicate end-of-iteration.
Definition: string_base.h:23
Textbuf::Assign
void Assign(StringID string)
Render a string into the textbuffer.
Definition: textbuf.cpp:405
Textbuf::max_bytes
uint16_t max_bytes
the maximum size of the buffer in bytes (including terminating '\0')
Definition: textbuf_type.h:33
Textbuf::pixels
uint16_t pixels
the current size of the string in pixels
Definition: textbuf_type.h:37
Utf8PrevChar
char * Utf8PrevChar(char *s)
Retrieve the previous UNICODE character in an UTF-8 encoded string.
Definition: string_func.h:148
Textbuf::caretpos
uint16_t caretpos
the current position of the caret in the buffer, in bytes
Definition: textbuf_type.h:39
Textbuf::markpos
uint16_t markpos
the start position of the marked area in the buffer, in bytes
Definition: textbuf_type.h:41
Textbuf::MovePos
bool MovePos(uint16_t keycode)
Handle text navigation with arrow keys left/right.
Definition: textbuf.cpp:331
Textbuf::InsertString
bool InsertString(const char *str, bool marked, const char *caret=nullptr, const char *insert_location=nullptr, const char *replacement_end=nullptr)
Insert a string into the text buffer.
Definition: textbuf.cpp:159
StringIterator::ITER_CHARACTER
@ ITER_CHARACTER
Iterate over characters (or more exactly grapheme clusters).
Definition: string_base.h:18
Textbuf::buf
char *const buf
buffer in which text is saved
Definition: textbuf_type.h:32
gfx_func.h
Utf8StringLength
size_t Utf8StringLength(const char *s)
Get the length of an UTF-8 encoded string in number of characters and thus not the number of bytes th...
Definition: string.cpp:378
Textbuf::HandleCaret
bool HandleCaret()
Handle the flashing of the caret.
Definition: textbuf.cpp:461
Textbuf::markxoffs
uint16_t markxoffs
the start position of the marked area in pixels
Definition: textbuf_type.h:43
StringIterator
Class for iterating over different kind of parts of a string.
Definition: string_base.h:14
FS_NORMAL
@ FS_NORMAL
Index of the normal font in the font tables.
Definition: gfx_type.h:203
free
void free(const void *ptr)
Version of the standard free that accepts const pointers.
Definition: stdafx.h:379
StrMakeValidInPlace
void StrMakeValidInPlace(char *str, const char *last, StringValidationSettings settings)
Scans the string for invalid characters and replaces then with a question mark '?' (if not ignored).
Definition: string.cpp:185
Textbuf::bytes
uint16_t bytes
the current size of the string in bytes (including terminating '\0')
Definition: textbuf_type.h:35
GetClipboardContents
std::optional< std::string > GetClipboardContents()
Try to retrieve the current clipboard contents.
Definition: unix.cpp:214
Textbuf::GetText
const char * GetText() const
Get the current text.
Definition: textbuf.cpp:289
HandleKeyPressResult
HandleKeyPressResult
Return values for Textbuf::HandleKeypress.
Definition: textbuf_type.h:20
Textbuf::UpdateMarkedText
void UpdateMarkedText()
Update pixel positions of the marked text area.
Definition: textbuf.cpp:315
safeguards.h
Textbuf::caret
bool caret
is the caret ("_") visible or not
Definition: textbuf_type.h:38
Textbuf::UpdateCaretPosition
void UpdateCaretPosition()
Update pixel position of the caret.
Definition: textbuf.cpp:309
Textbuf::afilter
CharSetFilter afilter
Allowed characters.
Definition: textbuf_type.h:31
Textbuf::DeleteChar
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
StringIterator::ITER_WORD
@ ITER_WORD
Iterate over words.
Definition: string_base.h:19
stdafx.h
CS_ALPHANUMERAL
@ CS_ALPHANUMERAL
Both numeric and alphabetic and spaces and stuff.
Definition: string_type.h:25
Textbuf::Textbuf
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:383
string_func.h
strings_func.h
IsValidChar
bool IsValidChar(char32_t key, CharSetFilter afilter)
Only allow certain keys.
Definition: string.cpp:415
Textbuf::InsertClipboard
bool InsertClipboard()
Insert a chunk of text from the clipboard onto the textbuffer.
Definition: textbuf.cpp:222
Textbuf::max_chars
uint16_t max_chars
the maximum size of the buffer in characters (including terminating '\0')
Definition: textbuf_type.h:34
alloc_func.hpp
Textbuf::DeleteText
void DeleteText(uint16_t from, uint16_t to, bool update)
Delete a part of the text.
Definition: textbuf.cpp:236
Textbuf::UpdateSize
void UpdateSize()
Update Textbuf type with its actual physical character and screenlength Get the count of characters i...
Definition: textbuf.cpp:435
Textbuf::marklength
uint16_t marklength
the length of the marked area in pixels
Definition: textbuf_type.h:44
GetString
std::string GetString(StringID string)
Resolve the given StringID into a std::string with all the associated DParam lookups and formatting.
Definition: strings.cpp:327
HKPR_CANCEL
@ HKPR_CANCEL
Escape key pressed.
Definition: textbuf_type.h:25
Textbuf::UpdateStringIter
void UpdateStringIter()
Update the character iter after the text has changed.
Definition: textbuf.cpp:295
SVS_NONE
@ SVS_NONE
Allow nothing and replace nothing.
Definition: string_type.h:45
Textbuf::chars
uint16_t chars
the current size of the string in characters (including terminating '\0')
Definition: textbuf_type.h:36
window_func.h
MallocT
T * MallocT(size_t num_elements)
Simplified allocation function that allocates the specified number of elements of the given type.
Definition: alloc_func.hpp:57
GetCharPosInString
Point GetCharPosInString(std::string_view str, const char *ch, FontSize start_fontsize)
Get the leading corner of a character in a single-line string relative to the start of the string.
Definition: gfx.cpp:892
Utf8Encode
size_t Utf8Encode(T buf, char32_t c)
Encode a unicode character and place it in the buffer.
Definition: string.cpp:479
Utf8Decode
size_t Utf8Decode(char32_t *c, const char *s)
Decode and consume the next UTF-8 encoded character.
Definition: string.cpp:438
HKPR_NOT_HANDLED
@ HKPR_NOT_HANDLED
Key does not affect editboxes.
Definition: textbuf_type.h:26
Textbuf::UpdateWidth
void UpdateWidth()
Update pixel width of the text.
Definition: textbuf.cpp:303
strecpy
char * strecpy(char *dst, const char *src, const char *last)
Copies characters from one buffer to another.
Definition: string.cpp:65
gfx_type.h
Textbuf::caretxoffs
uint16_t caretxoffs
the current position of the caret in pixels
Definition: textbuf_type.h:40
Textbuf::CanDelChar
bool CanDelChar(bool backspace)
Checks if it is possible to delete a character.
Definition: textbuf.cpp:39
Textbuf::DeleteAll
void DeleteAll()
Delete every character in the textbuffer.
Definition: textbuf.cpp:113
GetStringBoundingBox
Dimension GetStringBoundingBox(std::string_view str, FontSize start_fontsize)
Return the string dimension in pixels.
Definition: gfx.cpp:852
HKPR_CURSOR
@ HKPR_CURSOR
Non-text change, e.g. cursor position.
Definition: textbuf_type.h:23
Textbuf::DiscardMarkedText
void DiscardMarkedText(bool update=true)
Discard any marked text.
Definition: textbuf.cpp:277