Fix #10490: Allow ships to exit depots if another is not moving at the exit point...
[openttd-github.git] / src / textbuf.cpp
blob2cffc81aeb5ee795297f70161aefb4bee6eb9a0b
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 */
8 /** @file textbuf.cpp Textbuffer handling. */
10 #include "stdafx.h"
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"
20 #include "safeguards.h"
22 /**
23 * Try to retrieve the current clipboard contents.
25 * @note OS-specific function.
26 * @return The (optional) clipboard contents.
28 std::optional<std::string> GetClipboardContents();
30 int _caret_timer;
33 /**
34 * Checks if it is possible to delete a character.
35 * @param backspace if set, delete the character before the caret,
36 * otherwise, delete the character after it.
37 * @return true if a character can be deleted in the given direction.
39 bool Textbuf::CanDelChar(bool backspace)
41 return backspace ? this->caretpos != 0 : this->caretpos < this->bytes - 1;
44 /**
45 * Delete a character from a textbuffer, either with 'Delete' or 'Backspace'
46 * The character is delete from the position the caret is at
47 * @param keycode Type of deletion, either WKC_BACKSPACE or WKC_DELETE
48 * @return Return true on successful change of Textbuf, or false otherwise
50 bool Textbuf::DeleteChar(uint16_t keycode)
52 bool word = (keycode & WKC_CTRL) != 0;
54 keycode &= ~WKC_SPECIAL_KEYS;
55 if (keycode != WKC_BACKSPACE && keycode != WKC_DELETE) return false;
57 bool backspace = keycode == WKC_BACKSPACE;
59 if (!CanDelChar(backspace)) return false;
61 char *s = this->buf + this->caretpos;
62 uint16_t len = 0;
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;
74 /* Update character count. */
75 for (const char *ss = s; ss < s + len; Utf8Consume(&ss)) {
76 this->chars--;
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--;
96 /* Move the remaining characters over the marker */
97 memmove(s, s + len, this->bytes - (s - this->buf) - len);
98 this->bytes -= len;
100 if (backspace) this->caretpos -= len;
102 this->UpdateStringIter();
103 this->UpdateWidth();
104 this->UpdateCaretPosition();
105 this->UpdateMarkedText();
107 return true;
111 * Delete every character in the textbuffer
113 void Textbuf::DeleteAll()
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();
123 * Insert a character to a textbuffer. If maxwidth of the Textbuf is zero,
124 * we don't care about the visual-length but only about the physical
125 * length of the string
126 * @param key Character to be inserted
127 * @return Return true on successful change of Textbuf, or false otherwise
129 bool Textbuf::InsertChar(char32_t key)
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;
139 this->UpdateStringIter();
140 this->UpdateWidth();
141 this->UpdateCaretPosition();
142 this->UpdateMarkedText();
143 return true;
145 return false;
149 * Insert a string into the text buffer. If maxwidth of the Textbuf is zero,
150 * we don't care about the visual-length but only about the physical
151 * length of the string.
152 * @param str String to insert.
153 * @param marked Replace the currently marked text with the new text.
154 * @param caret Move the caret to this point in the insertion string.
155 * @param insert_location Position at which to insert the string.
156 * @param replacement_end Replace all characters from #insert_location up to this location with the new string.
157 * @return True on successful change of Textbuf, or false otherwise.
159 bool Textbuf::InsertString(const char *str, bool marked, const char *caret, const char *insert_location, const char *replacement_end)
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;
166 if (replacement_end != nullptr) {
167 this->DeleteText(insertpos, replacement_end - this->buf, str == nullptr);
169 } else {
170 if (marked) this->DiscardMarkedText(str == nullptr);
173 if (str == nullptr) return false;
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;
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;
184 bytes += len;
185 chars++;
187 /* Move caret if needed. */
188 if (ptr == caret) this->caretpos = insertpos + bytes;
191 if (bytes == 0) return false;
193 if (marked) {
194 this->markpos = insertpos;
195 this->markend = insertpos + bytes;
198 memmove(this->buf + insertpos + bytes, this->buf + insertpos, this->bytes - insertpos);
199 memcpy(this->buf + insertpos, str, bytes);
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
208 this->UpdateStringIter();
209 this->UpdateWidth();
210 this->UpdateCaretPosition();
211 this->UpdateMarkedText();
213 return true;
217 * Insert a chunk of text from the clipboard onto the textbuffer. Get TEXT clipboard
218 * and append this up to the maximum length (either absolute or screenlength). If maxlength
219 * is zero, we don't care about the screenlength but only about the physical length of the string
220 * @return true on successful change of Textbuf, or false otherwise
222 bool Textbuf::InsertClipboard()
224 auto contents = GetClipboardContents();
225 if (!contents.has_value()) return false;
227 return this->InsertString(contents.value().c_str(), false);
231 * Delete a part of the text.
232 * @param from Start of the text to delete.
233 * @param to End of the text to delete.
234 * @param update Set to true if the internal state should be updated.
236 void Textbuf::DeleteText(uint16_t from, uint16_t to, bool update)
238 uint c = 0;
239 const char *s = this->buf + from;
240 while (s < this->buf + to) {
241 Utf8Consume(&s);
242 c++;
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;
250 auto fixup = [&](uint16_t &pos) {
251 if (pos <= from) return;
252 if (pos <= to) {
253 pos = from;
254 } else {
255 pos -= to - from;
259 /* Fixup caret if needed. */
260 fixup(this->caretpos);
262 /* Fixup marked text if needed. */
263 fixup(this->markpos);
264 fixup(this->markend);
266 if (update) {
267 this->UpdateStringIter();
268 this->UpdateCaretPosition();
269 this->UpdateMarkedText();
274 * Discard any marked text.
275 * @param update Set to true if the internal state should be updated.
277 void Textbuf::DiscardMarkedText(bool update)
279 if (this->markend == 0) return;
281 this->DeleteText(this->markpos, this->markend, update);
282 this->markpos = this->markend = this->markxoffs = this->marklength = 0;
286 * Get the current text.
287 * @return Current text.
289 const char *Textbuf::GetText() const
291 return this->buf;
294 /** Update the character iter after the text has changed. */
295 void Textbuf::UpdateStringIter()
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;
302 /** Update pixel width of the text. */
303 void Textbuf::UpdateWidth()
305 this->pixels = GetStringBoundingBox(this->buf, FS_NORMAL).width;
308 /** Update pixel position of the caret. */
309 void Textbuf::UpdateCaretPosition()
311 this->caretxoffs = this->chars > 1 ? GetCharPosInString(this->buf, this->buf + this->caretpos, FS_NORMAL).x : 0;
314 /** Update pixel positions of the marked text area. */
315 void Textbuf::UpdateMarkedText()
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;
326 * Handle text navigation with arrow keys left/right.
327 * This defines where the caret will blink and the next character interaction will occur
328 * @param keycode Direction in which navigation occurs (WKC_CTRL |) WKC_LEFT, (WKC_CTRL |) WKC_RIGHT, WKC_END, WKC_HOME
329 * @return Return true on successful change of Textbuf, or false otherwise
331 bool Textbuf::MovePos(uint16_t keycode)
333 switch (keycode) {
334 case WKC_LEFT:
335 case WKC_CTRL | WKC_LEFT: {
336 if (this->caretpos == 0) break;
338 size_t pos = this->char_iter->Prev(keycode & WKC_CTRL ? StringIterator::ITER_WORD : StringIterator::ITER_CHARACTER);
339 if (pos == StringIterator::END) return true;
341 this->caretpos = (uint16_t)pos;
342 this->UpdateCaretPosition();
343 return true;
346 case WKC_RIGHT:
347 case WKC_CTRL | WKC_RIGHT: {
348 if (this->caretpos >= this->bytes - 1) break;
350 size_t pos = this->char_iter->Next(keycode & WKC_CTRL ? StringIterator::ITER_WORD : StringIterator::ITER_CHARACTER);
351 if (pos == StringIterator::END) return true;
353 this->caretpos = (uint16_t)pos;
354 this->UpdateCaretPosition();
355 return true;
358 case WKC_HOME:
359 this->caretpos = 0;
360 this->char_iter->SetCurPosition(this->caretpos);
361 this->UpdateCaretPosition();
362 return true;
364 case WKC_END:
365 this->caretpos = this->bytes - 1;
366 this->char_iter->SetCurPosition(this->caretpos);
367 this->UpdateCaretPosition();
368 return true;
370 default:
371 break;
374 return false;
378 * Initialize the textbuffer by supplying it the buffer to write into
379 * and the maximum length of this buffer
380 * @param max_bytes maximum size in bytes, including terminating '\0'
381 * @param max_chars maximum size in chars, including terminating '\0'
383 Textbuf::Textbuf(uint16_t max_bytes, uint16_t max_chars)
384 : buf(MallocT<char>(max_bytes)), char_iter(StringIterator::Create())
386 assert(max_bytes != 0);
387 assert(max_chars != 0);
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();
396 Textbuf::~Textbuf()
398 free(this->buf);
402 * Render a string into the textbuffer.
403 * @param string String
405 void Textbuf::Assign(StringID string)
407 this->Assign(GetString(string));
411 * Copy a string into the textbuffer.
412 * @param text Source.
414 void Textbuf::Assign(const std::string_view text)
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);
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';
426 this->UpdateSize();
431 * Update Textbuf type with its actual physical character and screenlength
432 * Get the count of characters in the string as well as the width in pixels.
433 * Useful when copying in a larger amount of text at once
435 void Textbuf::UpdateSize()
437 const char *buf = this->buf;
439 this->chars = this->bytes = 1; // terminating zero
441 char32_t c;
442 while ((c = Utf8Consume(&buf)) != '\0') {
443 this->bytes += Utf8CharLen(c);
444 this->chars++;
446 assert(this->bytes <= this->max_bytes);
447 assert(this->chars <= this->max_chars);
449 this->caretpos = this->bytes - 1;
450 this->UpdateStringIter();
451 this->UpdateWidth();
452 this->UpdateMarkedText();
454 this->UpdateCaretPosition();
458 * Handle the flashing of the caret.
459 * @return True if the caret state changes.
461 bool Textbuf::HandleCaret()
463 /* caret changed? */
464 bool b = !!(_caret_timer & 0x20);
466 if (b != this->caret) {
467 this->caret = b;
468 return true;
470 return false;
473 HandleKeyPressResult Textbuf::HandleKeyPress(char32_t key, uint16_t keycode)
475 bool edited = false;
477 switch (keycode) {
478 case WKC_ESC: return HKPR_CANCEL;
480 case WKC_RETURN: case WKC_NUM_ENTER: return HKPR_CONFIRM;
482 case (WKC_CTRL | 'V'):
483 case (WKC_SHIFT | WKC_INSERT):
484 edited = this->InsertClipboard();
485 break;
487 case (WKC_CTRL | 'U'):
488 this->DeleteAll();
489 edited = true;
490 break;
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;
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;
502 default:
503 if (IsValidChar(key, this->afilter)) {
504 edited = this->InsertChar(key);
505 } else {
506 return HKPR_NOT_HANDLED;
508 break;
511 return edited ? HKPR_EDITING : HKPR_CURSOR;