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 <engine/keys.h>
8#include <engine/shared/config.h>
9
10IInput *CLineInput::ms_pInput = nullptr;
11ITextRender *CLineInput::ms_pTextRender = nullptr;
12IGraphics *CLineInput::ms_pGraphics = nullptr;
13IClient *CLineInput::ms_pClient = nullptr;
14
15CLineInput *CLineInput::ms_pActiveInput = nullptr;
16EInputPriority CLineInput::ms_ActiveInputPriority = EInputPriority::NONE;
17
18vec2 CLineInput::ms_CompositionWindowPosition = vec2(0.0f, 0.0f);
19float CLineInput::ms_CompositionLineHeight = 0.0f;
20
21char CLineInput::ms_aStars[128] = "";
22
23void CLineInput::SetBuffer(char *pStr, size_t MaxSize, size_t MaxChars)
24{
25 if(m_pStr && m_pStr == pStr)
26 return;
27 const char *pLastStr = m_pStr;
28 m_pStr = pStr;
29 m_MaxSize = MaxSize;
30 m_MaxChars = MaxChars;
31 m_WasChanged = m_pStr && pLastStr && m_WasChanged;
32 m_WasCursorChanged = m_pStr && pLastStr && m_WasCursorChanged;
33 if(!pLastStr)
34 {
35 m_CursorPos = m_SelectionStart = m_SelectionEnd = m_LastCompositionCursorPos = 0;
36 m_ScrollOffset = m_ScrollOffsetChange = 0.0f;
37 m_CaretPosition = vec2(0.0f, 0.0f);
38 m_MouseSelection.m_Selecting = false;
39 m_Hidden = false;
40 m_pEmptyText = nullptr;
41 m_WasRendered = false;
42 }
43 if(m_pStr && m_pStr != pLastStr)
44 UpdateStrData();
45}
46
47void CLineInput::Clear()
48{
49 mem_zero(block: m_pStr, size: m_MaxSize);
50 UpdateStrData();
51}
52
53void CLineInput::Set(const char *pString)
54{
55 str_copy(dst: m_pStr, src: pString, dst_size: m_MaxSize);
56 UpdateStrData();
57 SetCursorOffset(m_Len);
58}
59
60void CLineInput::SetRange(const char *pString, size_t Begin, size_t End)
61{
62 if(Begin > End)
63 std::swap(a&: Begin, b&: End);
64 Begin = std::clamp<size_t>(val: Begin, lo: 0, hi: m_Len);
65 End = std::clamp<size_t>(val: End, lo: 0, hi: m_Len);
66
67 size_t RemovedCharSize, RemovedCharCount;
68 str_utf8_stats(str: m_pStr + Begin, max_size: End - Begin + 1, max_count: m_MaxChars, size: &RemovedCharSize, count: &RemovedCharCount);
69
70 size_t AddedCharSize, AddedCharCount;
71 str_utf8_stats(str: pString, max_size: m_MaxSize - m_Len + RemovedCharSize, max_count: m_MaxChars - m_NumChars + RemovedCharCount, size: &AddedCharSize, count: &AddedCharCount);
72
73 if(RemovedCharSize || AddedCharSize)
74 {
75 if(AddedCharSize < RemovedCharSize)
76 {
77 if(AddedCharSize)
78 mem_copy(dest: m_pStr + Begin, source: pString, size: AddedCharSize);
79 mem_move(dest: m_pStr + Begin + AddedCharSize, source: m_pStr + Begin + RemovedCharSize, size: m_Len - Begin - AddedCharSize);
80 }
81 else if(AddedCharSize > RemovedCharSize)
82 mem_move(dest: m_pStr + End + AddedCharSize - RemovedCharSize, source: m_pStr + End, size: m_Len - End);
83
84 if(AddedCharSize >= RemovedCharSize)
85 mem_copy(dest: m_pStr + Begin, source: pString, size: AddedCharSize);
86
87 m_CursorPos = End - RemovedCharSize + AddedCharSize;
88 m_Len += AddedCharSize - RemovedCharSize;
89 m_NumChars += AddedCharCount - RemovedCharCount;
90 m_WasChanged = true;
91 m_WasCursorChanged = true;
92 m_pStr[m_Len] = '\0';
93 m_SelectionStart = m_SelectionEnd = m_CursorPos;
94 }
95}
96
97void CLineInput::Insert(const char *pString, size_t Begin)
98{
99 SetRange(pString, Begin, End: Begin);
100}
101
102void CLineInput::Append(const char *pString)
103{
104 Insert(pString, Begin: m_Len);
105}
106
107void CLineInput::UpdateStrData()
108{
109 str_utf8_stats(str: m_pStr, max_size: m_MaxSize, max_count: m_MaxChars, size: &m_Len, count: &m_NumChars);
110 if(!in_range<size_t>(a: m_CursorPos, lower: 0, upper: m_Len))
111 SetCursorOffset(m_CursorPos);
112 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))
113 SetSelection(Start: m_SelectionStart, End: m_SelectionEnd);
114}
115
116const char *CLineInput::GetDisplayedString()
117{
118 if(m_pfnDisplayTextCallback)
119 return m_pfnDisplayTextCallback(m_pStr, GetNumChars());
120
121 if(!IsHidden())
122 return m_pStr;
123
124 const size_t NumStars = minimum(a: GetNumChars(), b: sizeof(ms_aStars) - 1);
125 for(size_t i = 0; i < NumStars; ++i)
126 ms_aStars[i] = '*';
127 ms_aStars[NumStars] = '\0';
128 return ms_aStars;
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_bytes_to_chars(str: m_pStr, byte_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 }
276 }
277
278 if(!Selecting)
279 {
280 m_SelectionStart = m_SelectionEnd = m_CursorPos;
281 }
282 KeyHandled = true;
283 }
284 else if(Event.m_Key == KEY_RIGHT)
285 {
286 if(SelectionLength && !Selecting)
287 {
288 m_CursorPos = m_SelectionEnd;
289 }
290 else if(m_CursorPos < m_Len)
291 {
292 MoveCursor(Direction: FORWARD, MoveWord, pStr: m_pStr, MaxSize: m_Len, pCursorPos: &m_CursorPos);
293 if(Selecting)
294 {
295 if(m_SelectionEnd == OldCursorPos) // expand end first
296 m_SelectionEnd = m_CursorPos;
297 else if(m_SelectionStart == OldCursorPos)
298 m_SelectionStart = m_CursorPos;
299 }
300 }
301
302 if(!Selecting)
303 {
304 m_SelectionStart = m_SelectionEnd = m_CursorPos;
305 }
306 KeyHandled = true;
307 }
308 else if(Event.m_Key == KEY_HOME)
309 {
310 if(Selecting)
311 {
312 if(SelectionLength && m_CursorPos == m_SelectionEnd)
313 m_SelectionEnd = m_SelectionStart;
314 }
315 else
316 m_SelectionEnd = 0;
317 m_CursorPos = 0;
318 m_SelectionStart = 0;
319 KeyHandled = true;
320 }
321 else if(Event.m_Key == KEY_END)
322 {
323 if(Selecting)
324 {
325 if(SelectionLength && m_CursorPos == m_SelectionStart)
326 m_SelectionStart = m_SelectionEnd;
327 }
328 else
329 m_SelectionStart = m_Len;
330 m_CursorPos = m_Len;
331 m_SelectionEnd = m_Len;
332 KeyHandled = true;
333 }
334 else if(ModPressed && !AltPressed && Event.m_Key == KEY_V)
335 {
336 std::string ClipboardText = Input()->GetClipboardText();
337 if(!ClipboardText.empty())
338 {
339 if(m_pfnClipboardLineCallback)
340 {
341 // Split clipboard text into multiple lines. Send all complete lines to callback.
342 // The lineinput is set to the last clipboard line.
343 bool FirstLine = true;
344 size_t i, Begin = 0;
345 for(i = 0; i < ClipboardText.length(); i++)
346 {
347 if(ClipboardText[i] == '\n')
348 {
349 if(i == Begin)
350 {
351 Begin++;
352 continue;
353 }
354 std::string Line = ClipboardText.substr(pos: Begin, n: i - Begin + 1);
355 if(FirstLine)
356 {
357 str_sanitize_cc(str: Line.data());
358 SetRange(pString: Line.c_str(), Begin: m_SelectionStart, End: m_SelectionEnd);
359 FirstLine = false;
360 Line = GetString();
361 }
362 Begin = i + 1;
363 str_sanitize_cc(str: Line.data());
364 m_pfnClipboardLineCallback(Line.c_str());
365 }
366 }
367 std::string Line = ClipboardText.substr(pos: Begin, n: i - Begin + 1);
368 str_sanitize_cc(str: Line.data());
369 if(FirstLine)
370 SetRange(pString: Line.c_str(), Begin: m_SelectionStart, End: m_SelectionEnd);
371 else
372 Set(Line.c_str());
373 }
374 else
375 {
376 str_sanitize_cc(str: ClipboardText.data());
377 SetRange(pString: ClipboardText.c_str(), Begin: m_SelectionStart, End: m_SelectionEnd);
378 }
379 }
380 KeyHandled = true;
381 }
382 else if(ModPressed && !AltPressed && (Event.m_Key == KEY_C || Event.m_Key == KEY_X) && SelectionLength)
383 {
384 char *pSelection = m_pStr + m_SelectionStart;
385 const char TempChar = pSelection[SelectionLength];
386 pSelection[SelectionLength] = '\0';
387 Input()->SetClipboardText(pSelection);
388 pSelection[SelectionLength] = TempChar;
389 if(Event.m_Key == KEY_X)
390 SetRange(pString: "", Begin: m_SelectionStart, End: m_SelectionEnd);
391 KeyHandled = true;
392 }
393 else if(ModPressed && !AltPressed && Event.m_Key == KEY_A)
394 {
395 m_SelectionStart = 0;
396 m_SelectionEnd = m_CursorPos = m_Len;
397 KeyHandled = true;
398 }
399 }
400
401 m_WasCursorChanged |= OldCursorPos != m_CursorPos;
402 m_WasCursorChanged |= SelectionLength != GetSelectionLength();
403 return KeyHandled;
404}
405
406STextBoundingBox CLineInput::Render(const CUIRect *pRect, float FontSize, int Align, bool Changed, float LineWidth, float LineSpacing, const std::vector<STextColorSplit> &vColorSplits)
407{
408 // update derived attributes to handle external changes to the buffer
409 UpdateStrData();
410
411 m_WasRendered = true;
412
413 const char *pDisplayStr = GetDisplayedString();
414 const bool HasComposition = Input()->HasComposition();
415
416 if(pDisplayStr[0] == '\0' && !HasComposition && m_pEmptyText != nullptr)
417 {
418 pDisplayStr = m_pEmptyText;
419 m_MouseSelection.m_Selecting = false;
420 TextRender()->TextColor(r: 1.0f, g: 1.0f, b: 1.0f, a: 0.75f);
421 }
422
423 CTextCursor Cursor;
424 if(IsActive())
425 {
426 const size_t CursorOffset = GetCursorOffset();
427 const size_t DisplayCursorOffset = OffsetFromActualToDisplay(ActualOffset: CursorOffset);
428 const size_t CompositionStart = CursorOffset + Input()->GetCompositionCursor();
429 const size_t DisplayCompositionStart = OffsetFromActualToDisplay(ActualOffset: CompositionStart);
430 const size_t CaretOffset = HasComposition ? DisplayCompositionStart : DisplayCursorOffset;
431
432 std::string DisplayStrBuffer;
433 if(HasComposition)
434 {
435 const std::string DisplayStr = std::string(pDisplayStr);
436 DisplayStrBuffer = DisplayStr.substr(pos: 0, n: DisplayCursorOffset) + Input()->GetComposition() + DisplayStr.substr(pos: DisplayCursorOffset);
437 pDisplayStr = DisplayStrBuffer.c_str();
438 }
439
440 const STextBoundingBox BoundingBox = TextRender()->TextBoundingBox(Size: FontSize, pText: pDisplayStr, StrLength: -1, LineWidth, LineSpacing);
441 const vec2 CursorPos = CUi::CalcAlignedCursorPos(pRect, TextSize: BoundingBox.Size(), Align);
442
443 Cursor.SetPosition(CursorPos);
444 Cursor.m_FontSize = FontSize;
445 Cursor.m_LineWidth = LineWidth;
446 Cursor.m_ForceCursorRendering = Changed;
447 Cursor.m_LineSpacing = LineSpacing;
448 Cursor.m_PressMouse.x = m_MouseSelection.m_PressMouse.x;
449 Cursor.m_ReleaseMouse.x = m_MouseSelection.m_ReleaseMouse.x;
450 Cursor.m_vColorSplits = vColorSplits;
451 if(LineWidth < 0.0f)
452 {
453 // Using a Y position that's always inside the line input makes it so the selection does not reset when
454 // the mouse is moved outside the line input while selecting, which would otherwise be very inconvenient.
455 // This is a single line cursor, so we don't need the Y position to support selection over multiple lines.
456 Cursor.m_PressMouse.y = CursorPos.y + BoundingBox.m_H / 2.0f;
457 Cursor.m_ReleaseMouse.y = CursorPos.y + BoundingBox.m_H / 2.0f;
458 }
459 else
460 {
461 Cursor.m_PressMouse.y = m_MouseSelection.m_PressMouse.y;
462 Cursor.m_ReleaseMouse.y = m_MouseSelection.m_ReleaseMouse.y;
463 }
464
465 if(HasComposition)
466 {
467 // We need to track the last composition cursor position separately, because the composition
468 // cursor movement does not cause an input event that would set the Changed variable.
469 Cursor.m_ForceCursorRendering |= m_LastCompositionCursorPos != CaretOffset;
470 m_LastCompositionCursorPos = CaretOffset;
471 const size_t DisplayCompositionEnd = DisplayCursorOffset + Input()->GetCompositionLength();
472 Cursor.m_CursorMode = TEXT_CURSOR_CURSOR_MODE_SET;
473 Cursor.m_CursorCharacter = str_utf8_offset_bytes_to_chars(str: pDisplayStr, byte_offset: CaretOffset);
474 Cursor.m_CalculateSelectionMode = TEXT_CURSOR_SELECTION_MODE_SET;
475 Cursor.m_SelectionHeightFactor = 0.1f;
476 Cursor.m_SelectionStart = str_utf8_offset_bytes_to_chars(str: pDisplayStr, byte_offset: DisplayCursorOffset);
477 Cursor.m_SelectionEnd = str_utf8_offset_bytes_to_chars(str: pDisplayStr, byte_offset: DisplayCompositionEnd);
478 TextRender()->TextSelectionColor(r: 1.0f, g: 1.0f, b: 1.0f, a: 0.8f);
479 TextRender()->TextEx(pCursor: &Cursor, pText: pDisplayStr);
480 TextRender()->TextSelectionColor(Color: TextRender()->DefaultTextSelectionColor());
481 }
482 else if(GetSelectionLength())
483 {
484 const size_t Start = OffsetFromActualToDisplay(ActualOffset: GetSelectionStart());
485 const size_t End = OffsetFromActualToDisplay(ActualOffset: GetSelectionEnd());
486 Cursor.m_CursorMode = m_MouseSelection.m_Selecting ? TEXT_CURSOR_CURSOR_MODE_CALCULATE : TEXT_CURSOR_CURSOR_MODE_SET;
487 Cursor.m_CursorCharacter = str_utf8_offset_bytes_to_chars(str: pDisplayStr, byte_offset: CaretOffset);
488 Cursor.m_CalculateSelectionMode = m_MouseSelection.m_Selecting ? TEXT_CURSOR_SELECTION_MODE_CALCULATE : TEXT_CURSOR_SELECTION_MODE_SET;
489 Cursor.m_SelectionStart = str_utf8_offset_bytes_to_chars(str: pDisplayStr, byte_offset: Start);
490 Cursor.m_SelectionEnd = str_utf8_offset_bytes_to_chars(str: pDisplayStr, byte_offset: End);
491 TextRender()->TextEx(pCursor: &Cursor, pText: pDisplayStr);
492 }
493 else
494 {
495 Cursor.m_CursorMode = m_MouseSelection.m_Selecting ? TEXT_CURSOR_CURSOR_MODE_CALCULATE : TEXT_CURSOR_CURSOR_MODE_SET;
496 Cursor.m_CursorCharacter = str_utf8_offset_bytes_to_chars(str: pDisplayStr, byte_offset: CaretOffset);
497 Cursor.m_CalculateSelectionMode = m_MouseSelection.m_Selecting ? TEXT_CURSOR_SELECTION_MODE_CALCULATE : TEXT_CURSOR_SELECTION_MODE_NONE;
498 TextRender()->TextEx(pCursor: &Cursor, pText: pDisplayStr);
499 }
500
501 if(Cursor.m_CursorMode == TEXT_CURSOR_CURSOR_MODE_CALCULATE && Cursor.m_CursorCharacter >= 0)
502 {
503 const size_t NewCursorOffset = str_utf8_offset_chars_to_bytes(str: pDisplayStr, char_offset: Cursor.m_CursorCharacter);
504 SetCursorOffset(OffsetFromDisplayToActual(DisplayOffset: NewCursorOffset));
505 }
506 if(Cursor.m_CalculateSelectionMode == TEXT_CURSOR_SELECTION_MODE_CALCULATE && Cursor.m_SelectionStart >= 0 && Cursor.m_SelectionEnd >= 0)
507 {
508 const size_t NewSelectionStart = str_utf8_offset_chars_to_bytes(str: pDisplayStr, char_offset: Cursor.m_SelectionStart);
509 const size_t NewSelectionEnd = str_utf8_offset_chars_to_bytes(str: pDisplayStr, char_offset: Cursor.m_SelectionEnd);
510 SetSelection(Start: OffsetFromDisplayToActual(DisplayOffset: NewSelectionStart), End: OffsetFromDisplayToActual(DisplayOffset: NewSelectionEnd));
511 }
512
513 m_CaretPosition = Cursor.m_CursorRenderedPosition;
514
515 CTextCursor CaretCursor;
516 CaretCursor.SetPosition(CursorPos);
517 CaretCursor.m_FontSize = FontSize;
518 CaretCursor.m_Flags = 0;
519 CaretCursor.m_LineWidth = LineWidth;
520 CaretCursor.m_LineSpacing = LineSpacing;
521 CaretCursor.m_CursorMode = TEXT_CURSOR_CURSOR_MODE_SET;
522 CaretCursor.m_CursorCharacter = str_utf8_offset_bytes_to_chars(str: pDisplayStr, byte_offset: DisplayCursorOffset);
523 TextRender()->TextEx(pCursor: &CaretCursor, pText: pDisplayStr);
524 SetCompositionWindowPosition(Anchor: CaretCursor.m_CursorRenderedPosition + vec2(0.0f, CaretCursor.m_AlignedFontSize / 2.0f), LineHeight: CaretCursor.m_AlignedFontSize);
525 }
526 else
527 {
528 const STextBoundingBox BoundingBox = TextRender()->TextBoundingBox(Size: FontSize, pText: pDisplayStr, StrLength: -1, LineWidth, LineSpacing);
529 Cursor.SetPosition(CUi::CalcAlignedCursorPos(pRect, TextSize: BoundingBox.Size(), Align));
530 Cursor.m_FontSize = FontSize;
531 Cursor.m_LineWidth = LineWidth;
532 Cursor.m_LineSpacing = LineSpacing;
533 Cursor.m_vColorSplits = vColorSplits;
534 TextRender()->TextEx(pCursor: &Cursor, pText: pDisplayStr);
535 }
536
537 TextRender()->TextColor(Color: TextRender()->DefaultTextColor());
538
539 return Cursor.BoundingBox();
540}
541
542void CLineInput::RenderCandidates()
543{
544 // Check if the active line input was not rendered and deactivate it in that case.
545 // This can happen e.g. when an input in the ingame menu is active and the menu is
546 // closed or when switching between menu and editor with an active input.
547 CLineInput *pActiveInput = GetActiveInput();
548 if(pActiveInput != nullptr)
549 {
550 if(pActiveInput->m_WasRendered)
551 {
552 pActiveInput->m_WasRendered = false;
553 }
554 else
555 {
556 pActiveInput->Deactivate();
557 return;
558 }
559 }
560
561 if(!Input()->HasComposition() || !Input()->GetCandidateCount())
562 return;
563
564 const float FontSize = 7.0f;
565 const float Padding = 1.0f;
566 const float Margin = 4.0f;
567 const float Height = 300.0f;
568 const float Width = Height * Graphics()->ScreenAspect();
569 const int ScreenWidth = Graphics()->ScreenWidth();
570 const int ScreenHeight = Graphics()->ScreenHeight();
571
572 Graphics()->MapScreen(TopLeftX: 0.0f, TopLeftY: 0.0f, BottomRightX: Width, BottomRightY: Height);
573
574 // Determine longest candidate width
575 float LongestCandidateWidth = 0.0f;
576 for(int i = 0; i < Input()->GetCandidateCount(); ++i)
577 LongestCandidateWidth = maximum(a: LongestCandidateWidth, b: TextRender()->TextWidth(Size: FontSize, pText: Input()->GetCandidate(Index: i)));
578
579 const float NumOffset = 8.0f;
580 const float RectWidth = LongestCandidateWidth + Margin + NumOffset + 2.0f * Padding;
581 const float RectHeight = Input()->GetCandidateCount() * (FontSize + 2.0f * Padding) + Margin;
582
583 vec2 Position = ms_CompositionWindowPosition / vec2(ScreenWidth, ScreenHeight) * vec2(Width, Height);
584 Position.y += Margin;
585
586 // Move candidate window left if needed
587 if(Position.x + RectWidth + Margin > Width)
588 Position.x -= Position.x + RectWidth + Margin - Width;
589
590 // Move candidate window up if needed
591 if(Position.y + RectHeight + Margin > Height)
592 Position.y -= RectHeight + ms_CompositionLineHeight / ScreenHeight * Height + 2.0f * Margin;
593
594 Graphics()->TextureClear();
595 Graphics()->QuadsBegin();
596 Graphics()->BlendNormal();
597
598 // Draw window shadow
599 Graphics()->SetColor(r: 0.0f, g: 0.0f, b: 0.0f, a: 0.8f);
600 IGraphics::CQuadItem Quad = IGraphics::CQuadItem(Position.x + 0.75f, Position.y + 0.75f, RectWidth, RectHeight);
601 Graphics()->QuadsDrawTL(pArray: &Quad, Num: 1);
602
603 // Draw window background
604 Graphics()->SetColor(r: 0.15f, g: 0.15f, b: 0.15f, a: 1.0f);
605 Quad = IGraphics::CQuadItem(Position.x, Position.y, RectWidth, RectHeight);
606 Graphics()->QuadsDrawTL(pArray: &Quad, Num: 1);
607
608 // Draw selected entry highlight
609 Graphics()->SetColor(r: 0.1f, g: 0.4f, b: 0.8f, a: 1.0f);
610 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);
611 Graphics()->QuadsDrawTL(pArray: &Quad, Num: 1);
612 Graphics()->QuadsEnd();
613
614 // Draw candidates
615 for(int i = 0; i < Input()->GetCandidateCount(); ++i)
616 {
617 char aBuf[3];
618 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "%d.", (i + 1) % 10);
619
620 const float PosX = Position.x + Margin / 2.0f + Padding;
621 const float PosY = Position.y + Margin / 2.0f + i * (FontSize + 2.0f * Padding) + Padding;
622 TextRender()->TextColor(r: 0.6f, g: 0.6f, b: 0.6f, a: 1.0f);
623 TextRender()->Text(x: PosX, y: PosY, Size: FontSize, pText: aBuf);
624 TextRender()->TextColor(r: 1.0f, g: 1.0f, b: 1.0f, a: 1.0f);
625 TextRender()->Text(x: PosX + NumOffset, y: PosY, Size: FontSize, pText: Input()->GetCandidate(Index: i));
626 }
627}
628
629void CLineInput::SetCompositionWindowPosition(vec2 Anchor, float LineHeight)
630{
631 float ScreenX0, ScreenY0, ScreenX1, ScreenY1;
632 const int ScreenWidth = Graphics()->ScreenWidth();
633 const int ScreenHeight = Graphics()->ScreenHeight();
634 Graphics()->GetScreen(pTopLeftX: &ScreenX0, pTopLeftY: &ScreenY0, pBottomRightX: &ScreenX1, pBottomRightY: &ScreenY1);
635
636 const vec2 ScreenScale = vec2(ScreenWidth / (ScreenX1 - ScreenX0), ScreenHeight / (ScreenY1 - ScreenY0));
637 ms_CompositionWindowPosition = Anchor * ScreenScale;
638 ms_CompositionLineHeight = LineHeight * ScreenScale.y;
639 Input()->SetCompositionWindowPosition(X: ms_CompositionWindowPosition.x, Y: ms_CompositionWindowPosition.y, H: ms_CompositionLineHeight);
640}
641
642void CLineInput::Activate(EInputPriority Priority)
643{
644 if(IsActive())
645 return;
646 if(ms_ActiveInputPriority != EInputPriority::NONE && Priority < ms_ActiveInputPriority)
647 return; // do not replace a higher priority input
648 if(ms_pActiveInput)
649 ms_pActiveInput->OnDeactivate();
650 ms_pActiveInput = this;
651 ms_pActiveInput->OnActivate();
652 ms_ActiveInputPriority = Priority;
653}
654
655void CLineInput::Deactivate() const
656{
657 if(!IsActive())
658 return;
659 ms_pActiveInput->OnDeactivate();
660 ms_pActiveInput = nullptr;
661 ms_ActiveInputPriority = EInputPriority::NONE;
662}
663
664void CLineInput::OnActivate()
665{
666 Input()->StartTextInput();
667}
668
669void CLineInput::OnDeactivate()
670{
671 Input()->StopTextInput();
672 m_MouseSelection.m_Selecting = false;
673}
674
675void CLineInputNumber::SetInteger(int Number, int Base, int HexPrefix)
676{
677 char aBuf[32];
678 switch(Base)
679 {
680 case 10:
681 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "%d", Number);
682 break;
683 case 16:
684 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "%0*X", HexPrefix, Number);
685 break;
686 default:
687 dbg_assert_failed("Base %d unsupported", Base);
688 }
689 if(str_comp(a: aBuf, b: GetString()) != 0)
690 Set(aBuf);
691}
692
693int CLineInputNumber::GetInteger(int Base) const
694{
695 return str_toint_base(str: GetString(), base: Base);
696}
697
698void CLineInputNumber::SetInteger64(int64_t Number, int Base, int HexPrefix)
699{
700 char aBuf[64];
701 switch(Base)
702 {
703 case 10:
704 str_format(aBuf, sizeof(aBuf), "%" PRId64, Number);
705 break;
706 case 16:
707 str_format(aBuf, sizeof(aBuf), "%0*" PRIX64, HexPrefix, Number);
708 break;
709 default:
710 dbg_assert_failed("Base %d unsupported", Base);
711 }
712 if(str_comp(a: aBuf, b: GetString()) != 0)
713 Set(aBuf);
714}
715
716int64_t CLineInputNumber::GetInteger64(int Base) const
717{
718 return str_toint64_base(str: GetString(), base: Base);
719}
720
721void CLineInputNumber::SetFloat(float Number)
722{
723 char aBuf[32];
724 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "%.3f", Number);
725 if(str_comp(a: aBuf, b: GetString()) != 0)
726 Set(aBuf);
727}
728
729float CLineInputNumber::GetFloat() const
730{
731 return str_tofloat(str: GetString());
732}
733