Add: Draw network password indicator lock in company drop down list. (#7079)
[openttd-github.git] / src / textbuf.cpp
blob61e449d3aedc68365cda8e723f1dc09dcc6f7436
1 /* $Id$ */
3 /*
4 * This file is part of OpenTTD.
5 * 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.
6 * 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.
7 * 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/>.
8 */
10 /** @file textbuf.cpp Textbuffer handling. */
12 #include "stdafx.h"
13 #include <stdarg.h>
15 #include "textbuf_type.h"
16 #include "string_func.h"
17 #include "strings_func.h"
18 #include "gfx_type.h"
19 #include "gfx_func.h"
20 #include "window_func.h"
21 #include "core/alloc_func.hpp"
23 #include "safeguards.h"
25 /**
26 * Try to retrieve the current clipboard contents.
28 * @note OS-specific function.
29 * @param buffer Clipboard content.
30 * @param last The pointer to the last element of the destination buffer
31 * @return True if some text could be retrieved.
33 bool GetClipboardContents(char *buffer, const char *last);
35 int _caret_timer;
38 /**
39 * Checks if it is possible to delete a character.
40 * @param backspace if set, delete the character before the caret,
41 * otherwise, delete the character after it.
42 * @return true if a character can be deleted in the given direction.
44 bool Textbuf::CanDelChar(bool backspace)
46 return backspace ? this->caretpos != 0 : this->caretpos < this->bytes - 1;
49 /**
50 * Delete a character from a textbuffer, either with 'Delete' or 'Backspace'
51 * The character is delete from the position the caret is at
52 * @param keycode Type of deletion, either WKC_BACKSPACE or WKC_DELETE
53 * @return Return true on successful change of Textbuf, or false otherwise
55 bool Textbuf::DeleteChar(uint16 keycode)
57 bool word = (keycode & WKC_CTRL) != 0;
59 keycode &= ~WKC_SPECIAL_KEYS;
60 if (keycode != WKC_BACKSPACE && keycode != WKC_DELETE) return false;
62 bool backspace = keycode == WKC_BACKSPACE;
64 if (!CanDelChar(backspace)) return false;
66 char *s = this->buf + this->caretpos;
67 uint16 len = 0;
69 if (word) {
70 /* Delete a complete word. */
71 if (backspace) {
72 /* Delete whitespace and word in front of the caret. */
73 len = this->caretpos - (uint16)this->char_iter->Prev(StringIterator::ITER_WORD);
74 s -= len;
75 } else {
76 /* Delete word and following whitespace following the caret. */
77 len = (uint16)this->char_iter->Next(StringIterator::ITER_WORD) - this->caretpos;
79 /* Update character count. */
80 for (const char *ss = s; ss < s + len; Utf8Consume(&ss)) {
81 this->chars--;
83 } else {
84 /* Delete a single character. */
85 if (backspace) {
86 /* Delete the last code point in front of the caret. */
87 s = Utf8PrevChar(s);
88 WChar c;
89 len = (uint16)Utf8Decode(&c, s);
90 this->chars--;
91 } else {
92 /* Delete the complete character following the caret. */
93 len = (uint16)this->char_iter->Next(StringIterator::ITER_CHARACTER) - this->caretpos;
94 /* Update character count. */
95 for (const char *ss = s; ss < s + len; Utf8Consume(&ss)) {
96 this->chars--;
101 /* Move the remaining characters over the marker */
102 memmove(s, s + len, this->bytes - (s - this->buf) - len);
103 this->bytes -= len;
105 if (backspace) this->caretpos -= len;
107 this->UpdateStringIter();
108 this->UpdateWidth();
109 this->UpdateCaretPosition();
110 this->UpdateMarkedText();
112 return true;
116 * Delete every character in the textbuffer
118 void Textbuf::DeleteAll()
120 memset(this->buf, 0, this->max_bytes);
121 this->bytes = this->chars = 1;
122 this->pixels = this->caretpos = this->caretxoffs = 0;
123 this->markpos = this->markend = this->markxoffs = this->marklength = 0;
124 this->UpdateStringIter();
128 * Insert a character to a textbuffer. If maxwidth of the Textbuf is zero,
129 * we don't care about the visual-length but only about the physical
130 * length of the string
131 * @param key Character to be inserted
132 * @return Return true on successful change of Textbuf, or false otherwise
134 bool Textbuf::InsertChar(WChar key)
136 uint16 len = (uint16)Utf8CharLen(key);
137 if (this->bytes + len <= this->max_bytes && this->chars + 1 <= this->max_chars) {
138 memmove(this->buf + this->caretpos + len, this->buf + this->caretpos, this->bytes - this->caretpos);
139 Utf8Encode(this->buf + this->caretpos, key);
140 this->chars++;
141 this->bytes += len;
142 this->caretpos += len;
144 this->UpdateStringIter();
145 this->UpdateWidth();
146 this->UpdateCaretPosition();
147 this->UpdateMarkedText();
148 return true;
150 return false;
154 * Insert a string into the text buffer. If maxwidth of the Textbuf is zero,
155 * we don't care about the visual-length but only about the physical
156 * length of the string.
157 * @param str String to insert.
158 * @param marked Replace the currently marked text with the new text.
159 * @param caret Move the caret to this point in the insertion string.
160 * @param insert_location Position at which to insert the string.
161 * @param replacement_end Replace all characters from #insert_location up to this location with the new string.
162 * @return True on successful change of Textbuf, or false otherwise.
164 bool Textbuf::InsertString(const char *str, bool marked, const char *caret, const char *insert_location, const char *replacement_end)
166 uint16 insertpos = (marked && this->marklength != 0) ? this->markpos : this->caretpos;
167 if (insert_location != NULL) {
168 insertpos = insert_location - this->buf;
169 if (insertpos > this->bytes) return false;
171 if (replacement_end != NULL) {
172 this->DeleteText(insertpos, replacement_end - this->buf, str == NULL);
174 } else {
175 if (marked) this->DiscardMarkedText(str == NULL);
178 if (str == NULL) return false;
180 uint16 bytes = 0, chars = 0;
181 WChar c;
182 for (const char *ptr = str; (c = Utf8Consume(&ptr)) != '\0';) {
183 if (!IsValidChar(c, this->afilter)) break;
185 byte len = Utf8CharLen(c);
186 if (this->bytes + bytes + len > this->max_bytes) break;
187 if (this->chars + chars + 1 > this->max_chars) break;
189 bytes += len;
190 chars++;
192 /* Move caret if needed. */
193 if (ptr == caret) this->caretpos = insertpos + bytes;
196 if (bytes == 0) return false;
198 if (marked) {
199 this->markpos = insertpos;
200 this->markend = insertpos + bytes;
203 memmove(this->buf + insertpos + bytes, this->buf + insertpos, this->bytes - insertpos);
204 memcpy(this->buf + insertpos, str, bytes);
206 this->bytes += bytes;
207 this->chars += chars;
208 if (!marked && caret == NULL) this->caretpos += bytes;
209 assert(this->bytes <= this->max_bytes);
210 assert(this->chars <= this->max_chars);
211 this->buf[this->bytes - 1] = '\0'; // terminating zero
213 this->UpdateStringIter();
214 this->UpdateWidth();
215 this->UpdateCaretPosition();
216 this->UpdateMarkedText();
218 return true;
222 * Insert a chunk of text from the clipboard onto the textbuffer. Get TEXT clipboard
223 * and append this up to the maximum length (either absolute or screenlength). If maxlength
224 * is zero, we don't care about the screenlength but only about the physical length of the string
225 * @return true on successful change of Textbuf, or false otherwise
227 bool Textbuf::InsertClipboard()
229 char utf8_buf[512];
231 if (!GetClipboardContents(utf8_buf, lastof(utf8_buf))) return false;
233 return this->InsertString(utf8_buf, false);
237 * Delete a part of the text.
238 * @param from Start of the text to delete.
239 * @param to End of the text to delete.
240 * @param update Set to true if the internal state should be updated.
242 void Textbuf::DeleteText(uint16 from, uint16 to, bool update)
244 uint c = 0;
245 const char *s = this->buf + from;
246 while (s < this->buf + to) {
247 Utf8Consume(&s);
248 c++;
251 /* Strip marked characters from buffer. */
252 memmove(this->buf + from, this->buf + to, this->bytes - to);
253 this->bytes -= to - from;
254 this->chars -= c;
256 /* Fixup caret if needed. */
257 if (this->caretpos > from) {
258 if (this->caretpos <= to) {
259 this->caretpos = from;
260 } else {
261 this->caretpos -= to - from;
265 if (update) {
266 this->UpdateStringIter();
267 this->UpdateCaretPosition();
268 this->UpdateMarkedText();
273 * Discard any marked text.
274 * @param update Set to true if the internal state should be updated.
276 void Textbuf::DiscardMarkedText(bool update)
278 if (this->markend == 0) return;
280 this->DeleteText(this->markpos, this->markend, update);
281 this->markpos = this->markend = this->markxoffs = this->marklength = 0;
284 /** Update the character iter after the text has changed. */
285 void Textbuf::UpdateStringIter()
287 this->char_iter->SetString(this->buf);
288 size_t pos = this->char_iter->SetCurPosition(this->caretpos);
289 this->caretpos = pos == StringIterator::END ? 0 : (uint16)pos;
292 /** Update pixel width of the text. */
293 void Textbuf::UpdateWidth()
295 this->pixels = GetStringBoundingBox(this->buf, FS_NORMAL).width;
298 /** Update pixel position of the caret. */
299 void Textbuf::UpdateCaretPosition()
301 this->caretxoffs = this->chars > 1 ? GetCharPosInString(this->buf, this->buf + this->caretpos, FS_NORMAL).x : 0;
304 /** Update pixel positions of the marked text area. */
305 void Textbuf::UpdateMarkedText()
307 if (this->markend != 0) {
308 this->markxoffs = GetCharPosInString(this->buf, this->buf + this->markpos, FS_NORMAL).x;
309 this->marklength = GetCharPosInString(this->buf, this->buf + this->markend, FS_NORMAL).x - this->markxoffs;
310 } else {
311 this->markxoffs = this->marklength = 0;
316 * Handle text navigation with arrow keys left/right.
317 * This defines where the caret will blink and the next character interaction will occur
318 * @param keycode Direction in which navigation occurs (WKC_CTRL |) WKC_LEFT, (WKC_CTRL |) WKC_RIGHT, WKC_END, WKC_HOME
319 * @return Return true on successful change of Textbuf, or false otherwise
321 bool Textbuf::MovePos(uint16 keycode)
323 switch (keycode) {
324 case WKC_LEFT:
325 case WKC_CTRL | WKC_LEFT: {
326 if (this->caretpos == 0) break;
328 size_t pos = this->char_iter->Prev(keycode & WKC_CTRL ? StringIterator::ITER_WORD : StringIterator::ITER_CHARACTER);
329 if (pos == StringIterator::END) return true;
331 this->caretpos = (uint16)pos;
332 this->UpdateCaretPosition();
333 return true;
336 case WKC_RIGHT:
337 case WKC_CTRL | WKC_RIGHT: {
338 if (this->caretpos >= this->bytes - 1) break;
340 size_t pos = this->char_iter->Next(keycode & WKC_CTRL ? StringIterator::ITER_WORD : StringIterator::ITER_CHARACTER);
341 if (pos == StringIterator::END) return true;
343 this->caretpos = (uint16)pos;
344 this->UpdateCaretPosition();
345 return true;
348 case WKC_HOME:
349 this->caretpos = 0;
350 this->char_iter->SetCurPosition(this->caretpos);
351 this->UpdateCaretPosition();
352 return true;
354 case WKC_END:
355 this->caretpos = this->bytes - 1;
356 this->char_iter->SetCurPosition(this->caretpos);
357 this->UpdateCaretPosition();
358 return true;
360 default:
361 break;
364 return false;
368 * Initialize the textbuffer by supplying it the buffer to write into
369 * and the maximum length of this buffer
370 * @param max_bytes maximum size in bytes, including terminating '\0'
371 * @param max_chars maximum size in chars, including terminating '\0'
373 Textbuf::Textbuf(uint16 max_bytes, uint16 max_chars)
374 : buf(MallocT<char>(max_bytes))
376 assert(max_bytes != 0);
377 assert(max_chars != 0);
379 this->char_iter = StringIterator::Create();
381 this->afilter = CS_ALPHANUMERAL;
382 this->max_bytes = max_bytes;
383 this->max_chars = max_chars == UINT16_MAX ? max_bytes : max_chars;
384 this->caret = true;
385 this->DeleteAll();
388 Textbuf::~Textbuf()
390 delete this->char_iter;
391 free(this->buf);
395 * Render a string into the textbuffer.
396 * @param string String
398 void Textbuf::Assign(StringID string)
400 GetString(this->buf, string, &this->buf[this->max_bytes - 1]);
401 this->UpdateSize();
405 * Copy a string into the textbuffer.
406 * @param text Source.
408 void Textbuf::Assign(const char *text)
410 strecpy(this->buf, text, &this->buf[this->max_bytes - 1]);
411 this->UpdateSize();
415 * Print a formatted string into the textbuffer.
417 void Textbuf::Print(const char *format, ...)
419 va_list va;
420 va_start(va, format);
421 vseprintf(this->buf, &this->buf[this->max_bytes - 1], format, va);
422 va_end(va);
423 this->UpdateSize();
428 * Update Textbuf type with its actual physical character and screenlength
429 * Get the count of characters in the string as well as the width in pixels.
430 * Useful when copying in a larger amount of text at once
432 void Textbuf::UpdateSize()
434 const char *buf = this->buf;
436 this->chars = this->bytes = 1; // terminating zero
438 WChar c;
439 while ((c = Utf8Consume(&buf)) != '\0') {
440 this->bytes += Utf8CharLen(c);
441 this->chars++;
443 assert(this->bytes <= this->max_bytes);
444 assert(this->chars <= this->max_chars);
446 this->caretpos = this->bytes - 1;
447 this->UpdateStringIter();
448 this->UpdateWidth();
449 this->UpdateMarkedText();
451 this->UpdateCaretPosition();
455 * Handle the flashing of the caret.
456 * @return True if the caret state changes.
458 bool Textbuf::HandleCaret()
460 /* caret changed? */
461 bool b = !!(_caret_timer & 0x20);
463 if (b != this->caret) {
464 this->caret = b;
465 return true;
467 return false;
470 HandleKeyPressResult Textbuf::HandleKeyPress(WChar key, uint16 keycode)
472 bool edited = false;
474 switch (keycode) {
475 case WKC_ESC: return HKPR_CANCEL;
477 case WKC_RETURN: case WKC_NUM_ENTER: return HKPR_CONFIRM;
479 case (WKC_CTRL | 'V'):
480 edited = this->InsertClipboard();
481 break;
483 case (WKC_CTRL | 'U'):
484 this->DeleteAll();
485 edited = true;
486 break;
488 case WKC_BACKSPACE: case WKC_DELETE:
489 case WKC_CTRL | WKC_BACKSPACE: case WKC_CTRL | WKC_DELETE:
490 edited = this->DeleteChar(keycode);
491 break;
493 case WKC_LEFT: case WKC_RIGHT: case WKC_END: case WKC_HOME:
494 case WKC_CTRL | WKC_LEFT: case WKC_CTRL | WKC_RIGHT:
495 this->MovePos(keycode);
496 break;
498 default:
499 if (IsValidChar(key, this->afilter)) {
500 edited = this->InsertChar(key);
501 } else {
502 return HKPR_NOT_HANDLED;
504 break;
507 return edited ? HKPR_EDITING : HKPR_CURSOR;