Fix ICU iterators on leading/trailing whitespace
[openttd/fttd.git] / src / textbuf.cpp
blob766396fc663e39b4e8100de38f46e1de2bf7fab6
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 /**
24 * Try to retrieve the current clipboard contents.
26 * @note OS-specific function.
27 * @return True if some text could be retrieved.
29 bool GetClipboardContents(char *buffer, size_t buff_len);
31 int _caret_timer;
34 /**
35 * Checks if it is possible to delete a character.
36 * @param backspace if set, delete the character before the caret,
37 * otherwise, delete the character after it.
38 * @return true if a character can be deleted in the given direction.
40 bool Textbuf::CanDelChar(bool backspace)
42 return backspace ? this->caretpos != 0 : this->caretpos < this->bytes - 1;
45 /**
46 * Delete a character from a textbuffer, either with 'Delete' or 'Backspace'
47 * The character is delete from the position the caret is at
48 * @param keycode Type of deletion, either WKC_BACKSPACE or WKC_DELETE
49 * @return Return true on successful change of Textbuf, or false otherwise
51 bool Textbuf::DeleteChar(uint16 keycode)
53 bool word = (keycode & WKC_CTRL) != 0;
55 keycode &= ~WKC_SPECIAL_KEYS;
56 if (keycode != WKC_BACKSPACE && keycode != WKC_DELETE) return false;
58 bool backspace = keycode == WKC_BACKSPACE;
60 if (!CanDelChar(backspace)) return false;
62 char *s = this->buf + this->caretpos;
63 uint16 len = 0;
65 if (word) {
66 /* Delete a complete word. */
67 if (backspace) {
68 /* Delete whitespace and word in front of the caret. */
69 len = this->caretpos - (uint16)this->char_iter->Prev(StringIterator::ITER_WORD);
70 s -= len;
71 } else {
72 /* Delete word and following whitespace following the caret. */
73 len = (uint16)this->char_iter->Next(StringIterator::ITER_WORD) - this->caretpos;
75 /* Update character count. */
76 for (const char *ss = s; ss < s + len; Utf8Consume(&ss)) {
77 this->chars--;
79 } else {
80 /* Delete a single character. */
81 if (backspace) {
82 /* Delete the last code point in front of the caret. */
83 s = Utf8PrevChar(s);
84 WChar c;
85 len = (uint16)Utf8Decode(&c, s);
86 this->chars--;
87 } else {
88 /* Delete the complete character following the caret. */
89 len = (uint16)this->char_iter->Next(StringIterator::ITER_CHARACTER) - this->caretpos;
90 /* Update character count. */
91 for (const char *ss = s; ss < s + len; Utf8Consume(&ss)) {
92 this->chars--;
97 /* Move the remaining characters over the marker */
98 memmove(s, s + len, this->bytes - (s - this->buf) - len);
99 this->bytes -= len;
101 if (backspace) this->caretpos -= len;
103 this->UpdateStringIter();
104 this->UpdateWidth();
105 this->UpdateCaretPosition();
106 this->UpdateMarkedText();
108 return true;
112 * Delete every character in the textbuffer
114 void Textbuf::DeleteAll()
116 memset(this->buf, 0, this->max_bytes);
117 this->bytes = this->chars = 1;
118 this->pixels = this->caretpos = this->caretxoffs = 0;
119 this->markpos = this->markend = this->markxoffs = this->marklength = 0;
120 this->UpdateStringIter();
124 * Insert a character to a textbuffer. If maxwidth of the Textbuf is zero,
125 * we don't care about the visual-length but only about the physical
126 * length of the string
127 * @param key Character to be inserted
128 * @return Return true on successful change of Textbuf, or false otherwise
130 bool Textbuf::InsertChar(WChar key)
132 uint16 len = (uint16)Utf8CharLen(key);
133 if (this->bytes + len <= this->max_bytes && this->chars + 1 <= this->max_chars) {
134 memmove(this->buf + this->caretpos + len, this->buf + this->caretpos, this->bytes - this->caretpos);
135 Utf8Encode(this->buf + this->caretpos, key);
136 this->chars++;
137 this->bytes += len;
138 this->caretpos += len;
140 this->UpdateStringIter();
141 this->UpdateWidth();
142 this->UpdateCaretPosition();
143 this->UpdateMarkedText();
144 return true;
146 return false;
150 * Insert a string into the text buffer. If maxwidth of the Textbuf is zero,
151 * we don't care about the visual-length but only about the physical
152 * length of the string.
153 * @param str String to insert.
154 * @param marked Replace the currently marked text with the new text.
155 * @param caret Move the caret to this point in the insertion string.
156 * @param insert_location Position at which to insert the string.
157 * @param replacement_end Replace all characters from #insert_location up to this location with the new string.
158 * @return True on successful change of Textbuf, or false otherwise.
160 bool Textbuf::InsertString(const char *str, bool marked, const char *caret, const char *insert_location, const char *replacement_end)
162 uint16 insertpos = (marked && this->marklength != 0) ? this->markpos : this->caretpos;
163 if (insert_location != NULL) {
164 insertpos = insert_location - this->buf;
165 if (insertpos > this->bytes) return false;
167 if (replacement_end != NULL) {
168 this->DeleteText(insertpos, replacement_end - this->buf, str == NULL);
170 } else {
171 if (marked) this->DiscardMarkedText(str == NULL);
174 if (str == NULL) return false;
176 uint16 bytes = 0, chars = 0;
177 WChar c;
178 for (const char *ptr = str; (c = Utf8Consume(&ptr)) != '\0';) {
179 if (!IsValidChar(c, this->afilter)) break;
181 byte len = Utf8CharLen(c);
182 if (this->bytes + bytes + len > this->max_bytes) break;
183 if (this->chars + chars + 1 > this->max_chars) break;
185 bytes += len;
186 chars++;
188 /* Move caret if needed. */
189 if (ptr == caret) this->caretpos = insertpos + bytes;
192 if (bytes == 0) return false;
194 if (marked) {
195 this->markpos = insertpos;
196 this->markend = insertpos + bytes;
199 memmove(this->buf + insertpos + bytes, this->buf + insertpos, this->bytes - insertpos);
200 memcpy(this->buf + insertpos, str, bytes);
202 this->bytes += bytes;
203 this->chars += chars;
204 if (!marked && caret == NULL) this->caretpos += bytes;
205 assert(this->bytes <= this->max_bytes);
206 assert(this->chars <= this->max_chars);
207 this->buf[this->bytes - 1] = '\0'; // terminating zero
209 this->UpdateStringIter();
210 this->UpdateWidth();
211 this->UpdateCaretPosition();
212 this->UpdateMarkedText();
214 return true;
218 * Insert a chunk of text from the clipboard onto the textbuffer. Get TEXT clipboard
219 * and append this up to the maximum length (either absolute or screenlength). If maxlength
220 * is zero, we don't care about the screenlength but only about the physical length of the string
221 * @return true on successful change of Textbuf, or false otherwise
223 bool Textbuf::InsertClipboard()
225 char utf8_buf[512];
227 if (!GetClipboardContents(utf8_buf, lengthof(utf8_buf))) return false;
229 return this->InsertString(utf8_buf, false);
233 * Delete a part of the text.
234 * @param from Start of the text to delete.
235 * @param to End of the text to delete.
236 * @param update Set to true if the internal state should be updated.
238 void Textbuf::DeleteText(uint16 from, uint16 to, bool update)
240 uint c = 0;
241 const char *s = this->buf + from;
242 while (s < this->buf + to) {
243 Utf8Consume(&s);
244 c++;
247 /* Strip marked characters from buffer. */
248 memmove(this->buf + from, this->buf + to, this->bytes - to);
249 this->bytes -= to - from;
250 this->chars -= c;
252 /* Fixup caret if needed. */
253 if (this->caretpos > from) {
254 if (this->caretpos <= to) {
255 this->caretpos = from;
256 } else {
257 this->caretpos -= to - from;
261 if (update) {
262 this->UpdateStringIter();
263 this->UpdateCaretPosition();
264 this->UpdateMarkedText();
269 * Discard any marked text.
270 * @param update Set to true if the internal state should be updated.
272 void Textbuf::DiscardMarkedText(bool update)
274 if (this->markend == 0) return;
276 this->DeleteText(this->markpos, this->markend, update);
277 this->markpos = this->markend = this->markxoffs = this->marklength = 0;
280 /** Update the character iter after the text has changed. */
281 void Textbuf::UpdateStringIter()
283 this->char_iter->SetString(this->buf);
284 size_t pos = this->char_iter->SetCurPosition(this->caretpos);
285 this->caretpos = pos == StringIterator::END ? 0 : (uint16)pos;
288 /** Update pixel width of the text. */
289 void Textbuf::UpdateWidth()
291 this->pixels = GetStringBoundingBox(this->buf, FS_NORMAL).width;
294 /** Update pixel position of the caret. */
295 void Textbuf::UpdateCaretPosition()
297 this->caretxoffs = this->chars > 1 ? GetCharPosInString(this->buf, this->buf + this->caretpos, FS_NORMAL).x : 0;
300 /** Update pixel positions of the marked text area. */
301 void Textbuf::UpdateMarkedText()
303 if (this->markend != 0) {
304 this->markxoffs = GetCharPosInString(this->buf, this->buf + this->markpos, FS_NORMAL).x;
305 this->marklength = GetCharPosInString(this->buf, this->buf + this->markend, FS_NORMAL).x - this->markxoffs;
306 } else {
307 this->markxoffs = this->marklength = 0;
312 * Handle text navigation with arrow keys left/right.
313 * This defines where the caret will blink and the next character interaction will occur
314 * @param keycode Direction in which navigation occurs (WKC_CTRL |) WKC_LEFT, (WKC_CTRL |) WKC_RIGHT, WKC_END, WKC_HOME
315 * @return Return true on successful change of Textbuf, or false otherwise
317 bool Textbuf::MovePos(uint16 keycode)
319 switch (keycode) {
320 case WKC_LEFT:
321 case WKC_CTRL | WKC_LEFT: {
322 if (this->caretpos == 0) break;
324 size_t pos = this->char_iter->Prev(keycode & WKC_CTRL ? StringIterator::ITER_WORD : StringIterator::ITER_CHARACTER);
325 if (pos == StringIterator::END) return true;
327 this->caretpos = (uint16)pos;
328 this->UpdateCaretPosition();
329 return true;
332 case WKC_RIGHT:
333 case WKC_CTRL | WKC_RIGHT: {
334 if (this->caretpos >= this->bytes - 1) break;
336 size_t pos = this->char_iter->Next(keycode & WKC_CTRL ? StringIterator::ITER_WORD : StringIterator::ITER_CHARACTER);
337 if (pos == StringIterator::END) return true;
339 this->caretpos = (uint16)pos;
340 this->UpdateCaretPosition();
341 return true;
344 case WKC_HOME:
345 this->caretpos = 0;
346 this->char_iter->SetCurPosition(this->caretpos);
347 this->UpdateCaretPosition();
348 return true;
350 case WKC_END:
351 this->caretpos = this->bytes - 1;
352 this->char_iter->SetCurPosition(this->caretpos);
353 this->UpdateCaretPosition();
354 return true;
356 default:
357 break;
360 return false;
364 * Initialize the textbuffer by supplying it the buffer to write into
365 * and the maximum length of this buffer
366 * @param buf the buffer that will be holding the data for input
367 * @param max_bytes maximum size in bytes, including terminating '\0'
368 * @param max_chars maximum size in chars, including terminating '\0'
370 Textbuf::Textbuf(uint16 max_bytes, uint16 max_chars)
371 : buf(MallocT<char>(max_bytes))
373 assert(max_bytes != 0);
374 assert(max_chars != 0);
376 this->char_iter = StringIterator::Create();
378 this->afilter = CS_ALPHANUMERAL;
379 this->max_bytes = max_bytes;
380 this->max_chars = max_chars == UINT16_MAX ? max_bytes : max_chars;
381 this->caret = true;
382 this->DeleteAll();
385 Textbuf::~Textbuf()
387 delete this->char_iter;
388 free(this->buf);
392 * Render a string into the textbuffer.
393 * @param string String
395 void Textbuf::Assign(StringID string)
397 GetString(this->buf, string, &this->buf[this->max_bytes - 1]);
398 this->UpdateSize();
402 * Copy a string into the textbuffer.
403 * @param text Source.
405 void Textbuf::Assign(const char *text)
407 ttd_strlcpy(this->buf, text, this->max_bytes);
408 this->UpdateSize();
412 * Print a formatted string into the textbuffer.
414 void Textbuf::Print(const char *format, ...)
416 va_list va;
417 va_start(va, format);
418 vsnprintf(this->buf, this->max_bytes, format, va);
419 va_end(va);
420 this->UpdateSize();
425 * Update Textbuf type with its actual physical character and screenlength
426 * Get the count of characters in the string as well as the width in pixels.
427 * Useful when copying in a larger amount of text at once
429 void Textbuf::UpdateSize()
431 const char *buf = this->buf;
433 this->chars = this->bytes = 1; // terminating zero
435 WChar c;
436 while ((c = Utf8Consume(&buf)) != '\0') {
437 this->bytes += Utf8CharLen(c);
438 this->chars++;
440 assert(this->bytes <= this->max_bytes);
441 assert(this->chars <= this->max_chars);
443 this->caretpos = this->bytes - 1;
444 this->UpdateStringIter();
445 this->UpdateWidth();
446 this->UpdateMarkedText();
448 this->UpdateCaretPosition();
452 * Handle the flashing of the caret.
453 * @return True if the caret state changes.
455 bool Textbuf::HandleCaret()
457 /* caret changed? */
458 bool b = !!(_caret_timer & 0x20);
460 if (b != this->caret) {
461 this->caret = b;
462 return true;
464 return false;
467 HandleKeyPressResult Textbuf::HandleKeyPress(WChar key, uint16 keycode)
469 bool edited = false;
471 switch (keycode) {
472 case WKC_ESC: return HKPR_CANCEL;
474 case WKC_RETURN: case WKC_NUM_ENTER: return HKPR_CONFIRM;
476 #ifdef WITH_COCOA
477 case (WKC_META | 'V'):
478 #endif
479 case (WKC_CTRL | 'V'):
480 edited = this->InsertClipboard();
481 break;
483 #ifdef WITH_COCOA
484 case (WKC_META | 'U'):
485 #endif
486 case (WKC_CTRL | 'U'):
487 this->DeleteAll();
488 edited = true;
489 break;
491 case WKC_BACKSPACE: case WKC_DELETE:
492 case WKC_CTRL | WKC_BACKSPACE: case WKC_CTRL | WKC_DELETE:
493 edited = this->DeleteChar(keycode);
494 break;
496 case WKC_LEFT: case WKC_RIGHT: case WKC_END: case WKC_HOME:
497 case WKC_CTRL | WKC_LEFT: case WKC_CTRL | WKC_RIGHT:
498 this->MovePos(keycode);
499 break;
501 default:
502 if (IsValidChar(key, this->afilter)) {
503 edited = this->InsertChar(key);
504 } else {
505 return HKPR_NOT_HANDLED;
507 break;
510 return edited ? HKPR_EDITING : HKPR_CURSOR;