1/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */
2/* If you are missing that file, acquire a complete release at teeworlds.com. */
3#include "lineinput.h"
4
5#include "ui.h"
6
7#include <base/dbg.h>
8#include <base/mem.h>
9#include <base/str.h>
10
11#include <engine/graphics.h>
12#include <engine/keys.h>
13#include <engine/shared/config.h>
14
15IInput *CLineInput::ms_pInput = nullptr;
16ITextRender *CLineInput::ms_pTextRender = nullptr;
17IGraphics *CLineInput::ms_pGraphics = nullptr;
18IClient *CLineInput::ms_pClient = nullptr;
19
20CLineInput *CLineInput::ms_pActiveInput = nullptr;
21EInputPriority CLineInput::ms_ActiveInputPriority = EInputPriority::NONE;
22
23vec2 CLineInput::ms_CompositionWindowPosition = vec2(0.0f, 0.0f);
24float CLineInput::ms_CompositionLineHeight = 0.0f;
25
26void CLineInput::SetBuffer(char *pStr, size_t MaxSize, size_t MaxChars)
27{
28 if(m_pStr && m_pStr == pStr)
29 return;
30 const char *pLastStr = m_pStr;
31 m_pStr = pStr;
32 m_MaxSize = MaxSize;
33 m_MaxChars = MaxChars;
34 m_WasChanged = m_pStr && pLastStr && m_WasChanged;
35 m_WasCursorChanged = m_pStr && pLastStr && m_WasCursorChanged;
36 if(!pLastStr)
37 {
38 m_CursorPos = m_SelectionStart = m_SelectionEnd = m_LastCompositionCursorPos = 0;
39 m_ScrollOffset = m_ScrollOffsetChange = 0.0f;
40 m_CaretPosition = vec2(0.0f, 0.0f);
41 m_MouseSelection.m_Selecting = false;
42 m_Hidden = false;
43 m_pEmptyText = nullptr;
44 m_WasRendered = false;
45 }
46 if(m_pStr && m_pStr != pLastStr)
47 UpdateStrData();
48}
49
50void CLineInput::Clear()
51{
52 mem_zero(block: m_pStr, size: m_MaxSize);
53 UpdateStrData();
54}
55
56void CLineInput::Set(const char *pString)
57{
58 str_copy(dst: m_pStr, src: pString, dst_size: m_MaxSize);
59 UpdateStrData();
60 SetCursorOffset(m_Len);
61}
62
63void CLineInput::SetRange(const char *pString, size_t Begin, size_t End)
64{
65 if(Begin > End)
66 std::swap(a&: Begin, b&: End);
67 Begin = std::clamp<size_t>(val: Begin, lo: 0, hi: m_Len);
68 End = std::clamp<size_t>(val: End, lo: 0, hi: m_Len);
69
70 size_t RemovedCharSize, RemovedCharCount;
71 str_utf8_stats(str: m_pStr + Begin, max_size: End - Begin + 1, max_count: m_MaxChars, size: &RemovedCharSize, count: &RemovedCharCount);
72
73 size_t AddedCharSize, AddedCharCount;
74 str_utf8_stats(str: pString, max_size: m_MaxSize - m_Len + RemovedCharSize, max_count: m_MaxChars - m_NumChars + RemovedCharCount, size: &AddedCharSize, count: &AddedCharCount);
75
76 if(RemovedCharSize || AddedCharSize)
77 {
78 if(AddedCharSize < RemovedCharSize)
79 {
80 if(AddedCharSize)
81 mem_copy(dest: m_pStr + Begin, source: pString, size: AddedCharSize);
82 mem_move(dest: m_pStr + Begin + AddedCharSize, source: m_pStr + Begin + RemovedCharSize, size: m_Len - Begin - RemovedCharSize);
83 }
84 else if(AddedCharSize > RemovedCharSize)
85 mem_move(dest: m_pStr + End + AddedCharSize - RemovedCharSize, source: m_pStr + End, size: m_Len - End);
86
87 if(AddedCharSize >= RemovedCharSize)
88 mem_copy(dest: m_pStr + Begin, source: pString, size: AddedCharSize);
89
90 m_CursorPos = End - RemovedCharSize + AddedCharSize;
91 m_Len += AddedCharSize - RemovedCharSize;
92 m_NumChars += AddedCharCount - RemovedCharCount;
93 m_WasChanged = true;
94 m_WasCursorChanged = true;
95 m_pStr[m_Len] = '\0';
96 m_SelectionStart = m_SelectionEnd = m_CursorPos;
97 }
98}
99
100void CLineInput::Insert(const char *pString, size_t Begin)
101{
102 SetRange(pString, Begin, End: Begin);
103}
104
105void CLineInput::Append(const char *pString)
106{
107 Insert(pString, Begin: m_Len);
108}
109
110void CLineInput::UpdateStrData()
111{
112 str_utf8_stats(str: m_pStr, max_size: m_MaxSize, max_count: m_MaxChars, size: &m_Len, count: &m_NumChars);
113 if(!in_range<size_t>(a: m_CursorPos, lower: 0, upper: m_Len))
114 SetCursorOffset(m_CursorPos);
115 if(!in_range<size_t>(a: m_SelectionStart, lower: 0, upper: m_Len) || !in_range<size_t>(a: m_SelectionEnd, lower: 0, upper: m_Len))
116 SetSelection(Start: m_SelectionStart, End: m_SelectionEnd);
117}
118
119const char *CLineInput::GetDisplayedString()
120{
121 if(m_pfnDisplayTextCallback)
122 return m_pfnDisplayTextCallback(m_pStr, GetNumChars());
123
124 if(!IsHidden())
125 return m_pStr;
126
127 m_StarsBuffer.resize(n: GetNumChars(), c: '*');
128 return m_StarsBuffer.c_str();
129}
130
131void CLineInput::MoveCursor(EMoveDirection Direction, bool MoveWord, const char *pStr, size_t MaxSize, size_t *pCursorPos)
132{
133 // Check whether cursor position is initially on space or non-space character.
134 // When forwarding, check character to the right of the cursor position.
135 // When rewinding, check character to the left of the cursor position (rewind first).
136 size_t PeekCursorPos = Direction == FORWARD ? *pCursorPos : str_utf8_rewind(str: pStr, cursor: *pCursorPos);
137 const char *pTemp = pStr + PeekCursorPos;
138 bool AnySpace = str_utf8_isspace(code: str_utf8_decode(ptr: &pTemp));
139 bool AnyWord = !AnySpace;
140 while(true)
141 {
142 if(Direction == FORWARD)
143 *pCursorPos = str_utf8_forward(str: pStr, cursor: *pCursorPos);
144 else
145 *pCursorPos = str_utf8_rewind(str: pStr, cursor: *pCursorPos);
146 if(!MoveWord || *pCursorPos <= 0 || *pCursorPos >= MaxSize)
147 break;
148 PeekCursorPos = Direction == FORWARD ? *pCursorPos : str_utf8_rewind(str: pStr, cursor: *pCursorPos);
149 pTemp = pStr + PeekCursorPos;
150 const bool CurrentSpace = str_utf8_isspace(code: str_utf8_decode(ptr: &pTemp));
151 const bool CurrentWord = !CurrentSpace;
152 if(Direction == FORWARD && AnySpace && !CurrentSpace)
153 break; // Forward: Stop when next (right) character is non-space after seeing at least one space character.
154 else if(Direction == REWIND && AnyWord && !CurrentWord)
155 break; // Rewind: Stop when next (left) character is space after seeing at least one non-space character.
156 AnySpace |= CurrentSpace;
157 AnyWord |= CurrentWord;
158 }
159}
160
161void CLineInput::SetCursorOffset(size_t Offset)
162{
163 m_SelectionStart = m_SelectionEnd = m_LastCompositionCursorPos = m_CursorPos = std::clamp<size_t>(val: Offset, lo: 0, hi: m_Len);
164 m_WasCursorChanged = true;
165}
166
167void CLineInput::SetSelection(size_t Start, size_t End)
168{
169 dbg_assert(m_CursorPos == Start || m_CursorPos == End, "Selection and cursor offset got desynchronized");
170 if(Start > End)
171 std::swap(a&: Start, b&: End);
172 m_SelectionStart = std::clamp<size_t>(val: Start, lo: 0, hi: m_Len);
173 m_SelectionEnd = std::clamp<size_t>(val: End, lo: 0, hi: m_Len);
174 m_WasCursorChanged = true;
175}
176
177size_t CLineInput::OffsetFromActualToDisplay(size_t ActualOffset)
178{
179 if(IsHidden() || (m_pfnCalculateOffsetCallback && m_pfnCalculateOffsetCallback()))
180 return str_utf8_offset_bytes_to_chars(str: m_pStr, byte_offset: ActualOffset);
181 return ActualOffset;
182}
183
184size_t CLineInput::OffsetFromDisplayToActual(size_t DisplayOffset)
185{
186 if(IsHidden() || (m_pfnCalculateOffsetCallback && m_pfnCalculateOffsetCallback()))
187 return str_utf8_offset_chars_to_bytes(str: m_pStr, char_offset: DisplayOffset);
188 return DisplayOffset;
189}
190
191bool CLineInput::ProcessInput(const IInput::CEvent &Event)
192{
193 // update derived attributes to handle external changes to the buffer
194 UpdateStrData();
195
196 const size_t OldCursorPos = m_CursorPos;
197 const bool Selecting = Input()->ShiftIsPressed();
198 const size_t SelectionLength = GetSelectionLength();
199 bool KeyHandled = false;
200
201 if(Event.m_Flags & IInput::FLAG_TEXT)
202 {
203 SetRange(pString: Event.m_aText, Begin: m_SelectionStart, End: m_SelectionEnd);
204 KeyHandled = true;
205 }
206
207 if(Event.m_Flags & IInput::FLAG_PRESS)
208 {
209 const bool ModPressed = Input()->ModifierIsPressed();
210 const bool AltPressed = Input()->AltIsPressed();
211
212#ifdef CONF_PLATFORM_MACOSX
213 const bool MoveWord = AltPressed && !ModPressed;
214#else
215 const bool MoveWord = ModPressed && !AltPressed;
216#endif
217
218 if(Event.m_Key == KEY_BACKSPACE)
219 {
220 if(SelectionLength)
221 {
222 SetRange(pString: "", Begin: m_SelectionStart, End: m_SelectionEnd);
223 }
224 else
225 {
226 // If in MoveWord-mode, backspace will delete the word before the selection
227 if(SelectionLength)
228 m_SelectionEnd = m_CursorPos = m_SelectionStart;
229 if(m_CursorPos > 0)
230 {
231 size_t NewCursorPos = m_CursorPos;
232 MoveCursor(Direction: REWIND, MoveWord, pStr: m_pStr, MaxSize: m_Len, pCursorPos: &NewCursorPos);
233 SetRange(pString: "", Begin: NewCursorPos, End: m_CursorPos);
234 }
235 m_SelectionStart = m_SelectionEnd = m_CursorPos;
236 }
237 KeyHandled = true;
238 }
239 else if(Event.m_Key == KEY_DELETE)
240 {
241 if(SelectionLength)
242 {
243 SetRange(pString: "", Begin: m_SelectionStart, End: m_SelectionEnd);
244 }
245 else
246 {
247 // If in MoveWord-mode, delete will delete the word after the selection
248 if(SelectionLength)
249 m_SelectionStart = m_CursorPos = m_SelectionEnd;
250 if(m_CursorPos < m_Len)
251 {
252 size_t EndCursorPos = m_CursorPos;
253 MoveCursor(Direction: FORWARD, MoveWord, pStr: m_pStr, MaxSize: m_Len, pCursorPos: &EndCursorPos);
254 SetRange(pString: "", Begin: m_CursorPos, End: EndCursorPos);
255 }
256 m_SelectionStart = m_SelectionEnd = m_CursorPos;
257 }
258 KeyHandled = true;
259 }
260 else if(Event.m_Key == KEY_LEFT)
261 {
262 if(SelectionLength && !Selecting)
263 {
264 m_CursorPos = m_SelectionStart;
265 }
266 else if(m_CursorPos > 0)
267 {
268 MoveCursor(Direction: REWIND, MoveWord, pStr: m_pStr, MaxSize: m_Len, pCursorPos: &m_CursorPos);
269 if(Selecting)
270 {
271 if(m_SelectionStart == OldCursorPos) // expand start first
272 m_SelectionStart = m_CursorPos;
273 else if(m_SelectionEnd == OldCursorPos)
274 m_SelectionEnd = m_CursorPos;
275 if(m_SelectionStart > m_SelectionEnd)
276 std::swap(a&: m_SelectionStart, b&: m_SelectionEnd);
277 }
278 }
279
280 if(!Selecting)
281 {
282 m_SelectionStart = m_SelectionEnd = m_CursorPos;
283 }
284 KeyHandled = true;
285 }
286 else if(Event.m_Key == KEY_RIGHT)
287 {
288 if(SelectionLength && !Selecting)
289 {
290 m_CursorPos = m_SelectionEnd;
291 }
292 else if(m_CursorPos < m_Len)
293 {
294 MoveCursor(Direction: FORWARD, MoveWord, pStr: m_pStr, MaxSize: m_Len, pCursorPos: &m_CursorPos);
295 if(Selecting)
296 {
297 if(m_SelectionEnd == OldCursorPos) // expand end first
298 m_SelectionEnd = m_CursorPos;
299 else if(m_SelectionStart == OldCursorPos)
300 m_SelectionStart = m_CursorPos;
301 if(m_SelectionStart > m_SelectionEnd)
302 std::swap(a&: m_SelectionStart, b&: m_SelectionEnd);
303 }
304 }
305
306 if(!Selecting)
307 {
308 m_SelectionStart = m_SelectionEnd = m_CursorPos;
309 }
310 KeyHandled = true;
311 }
312 else if(Event.m_Key == KEY_HOME)
313 {
314 if(Selecting)
315 {
316 if(SelectionLength && m_CursorPos == m_SelectionEnd)
317 m_SelectionEnd = m_SelectionStart;
318 }
319 else
320 m_SelectionEnd = 0;
321 m_CursorPos = 0;
322 m_SelectionStart = 0;
323 KeyHandled = true;
324 }
325 else if(Event.m_Key == KEY_END)
326 {
327 if(Selecting)
328 {
329 if(SelectionLength && m_CursorPos == m_SelectionStart)
330 m_SelectionStart = m_SelectionEnd;
331 }
332 else
333 m_SelectionStart = m_Len;
334 m_CursorPos = m_Len;
335 m_SelectionEnd = m_Len;
336 KeyHandled = true;
337 }
338 else if(ModPressed && !AltPressed && Event.m_Key == KEY_V)
339 {
340 std::string ClipboardText = Input()->GetClipboardText();
341 if(!ClipboardText.empty())
342 {
343 if(m_pfnClipboardLineCallback)
344 {
345 // Split clipboard text into multiple lines. Send all complete lines to callback.
346 // The lineinput is set to the last clipboard line.
347 bool FirstLine = true;
348 size_t i, Begin = 0;
349 for(i = 0; i < ClipboardText.length(); i++)
350 {
351 if(ClipboardText[i] == '\n')
352 {
353 size_t End = i;
354 if(End > 0 && ClipboardText[End - 1] == '\r')
355 {
356 --End;
357 }
358 std::string Line = ClipboardText.substr(pos: Begin, n: End - Begin);
359 str_sanitize_cc(str: Line.data());
360 if(FirstLine)
361 {
362 SetRange(pString: Line.c_str(), Begin: m_SelectionStart, End: m_SelectionEnd);
363 FirstLine = false;
364 }
365 else
366 {
367 Set(Line.c_str());
368 }
369 Begin = i + 1;
370 m_pfnClipboardLineCallback(GetString());
371 }
372 }
373 std::string Line = ClipboardText.substr(pos: Begin);
374 str_sanitize_cc(str: Line.data());
375 if(FirstLine)
376 SetRange(pString: Line.c_str(), Begin: m_SelectionStart, End: m_SelectionEnd);
377 else
378 Set(Line.c_str());
379 }
380 else
381 {
382 str_sanitize_cc(str: ClipboardText.data());
383 SetRange(pString: ClipboardText.c_str(), Begin: m_SelectionStart, End: m_SelectionEnd);
384 }
385 }
386 KeyHandled = true;
387 }
388 else if(ModPressed && !AltPressed && (Event.m_Key == KEY_C || Event.m_Key == KEY_X) && SelectionLength)
389 {
390 char *pSelection = m_pStr + m_SelectionStart;
391 const char TempChar = pSelection[SelectionLength];
392 pSelection[SelectionLength] = '\0';
393 Input()->SetClipboardText(pSelection);
394 pSelection[SelectionLength] = TempChar;
395 if(Event.m_Key == KEY_X)
396 SetRange(pString: "", Begin: m_SelectionStart, End: m_SelectionEnd);
397 KeyHandled = true;
398 }
399 else if(ModPressed && !AltPressed && Event.m_Key == KEY_A)
400 {
401 m_SelectionStart = 0;
402 m_SelectionEnd = m_CursorPos = m_Len;
403 KeyHandled = true;
404 }
405 }
406
407 m_WasCursorChanged |= OldCursorPos != m_CursorPos;
408 m_WasCursorChanged |= SelectionLength != GetSelectionLength();
409 return KeyHandled;
410}
411
412STextBoundingBox CLineInput::Render(const CUIRect *pRect, float FontSize, int Align, bool Changed, float LineWidth, float LineSpacing, const std::vector<STextColorSplit> &vColorSplits)
413{
414 // update derived attributes to handle external changes to the buffer
415 UpdateStrData();
416
417 m_WasRendered = true;
418
419 const char *pDisplayStr = GetDisplayedString();
420 const bool HasComposition = Input()->HasComposition();
421
422 if(pDisplayStr[0] == '\0' && !HasComposition && m_pEmptyText != nullptr)
423 {
424 pDisplayStr = m_pEmptyText;
425 m_MouseSelection.m_Selecting = false;
426 TextRender()->TextColor(r: 1.0f, g: 1.0f, b: 1.0f, a: 0.75f);
427 }
428
429 CTextCursor Cursor;
430 if(IsActive())
431 {
432 const size_t CursorOffset = GetCursorOffset();
433 const size_t DisplayCursorOffset = OffsetFromActualToDisplay(ActualOffset: CursorOffset);
434 const size_t CompositionStart = CursorOffset + Input()->GetCompositionCursor();
435 const size_t DisplayCompositionStart = OffsetFromActualToDisplay(ActualOffset: CompositionStart);
436 const size_t CaretOffset = HasComposition ? DisplayCompositionStart : DisplayCursorOffset;
437
438 std::string DisplayStrBuffer;
439 if(HasComposition)
440 {
441 const std::string DisplayStr = std::string(pDisplayStr);
442 DisplayStrBuffer = DisplayStr.substr(pos: 0, n: DisplayCursorOffset) + Input()->GetComposition() + DisplayStr.substr(pos: DisplayCursorOffset);
443 pDisplayStr = DisplayStrBuffer.c_str();
444 }
445
446 const STextBoundingBox BoundingBox = TextRender()->TextBoundingBox(Size: FontSize, pText: pDisplayStr, StrLength: -1, LineWidth, LineSpacing);
447 const vec2 CursorPos = CUi::CalcAlignedCursorPos(pRect, TextSize: BoundingBox.Size(), Align);
448
449 Cursor.SetPosition(CursorPos);
450 Cursor.m_FontSize = FontSize;
451 Cursor.m_LineWidth = LineWidth;
452 Cursor.m_ForceCursorRendering = Changed;
453 Cursor.m_LineSpacing = LineSpacing;
454 Cursor.m_PressMouse.x = m_MouseSelection.m_PressMouse.x;
455 Cursor.m_ReleaseMouse.x = m_MouseSelection.m_ReleaseMouse.x;
456 Cursor.m_vColorSplits = vColorSplits;
457 if(LineWidth < 0.0f)
458 {
459 // Using a Y position that's always inside the line input makes it so the selection does not reset when
460 // the mouse is moved outside the line input while selecting, which would otherwise be very inconvenient.
461 // This is a single line cursor, so we don't need the Y position to support selection over multiple lines.
462 Cursor.m_PressMouse.y = CursorPos.y + BoundingBox.m_H / 2.0f;
463 Cursor.m_ReleaseMouse.y = CursorPos.y + BoundingBox.m_H / 2.0f;
464 }
465 else
466 {
467 Cursor.m_PressMouse.y = m_MouseSelection.m_PressMouse.y;
468 Cursor.m_ReleaseMouse.y = m_MouseSelection.m_ReleaseMouse.y;
469 }
470
471 if(HasComposition)
472 {
473 // We need to track the last composition cursor position separately, because the composition
474 // cursor movement does not cause an input event that would set the Changed variable.
475 Cursor.m_ForceCursorRendering |= m_LastCompositionCursorPos != CaretOffset;
476 m_LastCompositionCursorPos = CaretOffset;
477 const size_t DisplayCompositionEnd = DisplayCursorOffset + Input()->GetCompositionLength();
478 Cursor.m_CursorMode = TEXT_CURSOR_CURSOR_MODE_SET;
479 Cursor.m_CursorCharacter = str_utf8_offset_bytes_to_chars(str: pDisplayStr, byte_offset: CaretOffset);
480 Cursor.m_CalculateSelectionMode = TEXT_CURSOR_SELECTION_MODE_SET;
481 Cursor.m_SelectionHeightFactor = 0.1f;
482 Cursor.m_SelectionStart = str_utf8_offset_bytes_to_chars(str: pDisplayStr, byte_offset: DisplayCursorOffset);
483 Cursor.m_SelectionEnd = str_utf8_offset_bytes_to_chars(str: pDisplayStr, byte_offset: DisplayCompositionEnd);
484 TextRender()->TextSelectionColor(r: 1.0f, g: 1.0f, b: 1.0f, a: 0.8f);
485 TextRender()->TextEx(pCursor: &Cursor, pText: pDisplayStr);
486 TextRender()->TextSelectionColor(Color: TextRender()->DefaultTextSelectionColor());
487 }
488 else if(GetSelectionLength())
489 {
490 const size_t Start = OffsetFromActualToDisplay(ActualOffset: GetSelectionStart());
491 const size_t End = OffsetFromActualToDisplay(ActualOffset: GetSelectionEnd());
492 Cursor.m_CursorMode = m_MouseSelection.m_Selecting ? TEXT_CURSOR_CURSOR_MODE_CALCULATE : TEXT_CURSOR_CURSOR_MODE_SET;
493 Cursor.m_CursorCharacter = str_utf8_offset_bytes_to_chars(str: pDisplayStr, byte_offset: CaretOffset);
494 Cursor.m_CalculateSelectionMode = m_MouseSelection.m_Selecting ? TEXT_CURSOR_SELECTION_MODE_CALCULATE : TEXT_CURSOR_SELECTION_MODE_SET;
495 Cursor.m_SelectionStart = str_utf8_offset_bytes_to_chars(str: pDisplayStr, byte_offset: Start);
496 Cursor.m_SelectionEnd = str_utf8_offset_bytes_to_chars(str: pDisplayStr, byte_offset: End);
497 TextRender()->TextEx(pCursor: &Cursor, pText: pDisplayStr);
498 }
499 else
500 {
501 Cursor.m_CursorMode = m_MouseSelection.m_Selecting ? TEXT_CURSOR_CURSOR_MODE_CALCULATE : TEXT_CURSOR_CURSOR_MODE_SET;
502 Cursor.m_CursorCharacter = str_utf8_offset_bytes_to_chars(str: pDisplayStr, byte_offset: CaretOffset);
503 Cursor.m_CalculateSelectionMode = m_MouseSelection.m_Selecting ? TEXT_CURSOR_SELECTION_MODE_CALCULATE : TEXT_CURSOR_SELECTION_MODE_NONE;
504 TextRender()->TextEx(pCursor: &Cursor, pText: pDisplayStr);
505 }
506
507 if(Cursor.m_CursorMode == TEXT_CURSOR_CURSOR_MODE_CALCULATE && Cursor.m_CursorCharacter >= 0)
508 {
509 const size_t NewCursorOffset = str_utf8_offset_chars_to_bytes(str: pDisplayStr, char_offset: Cursor.m_CursorCharacter);
510 SetCursorOffset(OffsetFromDisplayToActual(DisplayOffset: NewCursorOffset));
511 }
512 if(Cursor.m_CalculateSelectionMode == TEXT_CURSOR_SELECTION_MODE_CALCULATE && Cursor.m_SelectionStart >= 0 && Cursor.m_SelectionEnd >= 0)
513 {
514 const size_t NewSelectionStart = str_utf8_offset_chars_to_bytes(str: pDisplayStr, char_offset: Cursor.m_SelectionStart);
515 const size_t NewSelectionEnd = str_utf8_offset_chars_to_bytes(str: pDisplayStr, char_offset: Cursor.m_SelectionEnd);
516 SetSelection(Start: OffsetFromDisplayToActual(DisplayOffset: NewSelectionStart), End: OffsetFromDisplayToActual(DisplayOffset: NewSelectionEnd));
517 }
518
519 m_CaretPosition = Cursor.m_CursorRenderedPosition;
520
521 CTextCursor CaretCursor;
522 CaretCursor.SetPosition(CursorPos);
523 CaretCursor.m_FontSize = FontSize;
524 CaretCursor.m_Flags = 0;
525 CaretCursor.m_LineWidth = LineWidth;
526 CaretCursor.m_LineSpacing = LineSpacing;
527 CaretCursor.m_CursorMode = TEXT_CURSOR_CURSOR_MODE_SET;
528 CaretCursor.m_CursorCharacter = str_utf8_offset_bytes_to_chars(str: pDisplayStr, byte_offset: DisplayCursorOffset);
529 TextRender()->TextEx(pCursor: &CaretCursor, pText: pDisplayStr);
530 SetCompositionWindowPosition(Anchor: CaretCursor.m_CursorRenderedPosition + vec2(0.0f, CaretCursor.m_AlignedFontSize / 2.0f), LineHeight: CaretCursor.m_AlignedFontSize);
531 }
532 else
533 {
534 const STextBoundingBox BoundingBox = TextRender()->TextBoundingBox(Size: FontSize, pText: pDisplayStr, StrLength: -1, LineWidth, LineSpacing);
535 Cursor.SetPosition(CUi::CalcAlignedCursorPos(pRect, TextSize: BoundingBox.Size(), Align));
536 Cursor.m_FontSize = FontSize;
537 Cursor.m_LineWidth = LineWidth;
538 Cursor.m_LineSpacing = LineSpacing;
539 Cursor.m_vColorSplits = vColorSplits;
540 TextRender()->TextEx(pCursor: &Cursor, pText: pDisplayStr);
541 }
542
543 TextRender()->TextColor(Color: TextRender()->DefaultTextColor());
544
545 return Cursor.BoundingBox();
546}
547
548void CLineInput::RenderCandidates()
549{
550 // Check if the active line input was not rendered and deactivate it in that case.
551 // This can happen e.g. when an input in the ingame menu is active and the menu is
552 // closed or when switching between menu and editor with an active input.
553 CLineInput *pActiveInput = GetActiveInput();
554 if(pActiveInput != nullptr)
555 {
556 if(pActiveInput->m_WasRendered)
557 {
558 pActiveInput->m_WasRendered = false;
559 }
560 else
561 {
562 pActiveInput->Deactivate();
563 return;
564 }
565 }
566
567 if(!Input()->HasComposition() || !Input()->GetCandidateCount())
568 return;
569
570 const float FontSize = 7.0f;
571 const float Padding = 1.0f;
572 const float Margin = 4.0f;
573 const float Height = 300.0f;
574 const float Width = Height * Graphics()->ScreenAspect();
575 const vec2 ScreenSize = Graphics()->ScreenSize();
576
577 Graphics()->MapScreenToSize(Width, Height);
578
579 // Determine longest candidate width
580 float LongestCandidateWidth = 0.0f;
581 for(int i = 0; i < Input()->GetCandidateCount(); ++i)
582 LongestCandidateWidth = std::max(a: LongestCandidateWidth, b: TextRender()->TextWidth(Size: FontSize, pText: Input()->GetCandidate(Index: i)));
583
584 const float NumOffset = 8.0f;
585 const float RectWidth = LongestCandidateWidth + Margin + NumOffset + 2.0f * Padding;
586 const float RectHeight = Input()->GetCandidateCount() * (FontSize + 2.0f * Padding) + Margin;
587
588 vec2 Position = ms_CompositionWindowPosition / ScreenSize * vec2(Width, Height);
589 Position.y += Margin;
590
591 // Move candidate window left if needed
592 if(Position.x + RectWidth + Margin > Width)
593 Position.x -= Position.x + RectWidth + Margin - Width;
594
595 // Move candidate window up if needed
596 if(Position.y + RectHeight + Margin > Height)
597 Position.y -= RectHeight + ms_CompositionLineHeight / ScreenSize.y * Height + 2.0f * Margin;
598
599 Graphics()->TextureClear();
600 Graphics()->QuadsBegin();
601
602 // Draw window shadow
603 Graphics()->SetColor(r: 0.0f, g: 0.0f, b: 0.0f, a: 0.8f);
604 IGraphics::CQuadItem Quad = IGraphics::CQuadItem(Position.x + 0.75f, Position.y + 0.75f, RectWidth, RectHeight);
605 Graphics()->QuadsDrawTL(pArray: &Quad, Num: 1);
606
607 // Draw window background
608 Graphics()->SetColor(r: 0.15f, g: 0.15f, b: 0.15f, a: 1.0f);
609 Quad = IGraphics::CQuadItem(Position.x, Position.y, RectWidth, RectHeight);
610 Graphics()->QuadsDrawTL(pArray: &Quad, Num: 1);
611
612 // Draw selected entry highlight
613 Graphics()->SetColor(r: 0.1f, g: 0.4f, b: 0.8f, a: 1.0f);
614 Quad = IGraphics::CQuadItem(Position.x + Margin / 4.0f, Position.y + Margin / 2.0f + Input()->GetCandidateSelectedIndex() * (FontSize + 2.0f * Padding), RectWidth - Margin / 2.0f, FontSize + 2.0f * Padding);
615 Graphics()->QuadsDrawTL(pArray: &Quad, Num: 1);
616 Graphics()->QuadsEnd();
617
618 // Draw candidates
619 for(int i = 0; i < Input()->GetCandidateCount(); ++i)
620 {
621 char aBuf[3];
622 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "%d.", (i + 1) % 10);
623
624 const float PosX = Position.x + Margin / 2.0f + Padding;
625 const float PosY = Position.y + Margin / 2.0f + i * (FontSize + 2.0f * Padding) + Padding;
626 TextRender()->TextColor(r: 0.6f, g: 0.6f, b: 0.6f, a: 1.0f);
627 TextRender()->Text(x: PosX, y: PosY, Size: FontSize, pText: aBuf);
628 TextRender()->TextColor(r: 1.0f, g: 1.0f, b: 1.0f, a: 1.0f);
629 TextRender()->Text(x: PosX + NumOffset, y: PosY, Size: FontSize, pText: Input()->GetCandidate(Index: i));
630 }
631}
632
633void CLineInput::SetCompositionWindowPosition(vec2 Anchor, float LineHeight)
634{
635 const vec2 ScreenScale = Graphics()->ScreenSize() / Graphics()->GetScreen().Size();
636 ms_CompositionWindowPosition = Anchor * ScreenScale;
637 ms_CompositionLineHeight = LineHeight * ScreenScale.y;
638 Input()->SetCompositionWindowPosition(X: ms_CompositionWindowPosition.x, Y: ms_CompositionWindowPosition.y, H: ms_CompositionLineHeight);
639}
640
641void CLineInput::Activate(EInputPriority Priority)
642{
643 if(IsActive())
644 return;
645 if(ms_ActiveInputPriority != EInputPriority::NONE && Priority < ms_ActiveInputPriority)
646 return; // do not replace a higher priority input
647 if(ms_pActiveInput)
648 ms_pActiveInput->OnDeactivate();
649 ms_pActiveInput = this;
650 ms_pActiveInput->OnActivate();
651 ms_ActiveInputPriority = Priority;
652}
653
654void CLineInput::Deactivate() const
655{
656 if(!IsActive())
657 return;
658 ms_pActiveInput->OnDeactivate();
659 ms_pActiveInput = nullptr;
660 ms_ActiveInputPriority = EInputPriority::NONE;
661}
662
663void CLineInput::OnActivate()
664{
665 Input()->StartTextInput();
666}
667
668void CLineInput::OnDeactivate()
669{
670 Input()->StopTextInput();
671 m_MouseSelection.m_Selecting = false;
672}
673
674void CLineInputNumber::SetInteger(int Number, int Base, int HexPrefix)
675{
676 char aBuf[32];
677 switch(Base)
678 {
679 case 10:
680 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "%d", Number);
681 break;
682 case 16:
683 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "%0*X", HexPrefix, Number);
684 break;
685 default:
686 dbg_assert_failed("Base %d unsupported", Base);
687 }
688 if(str_comp(a: aBuf, b: GetString()) != 0)
689 Set(aBuf);
690}
691
692int CLineInputNumber::GetInteger(int Base) const
693{
694 return str_toint_base(str: GetString(), base: Base);
695}
696
697void CLineInputNumber::SetInteger64(int64_t Number, int Base, int HexPrefix)
698{
699 char aBuf[64];
700 switch(Base)
701 {
702 case 10:
703 str_format(aBuf, sizeof(aBuf), "%" PRId64, Number);
704 break;
705 case 16:
706 str_format(aBuf, sizeof(aBuf), "%0*" PRIX64, HexPrefix, Number);
707 break;
708 default:
709 dbg_assert_failed("Base %d unsupported", Base);
710 }
711 if(str_comp(a: aBuf, b: GetString()) != 0)
712 Set(aBuf);
713}
714
715int64_t CLineInputNumber::GetInteger64(int Base) const
716{
717 return str_toint64_base(str: GetString(), base: Base);
718}
719
720void CLineInputNumber::SetFloat(float Number)
721{
722 char aBuf[32];
723 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "%.3f", Number);
724 if(str_comp(a: aBuf, b: GetString()) != 0)
725 Set(aBuf);
726}
727
728float CLineInputNumber::GetFloat() const
729{
730 return str_tofloat(str: GetString());
731}
732