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 "ui.h"
4
5#include "ui_scrollregion.h"
6
7#include <base/dbg.h>
8#include <base/math.h>
9#include <base/str.h>
10#include <base/time.h>
11
12#include <engine/client.h>
13#include <engine/font_icons.h>
14#include <engine/graphics.h>
15#include <engine/input.h>
16#include <engine/keys.h>
17#include <engine/shared/config.h>
18
19#include <game/localization.h>
20
21constexpr float TOOLTIP_FONTSIZE = 14.0f;
22
23void CUIElement::Init(CUi *pUI, int RequestedRectCount)
24{
25 m_pUI = pUI;
26 pUI->AddUIElement(pElement: this);
27 if(RequestedRectCount > 0)
28 InitRects(RequestedRectCount);
29}
30
31void CUIElement::InitRects(int RequestedRectCount)
32{
33 dbg_assert(m_vUIRects.empty(), "UI rects can only be initialized once, create another ui element instead.");
34 m_vUIRects.resize(sz: RequestedRectCount);
35 for(auto &Rect : m_vUIRects)
36 Rect.m_pParent = this;
37}
38
39CUIElement::SUIElementRect::SUIElementRect() { Reset(); }
40
41void CUIElement::SUIElementRect::Reset()
42{
43 m_UIRectQuadContainer = -1;
44 m_UITextContainer.Reset();
45 m_X = -1;
46 m_Y = -1;
47 m_Width = -1;
48 m_Height = -1;
49 m_Rounding = -1.0f;
50 m_Corners = -1;
51 m_Text.clear();
52 m_Cursor = CTextCursor();
53 m_TextColor = ColorRGBA(-1, -1, -1, -1);
54 m_TextOutlineColor = ColorRGBA(-1, -1, -1, -1);
55 m_QuadColor = ColorRGBA(-1, -1, -1, -1);
56 m_ReadCursorGlyphCount = -1;
57}
58
59void CUIElement::SUIElementRect::Draw(const CUIRect *pRect, ColorRGBA Color, int Corners, float Rounding)
60{
61 bool NeedsRecreate = false;
62 if(m_UIRectQuadContainer == -1 || m_Width != pRect->w || m_Height != pRect->h || m_QuadColor != Color)
63 {
64 m_pParent->Ui()->Graphics()->DeleteQuadContainer(ContainerIndex&: m_UIRectQuadContainer);
65 NeedsRecreate = true;
66 }
67 m_X = pRect->x;
68 m_Y = pRect->y;
69 if(NeedsRecreate)
70 {
71 m_Width = pRect->w;
72 m_Height = pRect->h;
73 m_QuadColor = Color;
74
75 m_pParent->Ui()->Graphics()->SetColor(Color);
76 m_UIRectQuadContainer = m_pParent->Ui()->Graphics()->CreateRectQuadContainer(x: 0, y: 0, w: pRect->w, h: pRect->h, r: Rounding, Corners);
77 m_pParent->Ui()->Graphics()->SetColor(r: 1, g: 1, b: 1, a: 1);
78 }
79
80 m_pParent->Ui()->Graphics()->TextureClear();
81 m_pParent->Ui()->Graphics()->RenderQuadContainerEx(ContainerIndex: m_UIRectQuadContainer,
82 QuadOffset: 0, QuadDrawNum: -1, X: m_X, Y: m_Y, ScaleX: 1, ScaleY: 1);
83}
84
85void SLabelProperties::SetColor(const ColorRGBA &Color)
86{
87 m_vColorSplits.clear();
88 m_vColorSplits.emplace_back(args: 0, args: -1, args: Color);
89}
90
91/********************************************************
92 UI
93*********************************************************/
94
95const CLinearScrollbarScale CUi::ms_LinearScrollbarScale;
96const CLogarithmicScrollbarScale CUi::ms_LogarithmicScrollbarScale(25);
97const CDarkButtonColorFunction CUi::ms_DarkButtonColorFunction;
98const CLightButtonColorFunction CUi::ms_LightButtonColorFunction;
99const CScrollBarColorFunction CUi::ms_ScrollBarColorFunction;
100const float CUi::ms_FontmodHeight = 0.8f;
101
102CUi *CUIElementBase::ms_pUi = nullptr;
103
104IClient *CUIElementBase::Client() const { return ms_pUi->Client(); }
105IGraphics *CUIElementBase::Graphics() const { return ms_pUi->Graphics(); }
106IInput *CUIElementBase::Input() const { return ms_pUi->Input(); }
107ITextRender *CUIElementBase::TextRender() const { return ms_pUi->TextRender(); }
108
109void CUi::Init(IKernel *pKernel)
110{
111 m_pClient = pKernel->RequestInterface<IClient>();
112 m_pGraphics = pKernel->RequestInterface<IGraphics>();
113 m_pInput = pKernel->RequestInterface<IInput>();
114 m_pTextRender = pKernel->RequestInterface<ITextRender>();
115 CUIRect::Init(pGraphics: m_pGraphics);
116 CLineInput::Init(pClient: m_pClient, pGraphics: m_pGraphics, pInput: m_pInput, pTextRender: m_pTextRender);
117 CUIElementBase::Init(pUI: this);
118 m_pTooltips = std::make_unique<CTooltips>();
119 m_pTooltips->Init(pUi: this, pTextRender: m_pTextRender);
120}
121
122CUi::CUi()
123{
124 m_Enabled = true;
125
126 m_Screen.x = 0.0f;
127 m_Screen.y = 0.0f;
128}
129
130CUi::~CUi()
131{
132 for(CUIElement *&pEl : m_vpOwnUIElements)
133 {
134 delete pEl;
135 }
136 m_vpOwnUIElements.clear();
137}
138
139CUIElement *CUi::GetNewUIElement(int RequestedRectCount)
140{
141 CUIElement *pNewEl = new CUIElement(this, RequestedRectCount);
142
143 m_vpOwnUIElements.push_back(x: pNewEl);
144
145 return pNewEl;
146}
147
148void CUi::AddUIElement(CUIElement *pElement)
149{
150 m_vpUIElements.push_back(x: pElement);
151}
152
153void CUi::ResetUIElement(CUIElement &UIElement) const
154{
155 for(CUIElement::SUIElementRect &Rect : UIElement.m_vUIRects)
156 {
157 Graphics()->DeleteQuadContainer(ContainerIndex&: Rect.m_UIRectQuadContainer);
158 TextRender()->DeleteTextContainer(TextContainerIndex&: Rect.m_UITextContainer);
159 Rect.Reset();
160 }
161}
162
163void CUi::OnElementsReset()
164{
165 for(CUIElement *pEl : m_vpUIElements)
166 {
167 ResetUIElement(UIElement&: *pEl);
168 }
169}
170
171void CUi::OnWindowResize()
172{
173 OnElementsReset();
174}
175
176void CUi::OnCursorMove(float X, float Y)
177{
178 if(!CheckMouseLock())
179 {
180 m_UpdatedMousePos.x = std::clamp(val: m_UpdatedMousePos.x + X, lo: 0.0f, hi: Graphics()->WindowWidth() - 1.0f);
181 m_UpdatedMousePos.y = std::clamp(val: m_UpdatedMousePos.y + Y, lo: 0.0f, hi: Graphics()->WindowHeight() - 1.0f);
182 }
183
184 m_UpdatedMouseDelta += vec2(X, Y);
185}
186
187void CUi::Update()
188{
189 const vec2 WindowSize = vec2(Graphics()->WindowWidth(), Graphics()->WindowHeight());
190 const CUIRect *pScreen = Screen();
191
192 unsigned UpdatedMouseButtonsNext = 0;
193 if(Enabled())
194 {
195 // Update mouse buttons based on mouse keys
196 for(int MouseKey = KEY_MOUSE_1; MouseKey <= KEY_MOUSE_3; ++MouseKey)
197 {
198 if(Input()->KeyIsPressed(Key: MouseKey))
199 {
200 m_UpdatedMouseButtons |= 1 << (MouseKey - KEY_MOUSE_1);
201 }
202 }
203
204 // Update mouse position and buttons based on touch finger state
205 UpdateTouchState(State&: m_TouchState);
206 if(m_TouchState.m_AnyPressed)
207 {
208 if(!CheckMouseLock())
209 {
210 m_UpdatedMousePos = m_TouchState.m_PrimaryPosition * WindowSize;
211 m_UpdatedMousePos.x = std::clamp(val: m_UpdatedMousePos.x, lo: 0.0f, hi: WindowSize.x - 1.0f);
212 m_UpdatedMousePos.y = std::clamp(val: m_UpdatedMousePos.y, lo: 0.0f, hi: WindowSize.y - 1.0f);
213 }
214 m_UpdatedMouseDelta += m_TouchState.m_PrimaryDelta * WindowSize;
215
216 // Scroll currently hovered scroll region with touch scroll gesture.
217 if(m_TouchState.m_ScrollAmount != vec2(0.0f, 0.0f))
218 {
219 if(m_pHotScrollRegion != nullptr)
220 {
221 m_pHotScrollRegion->ScrollRelativeDirect(ScrollAmount: -m_TouchState.m_ScrollAmount * pScreen->Size());
222 }
223 m_TouchState.m_ScrollAmount = vec2(0.0f, 0.0f);
224 }
225
226 // We need to delay the click until the next update or it's not possible to use UI
227 // elements because click and hover would happen at the same time for touch events.
228 if(m_TouchState.m_PrimaryPressed)
229 {
230 UpdatedMouseButtonsNext |= 1;
231 }
232 if(m_TouchState.m_SecondaryPressed)
233 {
234 UpdatedMouseButtonsNext |= 2;
235 }
236 }
237 }
238
239 m_MousePos = m_UpdatedMousePos * vec2(pScreen->w, pScreen->h) / WindowSize;
240 m_MouseDelta = m_UpdatedMouseDelta;
241 m_UpdatedMouseDelta = vec2(0.0f, 0.0f);
242 m_LastMouseButtons = m_MouseButtons;
243 m_MouseButtons = m_UpdatedMouseButtons;
244 m_UpdatedMouseButtons = UpdatedMouseButtonsNext;
245
246 m_pHotItem = m_pBecomingHotItem;
247 if(m_pActiveItem)
248 m_pHotItem = m_pActiveItem;
249 m_pBecomingHotItem = nullptr;
250 m_pHotScrollRegion = m_pBecomingHotScrollRegion;
251 m_pBecomingHotScrollRegion = nullptr;
252
253 if(Enabled())
254 {
255 CLineInput *pActiveInput = CLineInput::GetActiveInput();
256 if(pActiveInput && m_pLastActiveItem && pActiveInput != m_pLastActiveItem)
257 pActiveInput->Deactivate();
258 }
259 else
260 {
261 m_pHotItem = nullptr;
262 m_pActiveItem = nullptr;
263 m_pHotScrollRegion = nullptr;
264 }
265
266 m_ProgressSpinnerOffset += Client()->RenderFrameTime() * 1.5f;
267 m_ProgressSpinnerOffset = std::fmod(x: m_ProgressSpinnerOffset, y: 1.0f);
268}
269
270void CUi::DebugRender(float X, float Y)
271{
272 MapScreen();
273
274 char aBuf[128];
275 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "hot=%p nexthot=%p active=%p lastactive=%p", HotItem(), NextHotItem(), ActiveItem(), m_pLastActiveItem);
276 TextRender()->Text(x: X, y: Y, Size: 10.0f, pText: aBuf);
277}
278
279bool CUi::MouseInside(const CUIRect *pRect) const
280{
281 return pRect->Inside(Point: MousePos());
282}
283
284void CUi::ConvertMouseMove(float *pX, float *pY, IInput::ECursorType CursorType) const
285{
286 float Factor = 1.0f;
287 switch(CursorType)
288 {
289 case IInput::CURSOR_MOUSE:
290 Factor = g_Config.m_UiMousesens / 100.0f;
291 break;
292 case IInput::CURSOR_JOYSTICK:
293 Factor = g_Config.m_UiControllerSens / 100.0f;
294 break;
295 default:
296 dbg_assert_failed("CUi::ConvertMouseMove CursorType %d", (int)CursorType);
297 }
298
299 if(m_MouseSlow)
300 Factor *= 0.05f;
301
302 *pX *= Factor;
303 *pY *= Factor;
304}
305
306void CUi::UpdateTouchState(CTouchState &State) const
307{
308 const std::vector<IInput::CTouchFingerState> &vTouchFingerStates = Input()->TouchFingerStates();
309
310 // Updated touch position as long as any finger is beinged pressed.
311 const bool WasAnyPressed = State.m_AnyPressed;
312 State.m_AnyPressed = !vTouchFingerStates.empty();
313 if(State.m_AnyPressed)
314 {
315 // We always use the position of first finger being pressed down. Multi-touch UI is
316 // not possible and always choosing the last finger would cause the cursor to briefly
317 // warp without having any effect if multiple fingers are used.
318 const IInput::CTouchFingerState &PrimaryTouchFingerState = vTouchFingerStates.front();
319 State.m_PrimaryPosition = PrimaryTouchFingerState.m_Position;
320 State.m_PrimaryDelta = PrimaryTouchFingerState.m_Delta;
321 }
322
323 // Update primary (left click) and secondary (right click) action.
324 if(State.m_SecondaryPressedNext)
325 {
326 // The secondary action is delayed by one frame until the primary has been released,
327 // otherwise most UI elements cannot be activated by the secondary action because they
328 // never become the hot-item unless all mouse buttons are released for one frame.
329 State.m_SecondaryPressedNext = false;
330 State.m_SecondaryPressed = true;
331 }
332 else if(vTouchFingerStates.size() != 1)
333 {
334 // Consider primary and secondary to be pressed only when exactly one finger is pressed,
335 // to avoid UI elements and console text selection being activated while scrolling.
336 State.m_PrimaryPressed = false;
337 State.m_SecondaryPressed = false;
338 }
339 else if(!WasAnyPressed)
340 {
341 State.m_PrimaryPressed = true;
342 State.m_SecondaryActivationTime = Client()->GlobalTime();
343 State.m_SecondaryActivationDelta = vec2(0.0f, 0.0f);
344 }
345 else if(State.m_PrimaryPressed)
346 {
347 // Activate secondary by pressing and holding roughly on the same position for some time.
348 const float SecondaryActivationDelay = 0.5f;
349 const float SecondaryActivationMaxDistance = 0.001f;
350 State.m_SecondaryActivationDelta += State.m_PrimaryDelta;
351 if(Client()->GlobalTime() - State.m_SecondaryActivationTime >= SecondaryActivationDelay &&
352 length(a: State.m_SecondaryActivationDelta) <= SecondaryActivationMaxDistance)
353 {
354 State.m_PrimaryPressed = false;
355 State.m_SecondaryPressedNext = true;
356 }
357 }
358
359 // Handle two fingers being moved roughly in same direction as a scrolling gesture.
360 if(vTouchFingerStates.size() == 2)
361 {
362 const vec2 Delta0 = vTouchFingerStates[0].m_Delta;
363 const vec2 Delta1 = vTouchFingerStates[1].m_Delta;
364 const float Similarity = dot(a: normalize(v: Delta0), b: normalize(v: Delta1));
365 const float SimilarityThreshold = 0.8f; // How parallel the deltas have to be (1.0f being completely parallel)
366 if(Similarity > SimilarityThreshold)
367 {
368 const float DirectionThreshold = 3.0f; // How much longer the delta of one axis has to be compared to other axis
369
370 // Vertical scrolling (y-delta must be larger than x-delta)
371 if(absolute(a: Delta0.y) > DirectionThreshold * absolute(a: Delta0.x) &&
372 absolute(a: Delta1.y) > DirectionThreshold * absolute(a: Delta1.x) &&
373 Delta0.y * Delta1.y > 0.0f) // Same y direction required
374 {
375 // Accumulate average delta of the two fingers
376 State.m_ScrollAmount.y += (Delta0.y + Delta1.y) / 2.0f;
377 }
378 else if(absolute(a: Delta0.x) > DirectionThreshold * absolute(a: Delta0.y) && // Horizontal scrolling (x-delta must be larger than y-delta)
379 absolute(a: Delta1.x) > DirectionThreshold * absolute(a: Delta1.y) &&
380 Delta0.x * Delta1.x > 0.0f) // Same x direction required
381 {
382 // Accumulate average delta of the two fingers
383 State.m_ScrollAmount.x += (Delta0.x + Delta1.x) / 2.0f;
384 }
385 }
386 }
387 else
388 {
389 // Scrolling gesture should start from zero again if released.
390 State.m_ScrollAmount = vec2(0.0f, 0.0f);
391 }
392}
393
394bool CUi::ConsumeHotkey(EHotkey Hotkey)
395{
396 const bool Pressed = m_HotkeysPressed & Hotkey;
397 m_HotkeysPressed &= ~Hotkey;
398 return Pressed;
399}
400
401bool CUi::OnInput(const IInput::CEvent &Event)
402{
403 if(!Enabled())
404 return false;
405
406 CLineInput *pActiveInput = CLineInput::GetActiveInput();
407 if(pActiveInput && pActiveInput->ProcessInput(Event))
408 return true;
409
410 if(Event.m_Flags & IInput::FLAG_PRESS)
411 {
412 unsigned LastHotkeysPressed = m_HotkeysPressed;
413 if(Event.m_Key == KEY_RETURN || Event.m_Key == KEY_KP_ENTER)
414 m_HotkeysPressed |= HOTKEY_ENTER;
415 else if(Event.m_Key == KEY_ESCAPE)
416 m_HotkeysPressed |= HOTKEY_ESCAPE;
417 else if(Event.m_Key == KEY_TAB && !Input()->AltIsPressed())
418 m_HotkeysPressed |= HOTKEY_TAB;
419 else if(Event.m_Key == KEY_DELETE)
420 m_HotkeysPressed |= HOTKEY_DELETE;
421 else if(Event.m_Key == KEY_UP)
422 m_HotkeysPressed |= HOTKEY_UP;
423 else if(Event.m_Key == KEY_DOWN)
424 m_HotkeysPressed |= HOTKEY_DOWN;
425 else if(Event.m_Key == KEY_LEFT)
426 m_HotkeysPressed |= HOTKEY_LEFT;
427 else if(Event.m_Key == KEY_RIGHT)
428 m_HotkeysPressed |= HOTKEY_RIGHT;
429 else if(Event.m_Key == KEY_MOUSE_WHEEL_UP)
430 m_HotkeysPressed |= HOTKEY_SCROLL_UP;
431 else if(Event.m_Key == KEY_MOUSE_WHEEL_DOWN)
432 m_HotkeysPressed |= HOTKEY_SCROLL_DOWN;
433 else if(Event.m_Key == KEY_PAGEUP)
434 m_HotkeysPressed |= HOTKEY_PAGE_UP;
435 else if(Event.m_Key == KEY_PAGEDOWN)
436 m_HotkeysPressed |= HOTKEY_PAGE_DOWN;
437 else if(Event.m_Key == KEY_HOME)
438 m_HotkeysPressed |= HOTKEY_HOME;
439 else if(Event.m_Key == KEY_END)
440 m_HotkeysPressed |= HOTKEY_END;
441 return LastHotkeysPressed != m_HotkeysPressed;
442 }
443 return false;
444}
445
446float CUi::ButtonColorMul(const void *pId)
447{
448 if(CheckActiveItem(pId))
449 return ButtonColorMulActive();
450 else if(HotItem() == pId)
451 return ButtonColorMulHot();
452 return ButtonColorMulDefault();
453}
454
455const CUIRect *CUi::Screen()
456{
457 m_Screen.h = 600.0f;
458 m_Screen.w = Graphics()->ScreenAspect() * m_Screen.h;
459 return &m_Screen;
460}
461
462void CUi::MapScreen()
463{
464 const CUIRect *pScreen = Screen();
465
466 // x and y are supposed to be 0
467 Graphics()->MapScreenToSize(Width: pScreen->w, Height: pScreen->h);
468}
469
470float CUi::PixelSize()
471{
472 return Screen()->w / Graphics()->ScreenWidth();
473}
474
475void CUi::ClipEnable(const CUIRect *pRect)
476{
477 if(IsClipped())
478 {
479 const CUIRect *pOldRect = ClipArea();
480 CUIRect Intersection;
481 Intersection.x = std::max(a: pRect->x, b: pOldRect->x);
482 Intersection.y = std::max(a: pRect->y, b: pOldRect->y);
483 Intersection.w = std::min(a: pRect->x + pRect->w, b: pOldRect->x + pOldRect->w) - Intersection.x;
484 Intersection.h = std::min(a: pRect->y + pRect->h, b: pOldRect->y + pOldRect->h) - Intersection.y;
485 m_vClips.push_back(x: Intersection);
486 }
487 else
488 {
489 m_vClips.push_back(x: *pRect);
490 }
491 UpdateClipping();
492}
493
494void CUi::ClipDisable()
495{
496 dbg_assert(IsClipped(), "no clip region");
497 m_vClips.pop_back();
498 UpdateClipping();
499}
500
501const CUIRect *CUi::ClipArea() const
502{
503 dbg_assert(IsClipped(), "no clip region");
504 return &m_vClips.back();
505}
506
507void CUi::UpdateClipping()
508{
509 if(IsClipped())
510 {
511 const CUIRect *pRect = ClipArea();
512 const float XScale = Graphics()->ScreenWidth() / Screen()->w;
513 const float YScale = Graphics()->ScreenHeight() / Screen()->h;
514
515 const float ScaledX = pRect->x * XScale;
516 const float ScaledY = pRect->y * YScale;
517 const float RoundX = std::round(x: ScaledX);
518 const float RoundY = std::round(x: ScaledY);
519 Graphics()->ClipEnable(x: RoundX, y: RoundY, w: std::round(x: pRect->w * XScale + (ScaledX - RoundX)), h: std::round(x: pRect->h * YScale + (ScaledY - RoundY)));
520 }
521 else
522 {
523 Graphics()->ClipDisable();
524 }
525}
526
527int CUi::DoButtonLogic(const void *pId, int Checked, const CUIRect *pRect, const unsigned Flags)
528{
529 int ReturnValue = 0;
530 const bool Inside = MouseHovered(pRect);
531
532 if(CheckActiveItem(pId))
533 {
534 dbg_assert(m_ActiveButtonLogicButton >= 0, "m_ActiveButtonLogicButton invalid");
535 if(!MouseButton(Index: m_ActiveButtonLogicButton))
536 {
537 if(Inside && Checked >= 0)
538 ReturnValue = 1 + m_ActiveButtonLogicButton;
539 SetActiveItem(nullptr);
540 m_ActiveButtonLogicButton = -1;
541 }
542 }
543
544 bool NoRelevantButtonsPressed = true;
545 for(int Button = 0; Button < 3; ++Button)
546 {
547 if((Flags & (BUTTONFLAG_LEFT << Button)) && MouseButton(Index: Button))
548 {
549 NoRelevantButtonsPressed = false;
550 if(HotItem() == pId)
551 {
552 SetActiveItem(pId);
553 m_ActiveButtonLogicButton = Button;
554 }
555 }
556 }
557
558 if(Inside && NoRelevantButtonsPressed)
559 SetHotItem(pId);
560
561 return ReturnValue;
562}
563
564int CUi::DoDraggableButtonLogic(const void *pId, int Checked, const CUIRect *pRect, bool *pClicked, bool *pAbrupted)
565{
566 // logic
567 int ReturnValue = 0;
568 const bool Inside = MouseHovered(pRect);
569
570 if(pClicked != nullptr)
571 *pClicked = false;
572 if(pAbrupted != nullptr)
573 *pAbrupted = false;
574
575 if(CheckActiveItem(pId))
576 {
577 dbg_assert(m_ActiveDraggableButtonLogicButton >= 0, "m_ActiveDraggableButtonLogicButton invalid");
578 if(m_ActiveDraggableButtonLogicButton == 0)
579 {
580 if(Checked >= 0)
581 ReturnValue = 1 + m_ActiveDraggableButtonLogicButton;
582 if(!MouseButton(Index: m_ActiveDraggableButtonLogicButton))
583 {
584 if(pClicked != nullptr)
585 *pClicked = true;
586 SetActiveItem(nullptr);
587 m_ActiveDraggableButtonLogicButton = -1;
588 }
589 if(MouseButton(Index: 1))
590 {
591 if(pAbrupted != nullptr)
592 *pAbrupted = true;
593 SetActiveItem(nullptr);
594 m_ActiveDraggableButtonLogicButton = -1;
595 }
596 }
597 else if(!MouseButton(Index: m_ActiveDraggableButtonLogicButton))
598 {
599 if(Inside && Checked >= 0)
600 ReturnValue = 1 + m_ActiveDraggableButtonLogicButton;
601 if(pClicked != nullptr)
602 *pClicked = true;
603 SetActiveItem(nullptr);
604 m_ActiveDraggableButtonLogicButton = -1;
605 }
606 }
607 else if(HotItem() == pId)
608 {
609 for(int i = 0; i < 3; ++i)
610 {
611 if(MouseButton(Index: i))
612 {
613 SetActiveItem(pId);
614 m_ActiveDraggableButtonLogicButton = i;
615 }
616 }
617 }
618
619 if(Inside && !MouseButton(Index: 0) && !MouseButton(Index: 1) && !MouseButton(Index: 2))
620 SetHotItem(pId);
621
622 return ReturnValue;
623}
624
625bool CUi::DoDoubleClickLogic(const void *pId)
626{
627 if(m_DoubleClickState.m_pLastClickedId == pId &&
628 Client()->GlobalTime() - m_DoubleClickState.m_LastClickTime < 0.5f &&
629 distance(a: m_DoubleClickState.m_LastClickPos, b: MousePos()) <= 32.0f * Screen()->h / Graphics()->ScreenHeight())
630 {
631 m_DoubleClickState.m_pLastClickedId = nullptr;
632 return true;
633 }
634 m_DoubleClickState.m_pLastClickedId = pId;
635 m_DoubleClickState.m_LastClickTime = Client()->GlobalTime();
636 m_DoubleClickState.m_LastClickPos = MousePos();
637 return false;
638}
639
640EEditState CUi::DoPickerLogic(const void *pId, const CUIRect *pRect, float *pX, float *pY)
641{
642 if(MouseHovered(pRect))
643 SetHotItem(pId);
644
645 EEditState Res = EEditState::EDITING;
646
647 if(HotItem() == pId && MouseButtonClicked(Index: 0))
648 {
649 SetActiveItem(pId);
650 if(!m_pLastEditingItem)
651 {
652 m_pLastEditingItem = pId;
653 Res = EEditState::START;
654 }
655 }
656
657 if(CheckActiveItem(pId) && !MouseButton(Index: 0))
658 {
659 SetActiveItem(nullptr);
660 if(m_pLastEditingItem == pId)
661 {
662 m_pLastEditingItem = nullptr;
663 Res = EEditState::END;
664 }
665 }
666
667 if(!CheckActiveItem(pId) && Res == EEditState::EDITING)
668 return EEditState::NONE;
669
670 if(Input()->ShiftIsPressed())
671 m_MouseSlow = true;
672
673 if(pX)
674 *pX = std::clamp(val: MouseX() - pRect->x, lo: 0.0f, hi: pRect->w);
675 if(pY)
676 *pY = std::clamp(val: MouseY() - pRect->y, lo: 0.0f, hi: pRect->h);
677
678 return Res;
679}
680
681void CUi::DoSmoothScrollLogic(float *pScrollOffset, float *pScrollOffsetChange, float ViewPortSize, float TotalSize, bool SmoothClamp, float ScrollSpeed) const
682{
683 // reset scrolling if it's not necessary anymore
684 if(TotalSize < ViewPortSize)
685 {
686 *pScrollOffsetChange = -*pScrollOffset;
687 }
688
689 // instant scrolling if distance too long
690 if(absolute(a: *pScrollOffsetChange) > 2.0f * ViewPortSize)
691 {
692 *pScrollOffset += *pScrollOffsetChange;
693 *pScrollOffsetChange = 0.0f;
694 }
695
696 // smooth scrolling
697 if(*pScrollOffsetChange)
698 {
699 const float Delta = *pScrollOffsetChange * std::clamp(val: Client()->RenderFrameTime() * ScrollSpeed, lo: 0.0f, hi: 1.0f);
700 *pScrollOffset += Delta;
701 *pScrollOffsetChange -= Delta;
702 }
703
704 // clamp to first item
705 if(*pScrollOffset < 0.0f)
706 {
707 if(SmoothClamp && *pScrollOffset < -0.1f)
708 {
709 *pScrollOffsetChange = -*pScrollOffset;
710 }
711 else
712 {
713 *pScrollOffset = 0.0f;
714 *pScrollOffsetChange = 0.0f;
715 }
716 }
717
718 // clamp to last item
719 if(TotalSize > ViewPortSize && *pScrollOffset > TotalSize - ViewPortSize)
720 {
721 if(SmoothClamp && *pScrollOffset - (TotalSize - ViewPortSize) > 0.1f)
722 {
723 *pScrollOffsetChange = (TotalSize - ViewPortSize) - *pScrollOffset;
724 }
725 else
726 {
727 *pScrollOffset = TotalSize - ViewPortSize;
728 *pScrollOffsetChange = 0.0f;
729 }
730 }
731}
732
733struct SCursorAndBoundingBox
734{
735 vec2 m_TextSize;
736 float m_BiggestCharacterHeight;
737 int m_LineCount;
738};
739
740static SCursorAndBoundingBox CalcFontSizeCursorHeightAndBoundingBox(ITextRender *pTextRender, const char *pText, int Flags, float &Size, float MaxWidth, const SLabelProperties &LabelProps)
741{
742 const float MaxTextWidth = LabelProps.m_MaxWidth != -1.0f ? LabelProps.m_MaxWidth : MaxWidth;
743 const int FlagsWithoutStop = Flags & ~(TEXTFLAG_STOP_AT_END | TEXTFLAG_ELLIPSIS_AT_END);
744 const float MaxTextWidthWithoutStop = Flags == FlagsWithoutStop ? LabelProps.m_MaxWidth : -1.0f;
745
746 float TextBoundingHeight = 0.0f;
747 float TextHeight = 0.0f;
748 int LineCount = 0;
749 STextSizeProperties TextSizeProps{};
750 TextSizeProps.m_pHeight = &TextHeight;
751 TextSizeProps.m_pMaxCharacterHeightInLine = &TextBoundingHeight;
752 TextSizeProps.m_pLineCount = &LineCount;
753
754 float TextWidth;
755 do
756 {
757 Size = std::max(a: Size, b: LabelProps.m_MinimumFontSize);
758 // Only consider stop-at-end and ellipsis-at-end when minimum font size reached or font scaling disabled
759 if((Size == LabelProps.m_MinimumFontSize || !LabelProps.m_EnableWidthCheck) && Flags != FlagsWithoutStop)
760 TextWidth = pTextRender->TextWidth(Size, pText, StrLength: -1, LineWidth: LabelProps.m_MaxWidth, Flags, TextSizeProps);
761 else
762 TextWidth = pTextRender->TextWidth(Size, pText, StrLength: -1, LineWidth: MaxTextWidthWithoutStop, Flags: FlagsWithoutStop, TextSizeProps);
763 if(TextWidth <= MaxTextWidth + 0.001f || !LabelProps.m_EnableWidthCheck || Size == LabelProps.m_MinimumFontSize)
764 break;
765 Size--;
766 } while(true);
767
768 SCursorAndBoundingBox Res{};
769 Res.m_TextSize = vec2(TextWidth, TextHeight);
770 Res.m_BiggestCharacterHeight = TextBoundingHeight;
771 Res.m_LineCount = LineCount;
772 return Res;
773}
774
775static int GetFlagsForLabelProperties(const SLabelProperties &LabelProps, const CTextCursor *pReadCursor)
776{
777 if(pReadCursor != nullptr)
778 return pReadCursor->m_Flags & ~TEXTFLAG_RENDER;
779
780 int Flags = 0;
781 Flags |= LabelProps.m_StopAtEnd ? TEXTFLAG_STOP_AT_END : 0;
782 Flags |= LabelProps.m_EllipsisAtEnd ? TEXTFLAG_ELLIPSIS_AT_END : 0;
783 return Flags;
784}
785
786vec2 CUi::CalcAlignedCursorPos(const CUIRect *pRect, vec2 TextSize, int Align, const float *pBiggestCharHeight)
787{
788 vec2 Cursor(pRect->x, pRect->y);
789
790 const int HorizontalAlign = Align & TEXTALIGN_MASK_HORIZONTAL;
791 if(HorizontalAlign == TEXTALIGN_CENTER)
792 {
793 Cursor.x += (pRect->w - TextSize.x) / 2.0f;
794 }
795 else if(HorizontalAlign == TEXTALIGN_RIGHT)
796 {
797 Cursor.x += pRect->w - TextSize.x;
798 }
799
800 const int VerticalAlign = Align & TEXTALIGN_MASK_VERTICAL;
801 if(VerticalAlign == TEXTALIGN_MIDDLE)
802 {
803 Cursor.y += pBiggestCharHeight != nullptr ? ((pRect->h - *pBiggestCharHeight) / 2.0f - (TextSize.y - *pBiggestCharHeight)) : (pRect->h - TextSize.y) / 2.0f;
804 }
805 else if(VerticalAlign == TEXTALIGN_BOTTOM)
806 {
807 Cursor.y += pRect->h - TextSize.y;
808 }
809
810 return Cursor;
811}
812
813CLabelResult CUi::DoLabel(const CUIRect *pRect, const char *pText, float Size, int Align, const SLabelProperties &LabelProps) const
814{
815 const int Flags = GetFlagsForLabelProperties(LabelProps, pReadCursor: nullptr);
816 const SCursorAndBoundingBox TextBounds = CalcFontSizeCursorHeightAndBoundingBox(pTextRender: TextRender(), pText, Flags, Size, MaxWidth: pRect->w, LabelProps);
817 const vec2 CursorPos = CalcAlignedCursorPos(pRect, TextSize: TextBounds.m_TextSize, Align, pBiggestCharHeight: TextBounds.m_LineCount == 1 ? &TextBounds.m_BiggestCharacterHeight : nullptr);
818
819 CTextCursor Cursor;
820 Cursor.SetPosition(CursorPos);
821 Cursor.m_FontSize = Size;
822 Cursor.m_Flags |= Flags;
823 Cursor.m_vColorSplits = LabelProps.m_vColorSplits;
824 Cursor.m_LineWidth = (float)LabelProps.m_MaxWidth;
825 TextRender()->TextEx(pCursor: &Cursor, pText, Length: -1);
826 if(Cursor.m_Truncated && LabelProps.m_pTooltipId)
827 {
828 DoToolTip(Tooltip: {LabelProps.m_pTooltipId,
829 *pRect,
830 pText,
831 -1,
832 Size,
833 true});
834 }
835 return CLabelResult{.m_Truncated = Cursor.m_Truncated};
836}
837
838void CUi::DoLabel(CUIElement::SUIElementRect &RectEl, const CUIRect *pRect, const char *pText, float Size, int Align, const SLabelProperties &LabelProps, int StrLen, const CTextCursor *pReadCursor) const
839{
840 const int Flags = GetFlagsForLabelProperties(LabelProps, pReadCursor);
841 const SCursorAndBoundingBox TextBounds = CalcFontSizeCursorHeightAndBoundingBox(pTextRender: TextRender(), pText, Flags, Size, MaxWidth: pRect->w, LabelProps);
842
843 CTextCursor Cursor;
844 if(pReadCursor)
845 {
846 Cursor = *pReadCursor;
847 }
848 else
849 {
850 Cursor.SetPosition(CalcAlignedCursorPos(pRect, TextSize: TextBounds.m_TextSize, Align));
851 Cursor.m_FontSize = Size;
852 Cursor.m_Flags |= Flags;
853 }
854 Cursor.m_LineWidth = LabelProps.m_MaxWidth;
855
856 RectEl.m_TextColor = TextRender()->GetTextColor();
857 RectEl.m_TextOutlineColor = TextRender()->GetTextOutlineColor();
858 TextRender()->TextColor(Color: TextRender()->DefaultTextColor());
859 TextRender()->TextOutlineColor(Color: TextRender()->DefaultTextOutlineColor());
860 TextRender()->CreateTextContainer(TextContainerIndex&: RectEl.m_UITextContainer, pCursor: &Cursor, pText, Length: StrLen);
861 TextRender()->TextColor(Color: RectEl.m_TextColor);
862 TextRender()->TextOutlineColor(Color: RectEl.m_TextOutlineColor);
863 RectEl.m_Cursor = std::move(Cursor);
864}
865
866void CUi::DoLabelStreamed(CUIElement::SUIElementRect &RectEl, const CUIRect *pRect, const char *pText, float Size, int Align, const SLabelProperties &LabelProps, int StrLen, const CTextCursor *pReadCursor) const
867{
868 const int ReadCursorGlyphCount = pReadCursor == nullptr ? -1 : pReadCursor->m_GlyphCount;
869 bool NeedsRecreate = false;
870 bool ColorChanged = RectEl.m_TextColor != TextRender()->GetTextColor() || RectEl.m_TextOutlineColor != TextRender()->GetTextOutlineColor();
871 if((!RectEl.m_UITextContainer.Valid() && pText[0] != '\0' && StrLen != 0) || RectEl.m_Width != pRect->w || RectEl.m_Height != pRect->h || ColorChanged || RectEl.m_ReadCursorGlyphCount != ReadCursorGlyphCount)
872 {
873 NeedsRecreate = true;
874 }
875 else
876 {
877 if(StrLen <= -1)
878 {
879 if(str_comp(a: RectEl.m_Text.c_str(), b: pText) != 0)
880 NeedsRecreate = true;
881 }
882 else
883 {
884 if(StrLen != (int)RectEl.m_Text.size() || str_comp_num(a: RectEl.m_Text.c_str(), b: pText, num: StrLen) != 0)
885 NeedsRecreate = true;
886 }
887 }
888 RectEl.m_X = pRect->x;
889 RectEl.m_Y = pRect->y;
890 if(NeedsRecreate)
891 {
892 TextRender()->DeleteTextContainer(TextContainerIndex&: RectEl.m_UITextContainer);
893
894 RectEl.m_Width = pRect->w;
895 RectEl.m_Height = pRect->h;
896
897 if(StrLen > 0)
898 RectEl.m_Text = std::string(pText, StrLen);
899 else if(StrLen < 0)
900 RectEl.m_Text = pText;
901 else
902 RectEl.m_Text.clear();
903
904 RectEl.m_ReadCursorGlyphCount = ReadCursorGlyphCount;
905
906 CUIRect TmpRect;
907 TmpRect.x = 0;
908 TmpRect.y = 0;
909 TmpRect.w = pRect->w;
910 TmpRect.h = pRect->h;
911
912 DoLabel(RectEl, pRect: &TmpRect, pText, Size, Align: TEXTALIGN_TL, LabelProps, StrLen, pReadCursor);
913 }
914
915 if(RectEl.m_UITextContainer.Valid())
916 {
917 const vec2 CursorPos = CalcAlignedCursorPos(pRect, TextSize: vec2(RectEl.m_Cursor.m_LongestLineWidth, RectEl.m_Cursor.Height()), Align);
918 TextRender()->RenderTextContainer(TextContainerIndex: RectEl.m_UITextContainer, TextColor: RectEl.m_TextColor, TextOutlineColor: RectEl.m_TextOutlineColor, X: CursorPos.x, Y: CursorPos.y);
919
920 if(RectEl.m_Cursor.m_Truncated && LabelProps.m_pTooltipId)
921 {
922 DoToolTip(Tooltip: {LabelProps.m_pTooltipId,
923 *pRect,
924 pText,
925 -1,
926 Size,
927 true});
928 }
929 }
930}
931
932CLabelResult CUi::DoLabel_AutoLineSize(const char *pText, float FontSize, int Align, CUIRect *pRect, float LineSize, const SLabelProperties &LabelProps) const
933{
934 CUIRect LabelRect;
935 pRect->HSplitTop(Cut: LineSize, pTop: &LabelRect, pBottom: pRect);
936
937 return DoLabel(pRect: &LabelRect, pText, Size: FontSize, Align);
938}
939
940bool CUi::DoEditBox(CLineInput *pLineInput, const CUIRect *pRect, float FontSize, int Corners, const std::vector<STextColorSplit> &vColorSplits)
941{
942 const bool Inside = MouseHovered(pRect);
943 const bool Active = m_pLastActiveItem == pLineInput;
944 const bool Changed = pLineInput->WasChanged();
945 const bool CursorChanged = pLineInput->WasCursorChanged();
946
947 const float VSpacing = 2.0f;
948 CUIRect Textbox;
949 pRect->VMargin(Cut: VSpacing, pOtherRect: &Textbox);
950
951 bool JustGotActive = false;
952 if(CheckActiveItem(pId: pLineInput))
953 {
954 if(MouseButton(Index: 0))
955 {
956 if(pLineInput->IsActive() && (Input()->HasComposition() || Input()->GetCandidateCount()))
957 {
958 // Clear IME composition/candidates on mouse press
959 Input()->StopTextInput();
960 Input()->StartTextInput();
961 }
962 }
963 else
964 {
965 SetActiveItem(nullptr);
966 }
967 }
968 else if(HotItem() == pLineInput)
969 {
970 if(MouseButton(Index: 0))
971 {
972 if(!Active)
973 JustGotActive = true;
974 SetActiveItem(pLineInput);
975 }
976 }
977
978 if(Inside && !MouseButton(Index: 0))
979 SetHotItem(pLineInput);
980
981 if(Enabled() && Active && !JustGotActive)
982 pLineInput->Activate(Priority: EInputPriority::UI);
983 else
984 pLineInput->Deactivate();
985
986 float ScrollOffset = pLineInput->GetScrollOffset();
987 float ScrollOffsetChange = pLineInput->GetScrollOffsetChange();
988
989 // Update mouse selection information
990 CLineInput::SMouseSelection *pMouseSelection = pLineInput->GetMouseSelection();
991 if(Inside)
992 {
993 if(!pMouseSelection->m_Selecting && MouseButtonClicked(Index: 0))
994 {
995 pMouseSelection->m_Selecting = true;
996 pMouseSelection->m_PressMouse = MousePos();
997 pMouseSelection->m_Offset.x = ScrollOffset;
998 }
999 }
1000 if(pMouseSelection->m_Selecting)
1001 {
1002 pMouseSelection->m_ReleaseMouse = MousePos();
1003 if(!MouseButton(Index: 0))
1004 {
1005 pMouseSelection->m_Selecting = false;
1006 if(Active)
1007 {
1008 Input()->EnsureScreenKeyboardShown();
1009 }
1010 }
1011 }
1012 if(ScrollOffset != pMouseSelection->m_Offset.x)
1013 {
1014 // When the scroll offset is changed, update the position that the mouse was pressed at,
1015 // so the existing text selection still stays mostly the same.
1016 // TODO: The selection may change by one character temporarily, due to different character widths.
1017 // Needs text render adjustment: keep selection start based on character.
1018 pMouseSelection->m_PressMouse.x -= ScrollOffset - pMouseSelection->m_Offset.x;
1019 pMouseSelection->m_Offset.x = ScrollOffset;
1020 }
1021
1022 // Render
1023 pRect->Draw(Color: ms_LightButtonColorFunction.GetColor(Active, Hovered: HotItem() == pLineInput), Corners, Rounding: 3.0f);
1024 ClipEnable(pRect);
1025 Textbox.x -= ScrollOffset;
1026 const STextBoundingBox BoundingBox = pLineInput->Render(pRect: &Textbox, FontSize, Align: TEXTALIGN_ML, Changed: Changed || CursorChanged, LineWidth: -1.0f, LineSpacing: 0.0f, vColorSplits);
1027 ClipDisable();
1028
1029 // Scroll left or right if necessary
1030 if(Active && !JustGotActive && (Changed || CursorChanged || Input()->HasComposition()))
1031 {
1032 const float CaretPositionX = pLineInput->GetCaretPosition().x - Textbox.x - ScrollOffset - ScrollOffsetChange;
1033 if(CaretPositionX > Textbox.w)
1034 ScrollOffsetChange += CaretPositionX - Textbox.w;
1035 else if(CaretPositionX < 0.0f)
1036 ScrollOffsetChange += CaretPositionX;
1037 }
1038
1039 DoSmoothScrollLogic(pScrollOffset: &ScrollOffset, pScrollOffsetChange: &ScrollOffsetChange, ViewPortSize: Textbox.w, TotalSize: BoundingBox.m_W, SmoothClamp: true);
1040
1041 pLineInput->SetScrollOffset(ScrollOffset);
1042 pLineInput->SetScrollOffsetChange(ScrollOffsetChange);
1043
1044 return Changed;
1045}
1046
1047bool CUi::DoClearableEditBox(CLineInput *pLineInput, const CUIRect *pRect, float FontSize, int Corners, const std::vector<STextColorSplit> &vColorSplits)
1048{
1049 CUIRect EditBox, ClearButton;
1050 pRect->VSplitRight(Cut: pRect->h, pLeft: &EditBox, pRight: &ClearButton);
1051
1052 bool ReturnValue = DoEditBox(pLineInput, pRect: &EditBox, FontSize, Corners: Corners & ~IGraphics::CORNER_R, vColorSplits);
1053
1054 ClearButton.Draw(Color: ColorRGBA(1.0f, 1.0f, 1.0f, 0.33f * ButtonColorMul(pId: pLineInput->GetClearButtonId())), Corners: Corners & ~IGraphics::CORNER_L, Rounding: 3.0f);
1055 TextRender()->SetRenderFlags(ETextRenderFlags::TEXT_RENDER_FLAG_ONLY_ADVANCE_WIDTH | ETextRenderFlags::TEXT_RENDER_FLAG_NO_X_BEARING | ETextRenderFlags::TEXT_RENDER_FLAG_NO_Y_BEARING | ETextRenderFlags::TEXT_RENDER_FLAG_NO_OVERSIZE);
1056 DoLabel(pRect: &ClearButton, pText: "×", Size: ClearButton.h * CUi::ms_FontmodHeight * 0.8f, Align: TEXTALIGN_MC);
1057 TextRender()->SetRenderFlags(0);
1058 if(DoButtonLogic(pId: pLineInput->GetClearButtonId(), Checked: 0, pRect: &ClearButton, Flags: BUTTONFLAG_LEFT))
1059 {
1060 pLineInput->Clear();
1061 SetActiveItem(pLineInput);
1062 ReturnValue = true;
1063 }
1064
1065 return ReturnValue;
1066}
1067
1068bool CUi::DoEditBox_Search(CLineInput *pLineInput, const CUIRect *pRect, float FontSize, bool HotkeyEnabled)
1069{
1070 CUIRect QuickSearch = *pRect;
1071 TextRender()->SetFontPreset(EFontPreset::ICON_FONT);
1072 TextRender()->SetRenderFlags(ETextRenderFlags::TEXT_RENDER_FLAG_ONLY_ADVANCE_WIDTH | ETextRenderFlags::TEXT_RENDER_FLAG_NO_X_BEARING | ETextRenderFlags::TEXT_RENDER_FLAG_NO_Y_BEARING | ETextRenderFlags::TEXT_RENDER_FLAG_NO_PIXEL_ALIGNMENT | ETextRenderFlags::TEXT_RENDER_FLAG_NO_OVERSIZE);
1073 DoLabel(pRect: &QuickSearch, pText: FontIcon::MAGNIFYING_GLASS, Size: FontSize, Align: TEXTALIGN_ML);
1074 const float SearchWidth = TextRender()->TextWidth(Size: FontSize, pText: FontIcon::MAGNIFYING_GLASS);
1075 TextRender()->SetRenderFlags(0);
1076 TextRender()->SetFontPreset(EFontPreset::DEFAULT_FONT);
1077 QuickSearch.VSplitLeft(Cut: SearchWidth + 5.0f, pLeft: nullptr, pRight: &QuickSearch);
1078 if(HotkeyEnabled && Input()->ModifierIsPressed() && Input()->KeyPress(Key: KEY_F))
1079 {
1080 SetActiveItem(pLineInput);
1081 pLineInput->SelectAll();
1082 }
1083 pLineInput->SetEmptyText(Localize(pStr: "Search"));
1084 return DoClearableEditBox(pLineInput, pRect: &QuickSearch, FontSize);
1085}
1086
1087int CUi::DoButton_Menu(CUIElement &UIElement, const CButtonContainer *pId, const std::function<const char *()> &GetTextLambda, const CUIRect *pRect, const SMenuButtonProperties &Props)
1088{
1089 CUIRect Text = *pRect, DropDownIcon;
1090 Text.HMargin(Cut: pRect->h >= 20.0f ? 2.0f : 1.0f, pOtherRect: &Text);
1091 Text.HMargin(Cut: (Text.h * Props.m_FontFactor) / 2.0f, pOtherRect: &Text);
1092 if(Props.m_ShowDropDownIcon)
1093 {
1094 Text.VSplitRight(Cut: pRect->h * 0.25f, pLeft: &Text, pRight: nullptr);
1095 Text.VSplitRight(Cut: pRect->h * 0.75f, pLeft: &Text, pRight: &DropDownIcon);
1096 }
1097
1098 if(!UIElement.AreRectsInit() || Props.m_HintRequiresStringCheck || Props.m_HintCanChangePositionOrSize || !UIElement.Rect(Index: 0)->m_UITextContainer.Valid())
1099 {
1100 bool NeedsRecalc = !UIElement.AreRectsInit() || !UIElement.Rect(Index: 0)->m_UITextContainer.Valid();
1101 if(Props.m_HintCanChangePositionOrSize)
1102 {
1103 if(UIElement.AreRectsInit())
1104 {
1105 if(UIElement.Rect(Index: 0)->m_X != pRect->x || UIElement.Rect(Index: 0)->m_Y != pRect->y || UIElement.Rect(Index: 0)->m_Width != pRect->w || UIElement.Rect(Index: 0)->m_Height != pRect->h || UIElement.Rect(Index: 0)->m_Rounding != Props.m_Rounding || UIElement.Rect(Index: 0)->m_Corners != Props.m_Corners)
1106 {
1107 NeedsRecalc = true;
1108 }
1109 }
1110 }
1111 const char *pText = nullptr;
1112 if(Props.m_HintRequiresStringCheck)
1113 {
1114 if(UIElement.AreRectsInit())
1115 {
1116 pText = GetTextLambda();
1117 if(str_comp(a: UIElement.Rect(Index: 0)->m_Text.c_str(), b: pText) != 0)
1118 {
1119 NeedsRecalc = true;
1120 }
1121 }
1122 }
1123 if(NeedsRecalc)
1124 {
1125 if(!UIElement.AreRectsInit())
1126 {
1127 UIElement.InitRects(RequestedRectCount: 3);
1128 }
1129 ResetUIElement(UIElement);
1130
1131 for(int i = 0; i < 3; ++i)
1132 {
1133 ColorRGBA Color = Props.m_Color;
1134 if(i == 0)
1135 Color.a *= ButtonColorMulActive();
1136 else if(i == 1)
1137 Color.a *= ButtonColorMulHot();
1138 else if(i == 2)
1139 Color.a *= ButtonColorMulDefault();
1140 Graphics()->SetColor(Color);
1141
1142 CUIElement::SUIElementRect &NewRect = *UIElement.Rect(Index: i);
1143 NewRect.m_UIRectQuadContainer = Graphics()->CreateRectQuadContainer(x: pRect->x, y: pRect->y, w: pRect->w, h: pRect->h, r: Props.m_Rounding, Corners: Props.m_Corners);
1144
1145 NewRect.m_X = pRect->x;
1146 NewRect.m_Y = pRect->y;
1147 NewRect.m_Width = pRect->w;
1148 NewRect.m_Height = pRect->h;
1149 NewRect.m_Rounding = Props.m_Rounding;
1150 NewRect.m_Corners = Props.m_Corners;
1151 if(i == 0)
1152 {
1153 if(pText == nullptr)
1154 pText = GetTextLambda();
1155 NewRect.m_Text = pText;
1156 if(Props.m_UseIconFont)
1157 TextRender()->SetFontPreset(EFontPreset::ICON_FONT);
1158 DoLabel(RectEl&: NewRect, pRect: &Text, pText, Size: Text.h * CUi::ms_FontmodHeight, Align: TEXTALIGN_MC);
1159 if(Props.m_UseIconFont)
1160 TextRender()->SetFontPreset(EFontPreset::DEFAULT_FONT);
1161 }
1162 }
1163 Graphics()->SetColor(r: 1.0f, g: 1.0f, b: 1.0f, a: 1.0f);
1164 }
1165 }
1166 // render
1167 size_t Index = 2;
1168 if(CheckActiveItem(pId))
1169 Index = 0;
1170 else if(HotItem() == pId)
1171 Index = 1;
1172 Graphics()->TextureClear();
1173 Graphics()->RenderQuadContainer(ContainerIndex: UIElement.Rect(Index)->m_UIRectQuadContainer, QuadDrawNum: -1);
1174 if(Props.m_ShowDropDownIcon)
1175 {
1176 TextRender()->SetFontPreset(EFontPreset::ICON_FONT);
1177 TextRender()->SetRenderFlags(ETextRenderFlags::TEXT_RENDER_FLAG_ONLY_ADVANCE_WIDTH | ETextRenderFlags::TEXT_RENDER_FLAG_NO_X_BEARING | ETextRenderFlags::TEXT_RENDER_FLAG_NO_Y_BEARING | ETextRenderFlags::TEXT_RENDER_FLAG_NO_PIXEL_ALIGNMENT | ETextRenderFlags::TEXT_RENDER_FLAG_NO_OVERSIZE);
1178 DoLabel(pRect: &DropDownIcon, pText: FontIcon::CIRCLE_CHEVRON_DOWN, Size: DropDownIcon.h * CUi::ms_FontmodHeight, Align: TEXTALIGN_MR);
1179 TextRender()->SetRenderFlags(0);
1180 TextRender()->SetFontPreset(EFontPreset::DEFAULT_FONT);
1181 }
1182 ColorRGBA ColorText(TextRender()->DefaultTextColor());
1183 ColorRGBA ColorTextOutline(TextRender()->DefaultTextOutlineColor());
1184 if(UIElement.Rect(Index: 0)->m_UITextContainer.Valid())
1185 TextRender()->RenderTextContainer(TextContainerIndex: UIElement.Rect(Index: 0)->m_UITextContainer, TextColor: ColorText, TextOutlineColor: ColorTextOutline);
1186 return DoButtonLogic(pId, Checked: Props.m_Checked, pRect, Flags: Props.m_Flags);
1187}
1188
1189void CUi::DrawButton_FontIcon(const char *pText, const CUIRect *pRect, ColorRGBA Color, int Corners, bool Enabled) const
1190{
1191 pRect->Draw(Color, Corners, Rounding: 5.0f);
1192
1193 TextRender()->SetFontPreset(EFontPreset::ICON_FONT);
1194 TextRender()->SetRenderFlags(ETextRenderFlags::TEXT_RENDER_FLAG_ONLY_ADVANCE_WIDTH | ETextRenderFlags::TEXT_RENDER_FLAG_NO_X_BEARING | ETextRenderFlags::TEXT_RENDER_FLAG_NO_Y_BEARING);
1195 TextRender()->TextOutlineColor(Color: TextRender()->DefaultTextOutlineColor());
1196 TextRender()->TextColor(Color: TextRender()->DefaultTextColor());
1197
1198 CUIRect Label;
1199 pRect->HMargin(Cut: 2.0f, pOtherRect: &Label);
1200 DoLabel(pRect: &Label, pText, Size: Label.h * ms_FontmodHeight, Align: TEXTALIGN_MC);
1201
1202 if(!Enabled)
1203 {
1204 TextRender()->TextColor(Color: ColorRGBA(1.0f, 0.0f, 0.0f, 1.0f));
1205 TextRender()->TextOutlineColor(Color: ColorRGBA(0.0f, 0.0f, 0.0f, 0.0f));
1206 DoLabel(pRect: &Label, pText: FontIcon::SLASH, Size: Label.h * ms_FontmodHeight, Align: TEXTALIGN_MC);
1207 TextRender()->TextOutlineColor(Color: TextRender()->DefaultTextOutlineColor());
1208 TextRender()->TextColor(Color: TextRender()->DefaultTextColor());
1209 }
1210
1211 TextRender()->SetRenderFlags(0);
1212 TextRender()->SetFontPreset(EFontPreset::DEFAULT_FONT);
1213}
1214
1215int CUi::DoButton_FontIcon(CButtonContainer *pButtonContainer, const char *pText, int Checked, const CUIRect *pRect, const unsigned Flags, int Corners, bool Enabled, const std::optional<ColorRGBA> ButtonColor)
1216{
1217 DrawButton_FontIcon(pText, pRect, Color: ButtonColor.value_or(u: ColorRGBA(1.0f, 1.0f, 1.0f, (Checked ? 0.1f : 0.5f) * ButtonColorMul(pId: pButtonContainer))), Corners, Enabled);
1218 return DoButtonLogic(pId: pButtonContainer, Checked, pRect, Flags);
1219}
1220
1221int CUi::DoButton_PopupMenu(CButtonContainer *pButtonContainer, const char *pText, const CUIRect *pRect, float Size, int Align, float Padding, bool TransparentInactive, bool Enabled, const std::optional<ColorRGBA> ButtonColor)
1222{
1223 if(!TransparentInactive || CheckActiveItem(pId: pButtonContainer) || HotItem() == pButtonContainer)
1224 pRect->Draw(Color: ButtonColor.value_or(u: Enabled ? ColorRGBA(1.0f, 1.0f, 1.0f, 0.5f * ButtonColorMul(pId: pButtonContainer)) : ColorRGBA(0.0f, 0.0f, 0.0f, 0.4f)), Corners: IGraphics::CORNER_ALL, Rounding: 3.0f);
1225
1226 CUIRect Label;
1227 pRect->Margin(Cut: Padding, pOtherRect: &Label);
1228 DoLabel(pRect: &Label, pText, Size, Align);
1229
1230 return Enabled ? DoButtonLogic(pId: pButtonContainer, Checked: 0, pRect, Flags: BUTTONFLAG_LEFT) : 0;
1231}
1232
1233int64_t CUi::DoValueSelector(const void *pId, const CUIRect *pRect, const char *pLabel, int64_t Current, int64_t Min, int64_t Max, const SValueSelectorProperties &Props)
1234{
1235 return DoValueSelectorWithState(pId, pRect, pLabel, Current, Min, Max, Props).m_Value;
1236}
1237
1238SEditResult<int64_t> CUi::DoValueSelectorWithState(const void *pId, const CUIRect *pRect, const char *pLabel, int64_t Current, int64_t Min, int64_t Max, const SValueSelectorProperties &Props)
1239{
1240 // logic
1241 const bool Inside = MouseInside(pRect);
1242 const int Base = Props.m_IsHex ? 16 : 10;
1243
1244 if(HotItem() == pId && m_ActiveValueSelectorState.m_Button >= 0 && !MouseButton(Index: m_ActiveValueSelectorState.m_Button))
1245 {
1246 DisableMouseLock();
1247 if(CheckActiveItem(pId))
1248 {
1249 SetActiveItem(nullptr);
1250 }
1251 if(Inside && ((m_ActiveValueSelectorState.m_Button == 0 && !m_ActiveValueSelectorState.m_DidScroll && DoDoubleClickLogic(pId)) || m_ActiveValueSelectorState.m_Button == 1))
1252 {
1253 m_ActiveValueSelectorState.m_pLastTextId = pId;
1254 m_ActiveValueSelectorState.m_NumberInput.SetInteger64(Number: Current, Base, HexPrefix: Props.m_HexPrefix);
1255 m_ActiveValueSelectorState.m_NumberInput.SelectAll();
1256 }
1257 m_ActiveValueSelectorState.m_Button = -1;
1258 }
1259
1260 if(m_ActiveValueSelectorState.m_pLastTextId == pId)
1261 {
1262 SetActiveItem(&m_ActiveValueSelectorState.m_NumberInput);
1263 DoEditBox(pLineInput: &m_ActiveValueSelectorState.m_NumberInput, pRect, FontSize: 10.0f);
1264
1265 if(ConsumeHotkey(Hotkey: HOTKEY_ENTER) || ((MouseButtonClicked(Index: 1) || MouseButtonClicked(Index: 0)) && !Inside))
1266 {
1267 Current = std::clamp(val: m_ActiveValueSelectorState.m_NumberInput.GetInteger64(Base), lo: Min, hi: Max);
1268 DisableMouseLock();
1269 SetActiveItem(nullptr);
1270 m_ActiveValueSelectorState.m_pLastTextId = nullptr;
1271 }
1272
1273 if(ConsumeHotkey(Hotkey: HOTKEY_ESCAPE))
1274 {
1275 DisableMouseLock();
1276 SetActiveItem(nullptr);
1277 m_ActiveValueSelectorState.m_pLastTextId = nullptr;
1278 }
1279 }
1280 else
1281 {
1282 if(CheckActiveItem(pId))
1283 {
1284 dbg_assert(m_ActiveValueSelectorState.m_Button >= 0, "m_ActiveValueSelectorState.m_Button invalid");
1285 if(Props.m_UseScroll && m_ActiveValueSelectorState.m_Button == 0 && MouseButton(Index: 0))
1286 {
1287 m_ActiveValueSelectorState.m_ScrollValue += MouseDeltaX() * (Input()->ShiftIsPressed() ? 0.05f : 1.0f);
1288
1289 if(absolute(a: m_ActiveValueSelectorState.m_ScrollValue) > Props.m_Scale)
1290 {
1291 const int64_t Count = (int64_t)(m_ActiveValueSelectorState.m_ScrollValue / Props.m_Scale);
1292 m_ActiveValueSelectorState.m_ScrollValue = std::fmod(x: m_ActiveValueSelectorState.m_ScrollValue, y: Props.m_Scale);
1293 Current += Props.m_Step * Count;
1294 Current = std::clamp(val: Current, lo: Min, hi: Max);
1295 m_ActiveValueSelectorState.m_DidScroll = true;
1296
1297 // Constrain to discrete steps
1298 if(Count > 0)
1299 Current = Current / Props.m_Step * Props.m_Step;
1300 else
1301 Current = std::ceil(x: Current / (float)Props.m_Step) * Props.m_Step;
1302 }
1303 }
1304 }
1305 else if(HotItem() == pId)
1306 {
1307 if(MouseButton(Index: 0))
1308 {
1309 m_ActiveValueSelectorState.m_Button = 0;
1310 m_ActiveValueSelectorState.m_DidScroll = false;
1311 m_ActiveValueSelectorState.m_ScrollValue = 0.0f;
1312 SetActiveItem(pId);
1313 if(Props.m_UseScroll)
1314 EnableMouseLock(pId);
1315 }
1316 else if(MouseButton(Index: 1))
1317 {
1318 m_ActiveValueSelectorState.m_Button = 1;
1319 SetActiveItem(pId);
1320 }
1321 }
1322
1323 // render
1324 char aBuf[128];
1325 if(pLabel[0] != '\0')
1326 {
1327 if(Props.m_IsHex)
1328 str_format(aBuf, sizeof(aBuf), "%s #%0*" PRIX64, pLabel, Props.m_HexPrefix, Current);
1329 else
1330 str_format(aBuf, sizeof(aBuf), "%s %" PRId64, pLabel, Current);
1331 }
1332 else
1333 {
1334 if(Props.m_IsHex)
1335 str_format(aBuf, sizeof(aBuf), "#%0*" PRIX64, Props.m_HexPrefix, Current);
1336 else
1337 str_format(aBuf, sizeof(aBuf), "%" PRId64, Current);
1338 }
1339 pRect->Draw(Color: Props.m_Color, Corners: IGraphics::CORNER_ALL, Rounding: 3.0f);
1340 DoLabel(pRect, pText: aBuf, Size: 10.0f, Align: TEXTALIGN_MC);
1341 }
1342
1343 if(Inside && !MouseButton(Index: 0) && !MouseButton(Index: 1))
1344 SetHotItem(pId);
1345
1346 EEditState State = EEditState::NONE;
1347 if(m_pLastEditingItem == pId)
1348 {
1349 State = EEditState::EDITING;
1350 }
1351 if(((CheckActiveItem(pId) && CheckMouseLock()) || m_ActiveValueSelectorState.m_pLastTextId == pId) && m_pLastEditingItem != pId)
1352 {
1353 State = EEditState::START;
1354 m_pLastEditingItem = pId;
1355 }
1356 if(!CheckMouseLock() && m_ActiveValueSelectorState.m_pLastTextId != pId && m_pLastEditingItem == pId)
1357 {
1358 State = EEditState::END;
1359 m_pLastEditingItem = nullptr;
1360 }
1361
1362 return SEditResult<int64_t>{.m_State: State, .m_Value: Current};
1363}
1364
1365float CUi::DoScrollbarV(const void *pId, const CUIRect *pRect, float Current)
1366{
1367 Current = std::clamp(val: Current, lo: 0.0f, hi: 1.0f);
1368
1369 // layout
1370 CUIRect Rail;
1371 pRect->Margin(Cut: 5.0f, pOtherRect: &Rail);
1372
1373 CUIRect Handle;
1374 Rail.HSplitTop(Cut: std::clamp(val: 33.0f, lo: Rail.w, hi: Rail.h / 3.0f), pTop: &Handle, pBottom: nullptr);
1375 Handle.y = Rail.y + (Rail.h - Handle.h) * Current;
1376
1377 // logic
1378 const bool InsideRail = MouseHovered(pRect: &Rail);
1379 const bool InsideHandle = MouseHovered(pRect: &Handle);
1380 bool Grabbed = false; // whether to apply the offset
1381
1382 if(CheckActiveItem(pId))
1383 {
1384 if(MouseButton(Index: 0))
1385 {
1386 Grabbed = true;
1387 if(Input()->ShiftIsPressed())
1388 m_MouseSlow = true;
1389 }
1390 else
1391 {
1392 SetActiveItem(nullptr);
1393 }
1394 }
1395 else if(HotItem() == pId)
1396 {
1397 if(InsideHandle)
1398 {
1399 if(MouseButton(Index: 0))
1400 {
1401 SetActiveItem(pId);
1402 m_ActiveScrollbarOffset = MouseY() - Handle.y;
1403 Grabbed = true;
1404 }
1405 }
1406 else if(MouseButtonClicked(Index: 0))
1407 {
1408 SetActiveItem(pId);
1409 m_ActiveScrollbarOffset = Handle.h / 2.0f;
1410 Grabbed = true;
1411 }
1412 }
1413
1414 if(InsideRail && !MouseButton(Index: 0))
1415 {
1416 SetHotItem(pId);
1417 }
1418
1419 float ReturnValue = Current;
1420 if(Grabbed)
1421 {
1422 const float Min = Rail.y;
1423 const float Max = Rail.h - Handle.h;
1424 const float Cur = MouseY() - m_ActiveScrollbarOffset;
1425 ReturnValue = std::clamp(val: (Cur - Min) / Max, lo: 0.0f, hi: 1.0f);
1426
1427 DoToolTip(Tooltip: {
1428 pId,
1429 Handle,
1430 Localize(pStr: "Hold Shift to be more precise."),
1431 -1.0f,
1432 TOOLTIP_FONTSIZE,
1433 false,
1434 });
1435 }
1436
1437 // render
1438 Rail.Draw(Color: ColorRGBA(1.0f, 1.0f, 1.0f, 0.25f), Corners: IGraphics::CORNER_ALL, Rounding: Rail.w / 2.0f);
1439 Handle.Draw(Color: ms_ScrollBarColorFunction.GetColor(Active: CheckActiveItem(pId), Hovered: HotItem() == pId), Corners: IGraphics::CORNER_ALL, Rounding: Handle.w / 2.0f);
1440
1441 return ReturnValue;
1442}
1443
1444float CUi::DoScrollbarH(const void *pId, const CUIRect *pRect, float Current, const ColorRGBA *pColorInner)
1445{
1446 Current = std::clamp(val: Current, lo: 0.0f, hi: 1.0f);
1447
1448 // layout
1449 CUIRect Rail;
1450 if(pColorInner)
1451 Rail = *pRect;
1452 else
1453 pRect->HMargin(Cut: 5.0f, pOtherRect: &Rail);
1454
1455 CUIRect Handle;
1456 Rail.VSplitLeft(Cut: pColorInner ? 8.0f : std::clamp(val: 33.0f, lo: Rail.h, hi: Rail.w / 3.0f), pLeft: &Handle, pRight: nullptr);
1457 Handle.x += (Rail.w - Handle.w) * Current;
1458
1459 CUIRect HandleArea = Handle;
1460 if(!pColorInner)
1461 {
1462 HandleArea.h = pRect->h * 0.9f;
1463 HandleArea.y = pRect->y + pRect->h * 0.05f;
1464 HandleArea.w += 6.0f;
1465 HandleArea.x -= 3.0f;
1466 }
1467
1468 // logic
1469 const bool InsideRail = MouseHovered(pRect: &Rail);
1470 const bool InsideHandle = MouseHovered(pRect: &HandleArea);
1471 bool Grabbed = false; // whether to apply the offset
1472
1473 if(CheckActiveItem(pId))
1474 {
1475 if(MouseButton(Index: 0))
1476 {
1477 Grabbed = true;
1478 if(Input()->ShiftIsPressed())
1479 m_MouseSlow = true;
1480 }
1481 else
1482 {
1483 SetActiveItem(nullptr);
1484 }
1485 }
1486 else if(HotItem() == pId)
1487 {
1488 if(InsideHandle)
1489 {
1490 if(MouseButton(Index: 0))
1491 {
1492 SetActiveItem(pId);
1493 m_pLastActiveScrollbar = pId;
1494 m_ActiveScrollbarOffset = MouseX() - Handle.x;
1495 Grabbed = true;
1496 }
1497 }
1498 else if(MouseButtonClicked(Index: 0))
1499 {
1500 SetActiveItem(pId);
1501 m_pLastActiveScrollbar = pId;
1502 m_ActiveScrollbarOffset = Handle.w / 2.0f;
1503 Grabbed = true;
1504 }
1505 }
1506
1507 if(!pColorInner && (InsideHandle || Grabbed) && (CheckActiveItem(pId) || HotItem() == pId))
1508 {
1509 Handle.h += 3.0f;
1510 Handle.y -= 1.5f;
1511 }
1512
1513 if(InsideRail && !MouseButton(Index: 0))
1514 {
1515 SetHotItem(pId);
1516 }
1517
1518 float ReturnValue = Current;
1519 if(Grabbed)
1520 {
1521 const float Min = Rail.x;
1522 const float Max = Rail.w - Handle.w;
1523 const float Cur = MouseX() - m_ActiveScrollbarOffset;
1524 ReturnValue = std::clamp(val: (Cur - Min) / Max, lo: 0.0f, hi: 1.0f);
1525
1526 DoToolTip(Tooltip: {
1527 pId,
1528 Handle,
1529 Localize(pStr: "Hold Shift to be more precise."),
1530 -1.0f,
1531 TOOLTIP_FONTSIZE,
1532 false,
1533 });
1534 }
1535
1536 // render
1537 const ColorRGBA HandleColor = ms_ScrollBarColorFunction.GetColor(Active: CheckActiveItem(pId), Hovered: HotItem() == pId);
1538 if(pColorInner)
1539 {
1540 CUIRect Slider;
1541 Handle.VMargin(Cut: -2.0f, pOtherRect: &Slider);
1542 Slider.HMargin(Cut: -3.0f, pOtherRect: &Slider);
1543 Slider.Draw(Color: ColorRGBA(0.15f, 0.15f, 0.15f, 1.0f).Multiply(Other: HandleColor), Corners: IGraphics::CORNER_ALL, Rounding: 5.0f);
1544 Slider.Margin(Cut: 2.0f, pOtherRect: &Slider);
1545 Slider.Draw(Color: pColorInner->Multiply(Other: HandleColor), Corners: IGraphics::CORNER_ALL, Rounding: 3.0f);
1546 }
1547 else
1548 {
1549 Rail.Draw(Color: ColorRGBA(1.0f, 1.0f, 1.0f, 0.25f), Corners: IGraphics::CORNER_ALL, Rounding: Rail.h / 2.0f);
1550 Handle.Draw(Color: HandleColor, Corners: IGraphics::CORNER_ALL, Rounding: Rail.h / 2.0f);
1551 }
1552
1553 return ReturnValue;
1554}
1555
1556bool CUi::DoScrollbarOption(const void *pId, int *pOption, const CUIRect *pRect, const char *pStr, int Min, int Max, const IScrollbarScale *pScale, unsigned Flags, const char *pSuffix)
1557{
1558 const bool Infinite = Flags & CUi::SCROLLBAR_OPTION_INFINITE;
1559 const bool NoClampValue = Flags & CUi::SCROLLBAR_OPTION_NOCLAMPVALUE;
1560 const bool MultiLine = Flags & CUi::SCROLLBAR_OPTION_MULTILINE;
1561 const bool DelayUpdate = Flags & CUi::SCROLLBAR_OPTION_DELAYUPDATE;
1562
1563 int PrevValue = (DelayUpdate && m_pLastActiveScrollbar == pId && CheckActiveItem(pId)) ? m_ScrollbarValue : *pOption;
1564 int Value = PrevValue;
1565 if(Infinite)
1566 {
1567 Max += 1;
1568 if(Value == 0)
1569 Value = Max;
1570 }
1571
1572 char aBuf[256];
1573 if(!Infinite || Value != Max)
1574 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "%s: %i%s", pStr, Value, pSuffix);
1575 else
1576 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "%s: ∞", pStr);
1577
1578 if(NoClampValue)
1579 {
1580 // clamp the value internally for the scrollbar
1581 Value = std::clamp(val: Value, lo: Min, hi: Max);
1582 }
1583
1584 CUIRect Label, ScrollBar;
1585 if(MultiLine)
1586 pRect->HSplitMid(pTop: &Label, pBottom: &ScrollBar);
1587 else
1588 pRect->VSplitMid(pLeft: &Label, pRight: &ScrollBar, Spacing: std::min(a: 10.0f, b: pRect->w * 0.05f));
1589
1590 const float FontSize = Label.h * CUi::ms_FontmodHeight * 0.8f;
1591 DoLabel(pRect: &Label, pText: aBuf, Size: FontSize, Align: TEXTALIGN_ML);
1592
1593 Value = pScale->ToAbsolute(RelativeValue: DoScrollbarH(pId, pRect: &ScrollBar, Current: pScale->ToRelative(AbsoluteValue: Value, Min, Max)), Min, Max);
1594 if(NoClampValue && ((Value == Min && PrevValue < Min) || (Value == Max && PrevValue > Max)))
1595 {
1596 Value = PrevValue; // use previous out of range value instead if the scrollbar is at the edge
1597 }
1598 else if(Infinite)
1599 {
1600 if(Value == Max)
1601 Value = 0;
1602 }
1603
1604 if(DelayUpdate && m_pLastActiveScrollbar == pId && CheckActiveItem(pId))
1605 {
1606 m_ScrollbarValue = Value;
1607 return false;
1608 }
1609
1610 if(*pOption != Value)
1611 {
1612 *pOption = Value;
1613 return true;
1614 }
1615 return false;
1616}
1617
1618void CUi::RenderProgressBar(CUIRect ProgressBar, float Progress)
1619{
1620 const float Rounding = std::min(a: 5.0f, b: ProgressBar.h / 2.0f);
1621 ProgressBar.Draw(Color: ColorRGBA(1.0f, 1.0f, 1.0f, 0.25f), Corners: IGraphics::CORNER_ALL, Rounding);
1622 ProgressBar.w = std::max(a: ProgressBar.w * Progress, b: 2 * Rounding);
1623 ProgressBar.Draw(Color: ColorRGBA(1.0f, 1.0f, 1.0f, 0.5f), Corners: IGraphics::CORNER_ALL, Rounding);
1624}
1625
1626void CCachedText::Update(ITextRender *pTextRender, const char *pText, float FontSize, float LineWidth, int CursorFlags)
1627{
1628 if(m_FontSize == FontSize && m_LineWidth == LineWidth && m_CursorFlags == CursorFlags && m_Text == pText)
1629 return;
1630
1631 // The render flags of a text container are fixed when it is created and depend on the
1632 // line width, so only text and font size changes can reuse the existing container and
1633 // upload the new quads into its buffer instead of allocating a new one.
1634 const bool ReuseContainer = m_TextContainerIndex.Valid() && m_LineWidth == LineWidth && m_CursorFlags == CursorFlags;
1635
1636 m_Text = pText;
1637 m_FontSize = FontSize;
1638 m_LineWidth = LineWidth;
1639 m_CursorFlags = CursorFlags;
1640
1641 CTextCursor Cursor;
1642 Cursor.m_FontSize = FontSize;
1643 Cursor.m_LineWidth = LineWidth;
1644 Cursor.m_Flags = CursorFlags;
1645
1646 // The color is applied when rendering, so it must not be baked into the quads.
1647 const ColorRGBA OldColor = pTextRender->GetTextColor();
1648 pTextRender->TextColor(Color: pTextRender->DefaultTextColor());
1649 if(ReuseContainer)
1650 pTextRender->RecreateTextContainerSoft(TextContainerIndex&: m_TextContainerIndex, pCursor: &Cursor, pText: m_Text.c_str());
1651 else
1652 pTextRender->RecreateTextContainer(TextContainerIndex&: m_TextContainerIndex, pCursor: &Cursor, pText: m_Text.c_str());
1653 pTextRender->TextColor(Color: OldColor);
1654
1655 m_BoundingBox = Cursor.BoundingBox();
1656 m_MaxCharacterHeight = Cursor.m_MaxCharacterHeight;
1657 m_AlignedFontSize = Cursor.m_AlignedFontSize;
1658}
1659
1660void CCachedText::Render(ITextRender *pTextRender, vec2 Pos, ColorRGBA Color) const
1661{
1662 if(!m_TextContainerIndex.Valid())
1663 return;
1664 // The quads are built with the default color, so the outline has to be faded here
1665 // instead of inheriting the alpha from the baked vertex color.
1666 pTextRender->RenderTextContainer(TextContainerIndex: m_TextContainerIndex, TextColor: Color, TextOutlineColor: pTextRender->DefaultTextOutlineColor().WithMultipliedAlpha(alpha: Color.a), X: Pos.x, Y: Pos.y);
1667}
1668
1669void CCachedText::Reset(ITextRender *pTextRender)
1670{
1671 pTextRender->DeleteTextContainer(TextContainerIndex&: m_TextContainerIndex);
1672 m_Text.clear();
1673 m_FontSize = -1.0f;
1674 m_LineWidth = -1.0f;
1675 m_CursorFlags = 0;
1676 m_BoundingBox = {.m_X: 0.0f, .m_Y: 0.0f, .m_W: 0.0f, .m_H: 0.0f};
1677 m_MaxCharacterHeight = 0.0f;
1678}
1679
1680void CUi::RenderTime(CUIRect TimeRect, float FontSize, int Seconds, bool NotFinished, int Millis, bool TrueMilliseconds, CCachedText &SecondsText, CCachedText &MillisText, ColorRGBA Color) const
1681{
1682 if(NotFinished)
1683 return;
1684
1685 char aBuf[128];
1686 str_time(centisecs: absolute(a: static_cast<int64_t>(Seconds)) * 100, format: ETimeFormat::HOURS, buffer: aBuf, buffer_size: sizeof(aBuf));
1687 SecondsText.Update(pTextRender: TextRender(), pText: aBuf, FontSize);
1688
1689 // align in vertical middle
1690 vec2 Cursor = TimeRect.TopLeft();
1691 const float SecondsWidth = std::min(a: SecondsText.Width(), b: TimeRect.w);
1692 Cursor.x += TimeRect.w - SecondsWidth; // align right
1693 Cursor.y += ((TimeRect.h - SecondsText.MaxCharacterHeight()) / 2.0f - (FontSize - SecondsText.MaxCharacterHeight()));
1694
1695 // show milliseconds or centiseconds if we are under an hour
1696 if(Millis >= 0 && Seconds < 60 * 60)
1697 {
1698 constexpr float Ratio = 0.7f;
1699 const float CentisecondFontSize = FontSize * Ratio;
1700
1701 // format dot plus 2 or 3 digits
1702 char aMillis[5];
1703 Millis %= 1000;
1704 if(!TrueMilliseconds)
1705 str_format(buffer: aMillis, buffer_size: sizeof(aMillis), format: ".%02d", (int)std::round(x: Millis / 10));
1706 else
1707 str_format(buffer: aMillis, buffer_size: sizeof(aMillis), format: ".%03d", Millis);
1708 MillisText.Update(pTextRender: TextRender(), pText: aMillis, FontSize: CentisecondFontSize);
1709
1710 const float MillisWidth = MillisText.Width();
1711
1712 // pull the fractional block (dot + digits) slightly closer to the seconds
1713 constexpr float FractionKern = 0.35f;
1714 const float DotWidth = MillisWidth / (TrueMilliseconds ? 4 : 3);
1715 const float Kern = DotWidth * FractionKern;
1716 Cursor.x -= MillisWidth - Kern;
1717
1718 vec2 CursorMillis = TimeRect.TopLeft();
1719 CursorMillis.x += TimeRect.w - MillisWidth; // align right
1720
1721 // Align the bottom of the fractional text with the bottom of the seconds.
1722 CursorMillis.y = Cursor.y + (SecondsText.AlignedFontSize() - MillisText.AlignedFontSize());
1723
1724 SecondsText.Render(pTextRender: TextRender(), Pos: Cursor, Color);
1725 MillisText.Render(pTextRender: TextRender(), Pos: CursorMillis, Color);
1726 }
1727 else
1728 {
1729 SecondsText.Render(pTextRender: TextRender(), Pos: Cursor, Color);
1730 }
1731}
1732
1733void CUi::RenderProgressSpinner(vec2 Center, float OuterRadius, const SProgressSpinnerProperties &Props) const
1734{
1735 Graphics()->TextureClear();
1736 Graphics()->QuadsBegin();
1737
1738 // The filled and unfilled segments need to begin at the same angle offset
1739 // or the differences in pixel alignment will make the filled segments flicker.
1740 const float SegmentsAngle = 2.0f * pi / Props.m_Segments;
1741 const float InnerRadius = OuterRadius * 0.75f;
1742 const float AngleOffset = -0.5f * pi;
1743 Graphics()->SetColor(Props.m_Color.WithMultipliedAlpha(alpha: 0.5f));
1744 for(int i = 0; i < Props.m_Segments; ++i)
1745 {
1746 const vec2 Dir1 = direction(angle: AngleOffset + i * SegmentsAngle);
1747 const vec2 Dir2 = direction(angle: AngleOffset + (i + 1) * SegmentsAngle);
1748 IGraphics::CFreeformItem Item = IGraphics::CFreeformItem(
1749 Center + Dir1 * InnerRadius, Center + Dir2 * InnerRadius,
1750 Center + Dir1 * OuterRadius, Center + Dir2 * OuterRadius);
1751 Graphics()->QuadsDrawFreeform(pArray: &Item, Num: 1);
1752 }
1753
1754 const float FilledRatio = Props.m_Progress < 0.0f ? 0.333f : Props.m_Progress;
1755 const int FilledSegmentOffset = Props.m_Progress < 0.0f ? round_to_int(f: m_ProgressSpinnerOffset * Props.m_Segments) : 0;
1756 const int FilledNumSegments = std::min(a: (int)(Props.m_Segments * FilledRatio) + (Props.m_Progress < 0.0f ? 0 : 1), b: Props.m_Segments);
1757 Graphics()->SetColor(Props.m_Color);
1758 for(int i = 0; i < FilledNumSegments; ++i)
1759 {
1760 const float Angle1 = AngleOffset + (i + FilledSegmentOffset) * SegmentsAngle;
1761 const float Angle2 = AngleOffset + ((i + 1 == FilledNumSegments && Props.m_Progress >= 0.0f) ? (2.0f * pi * Props.m_Progress) : ((i + FilledSegmentOffset + 1) * SegmentsAngle));
1762 IGraphics::CFreeformItem Item = IGraphics::CFreeformItem(
1763 Center.x + std::cos(x: Angle1) * InnerRadius, Center.y + std::sin(x: Angle1) * InnerRadius,
1764 Center.x + std::cos(x: Angle2) * InnerRadius, Center.y + std::sin(x: Angle2) * InnerRadius,
1765 Center.x + std::cos(x: Angle1) * OuterRadius, Center.y + std::sin(x: Angle1) * OuterRadius,
1766 Center.x + std::cos(x: Angle2) * OuterRadius, Center.y + std::sin(x: Angle2) * OuterRadius);
1767 Graphics()->QuadsDrawFreeform(pArray: &Item, Num: 1);
1768 }
1769
1770 Graphics()->QuadsEnd();
1771}
1772
1773void CUi::DoBackButton()
1774{
1775 if(!g_Config.m_ClBackButton)
1776 return;
1777
1778 MapScreen();
1779 const CUIRect *pScreen = Screen();
1780 const float Size = pScreen->h * 0.1f;
1781 constexpr float PositionScale = 1000000.0f;
1782 const auto ClampPos = [&](vec2 Pos) {
1783 Pos.x = std::clamp(val: Pos.x, lo: 0.0f, hi: pScreen->w - Size);
1784 Pos.y = std::clamp(val: Pos.y, lo: 0.0f, hi: pScreen->h - Size);
1785 return Pos;
1786 };
1787
1788 vec2 ButtonPos = ClampPos({g_Config.m_ClBackButtonX / PositionScale * pScreen->w, g_Config.m_ClBackButtonY / PositionScale * pScreen->h});
1789 CUIRect ButtonRect{.x: ButtonPos.x, .y: ButtonPos.y, .w: Size, .h: Size};
1790
1791 bool Clicked = false;
1792 bool Abrupted = false;
1793 const int Result = DoDraggableButtonLogic(pId: &m_BackButtonId, Checked: 0, pRect: &ButtonRect, pClicked: &Clicked, pAbrupted: &Abrupted);
1794
1795 // Detect the press transition. DoDraggableButtonLogic sets the active item on the
1796 // press frame but returns 0 there, so check CheckActiveItem to catch it.
1797 if(m_BackButtonOp == EBackButtonOp::NONE && CheckActiveItem(pId: &m_BackButtonId))
1798 {
1799 m_BackButtonInitialMouse = MousePos();
1800 m_BackButtonDragOffset = ButtonPos - MousePos();
1801 m_BackButtonOp = EBackButtonOp::CLICKED;
1802 if(m_OnBackButtonPressedFunction)
1803 m_OnBackButtonPressedFunction();
1804 }
1805
1806 if(m_BackButtonOp == EBackButtonOp::CLICKED && length(a: MousePos() - m_BackButtonInitialMouse) > 5.0f)
1807 {
1808 m_BackButtonOp = EBackButtonOp::DRAGGING;
1809 }
1810
1811 if(m_BackButtonOp == EBackButtonOp::DRAGGING)
1812 {
1813 ButtonPos = ClampPos(MousePos() + m_BackButtonDragOffset);
1814 g_Config.m_ClBackButtonX = round_to_int(f: ButtonPos.x / pScreen->w * PositionScale);
1815 g_Config.m_ClBackButtonY = round_to_int(f: ButtonPos.y / pScreen->h * PositionScale);
1816 ButtonRect.x = ButtonPos.x;
1817 ButtonRect.y = ButtonPos.y;
1818 }
1819
1820 if(Clicked || Abrupted)
1821 {
1822 if(Result && Clicked && m_BackButtonOp == EBackButtonOp::CLICKED && m_DispatchInputFunction)
1823 {
1824 IInput::CEvent Event;
1825 Event.m_Key = KEY_ESCAPE;
1826 Event.m_InputCount = 0;
1827 Event.m_aText[0] = '\0';
1828 Event.m_Flags = IInput::FLAG_PRESS;
1829 m_DispatchInputFunction(Event);
1830 Event.m_Flags = IInput::FLAG_RELEASE;
1831 m_DispatchInputFunction(Event);
1832 }
1833 m_BackButtonOp = EBackButtonOp::NONE;
1834 }
1835
1836 m_BackButtonRect = ButtonRect;
1837}
1838
1839void CUi::RenderBackButton()
1840{
1841 if(!g_Config.m_ClBackButton)
1842 return;
1843
1844 MapScreen();
1845
1846 // Override hot/active claims made by UI rendered between DoBackButton and RenderBackButton.
1847 if(m_BackButtonOp != EBackButtonOp::NONE)
1848 SetActiveItem(&m_BackButtonId);
1849 else if(MouseHovered(pRect: &m_BackButtonRect) && !MouseButton(Index: 0) && !MouseButton(Index: 1) && !MouseButton(Index: 2))
1850 SetHotItem(&m_BackButtonId);
1851
1852 const bool Pressed = m_BackButtonOp != EBackButtonOp::NONE;
1853 const bool Hovered = !Pressed && HotItem() == &m_BackButtonId;
1854 const float Alpha = Pressed ? 0.9f : (Hovered ? 0.35f : 0.5f);
1855 m_BackButtonRect.Draw(Color: {0.0f, 0.0f, 0.0f, Alpha}, Corners: IGraphics::CORNER_ALL, Rounding: 12.0f);
1856
1857 TextRender()->SetFontPreset(EFontPreset::ICON_FONT);
1858 TextRender()->SetRenderFlags(ETextRenderFlags::TEXT_RENDER_FLAG_ONLY_ADVANCE_WIDTH |
1859 ETextRenderFlags::TEXT_RENDER_FLAG_NO_X_BEARING |
1860 ETextRenderFlags::TEXT_RENDER_FLAG_NO_Y_BEARING);
1861 DoLabel(pRect: &m_BackButtonRect, pText: FontIcon::CHEVRON_LEFT, Size: m_BackButtonRect.w * 0.5f, Align: TEXTALIGN_MC);
1862 TextRender()->SetRenderFlags(0);
1863 TextRender()->SetFontPreset(EFontPreset::DEFAULT_FONT);
1864}
1865
1866void CUi::DoToolTip(const void *pId, const CUIRect *pNearRect, const char *pText, float WidthHint) const
1867{
1868 DoToolTip(Tooltip: {pId,
1869 *pNearRect,
1870 pText,
1871 WidthHint,
1872 TOOLTIP_FONTSIZE,
1873 false});
1874}
1875
1876void CUi::DoToolTip(const CTooltip &Tooltip) const
1877{
1878 m_pTooltips->DoToolTip(Tooltip);
1879}
1880