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
21#include <limits>
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}
119
120CUi::CUi()
121{
122 m_Enabled = true;
123
124 m_Screen.x = 0.0f;
125 m_Screen.y = 0.0f;
126}
127
128CUi::~CUi()
129{
130 for(CUIElement *&pEl : m_vpOwnUIElements)
131 {
132 delete pEl;
133 }
134 m_vpOwnUIElements.clear();
135}
136
137CUIElement *CUi::GetNewUIElement(int RequestedRectCount)
138{
139 CUIElement *pNewEl = new CUIElement(this, RequestedRectCount);
140
141 m_vpOwnUIElements.push_back(x: pNewEl);
142
143 return pNewEl;
144}
145
146void CUi::AddUIElement(CUIElement *pElement)
147{
148 m_vpUIElements.push_back(x: pElement);
149}
150
151void CUi::ResetUIElement(CUIElement &UIElement) const
152{
153 for(CUIElement::SUIElementRect &Rect : UIElement.m_vUIRects)
154 {
155 Graphics()->DeleteQuadContainer(ContainerIndex&: Rect.m_UIRectQuadContainer);
156 TextRender()->DeleteTextContainer(TextContainerIndex&: Rect.m_UITextContainer);
157 Rect.Reset();
158 }
159}
160
161void CUi::OnElementsReset()
162{
163 for(CUIElement *pEl : m_vpUIElements)
164 {
165 ResetUIElement(UIElement&: *pEl);
166 }
167}
168
169void CUi::OnWindowResize()
170{
171 OnElementsReset();
172}
173
174void CUi::OnCursorMove(float X, float Y)
175{
176 if(!CheckMouseLock())
177 {
178 m_UpdatedMousePos.x = std::clamp(val: m_UpdatedMousePos.x + X, lo: 0.0f, hi: Graphics()->WindowWidth() - 1.0f);
179 m_UpdatedMousePos.y = std::clamp(val: m_UpdatedMousePos.y + Y, lo: 0.0f, hi: Graphics()->WindowHeight() - 1.0f);
180 }
181
182 m_UpdatedMouseDelta += vec2(X, Y);
183}
184
185void CUi::Update()
186{
187 const vec2 WindowSize = vec2(Graphics()->WindowWidth(), Graphics()->WindowHeight());
188 const CUIRect *pScreen = Screen();
189
190 unsigned UpdatedMouseButtonsNext = 0;
191 if(Enabled())
192 {
193 // Update mouse buttons based on mouse keys
194 for(int MouseKey = KEY_MOUSE_1; MouseKey <= KEY_MOUSE_3; ++MouseKey)
195 {
196 if(Input()->KeyIsPressed(Key: MouseKey))
197 {
198 m_UpdatedMouseButtons |= 1 << (MouseKey - KEY_MOUSE_1);
199 }
200 }
201
202 // Update mouse position and buttons based on touch finger state
203 UpdateTouchState(State&: m_TouchState);
204 if(m_TouchState.m_AnyPressed)
205 {
206 if(!CheckMouseLock())
207 {
208 m_UpdatedMousePos = m_TouchState.m_PrimaryPosition * WindowSize;
209 m_UpdatedMousePos.x = std::clamp(val: m_UpdatedMousePos.x, lo: 0.0f, hi: WindowSize.x - 1.0f);
210 m_UpdatedMousePos.y = std::clamp(val: m_UpdatedMousePos.y, lo: 0.0f, hi: WindowSize.y - 1.0f);
211 }
212 m_UpdatedMouseDelta += m_TouchState.m_PrimaryDelta * WindowSize;
213
214 // Scroll currently hovered scroll region with touch scroll gesture.
215 if(m_TouchState.m_ScrollAmount != vec2(0.0f, 0.0f))
216 {
217 if(m_pHotScrollRegion != nullptr)
218 {
219 m_pHotScrollRegion->ScrollRelativeDirect(ScrollAmount: -m_TouchState.m_ScrollAmount.y * pScreen->h);
220 }
221 m_TouchState.m_ScrollAmount = vec2(0.0f, 0.0f);
222 }
223
224 // We need to delay the click until the next update or it's not possible to use UI
225 // elements because click and hover would happen at the same time for touch events.
226 if(m_TouchState.m_PrimaryPressed)
227 {
228 UpdatedMouseButtonsNext |= 1;
229 }
230 if(m_TouchState.m_SecondaryPressed)
231 {
232 UpdatedMouseButtonsNext |= 2;
233 }
234 }
235 }
236
237 m_MousePos = m_UpdatedMousePos * vec2(pScreen->w, pScreen->h) / WindowSize;
238 m_MouseDelta = m_UpdatedMouseDelta;
239 m_UpdatedMouseDelta = vec2(0.0f, 0.0f);
240 m_LastMouseButtons = m_MouseButtons;
241 m_MouseButtons = m_UpdatedMouseButtons;
242 m_UpdatedMouseButtons = UpdatedMouseButtonsNext;
243
244 m_pHotItem = m_pBecomingHotItem;
245 if(m_pActiveItem)
246 m_pHotItem = m_pActiveItem;
247 m_pBecomingHotItem = nullptr;
248 m_pHotScrollRegion = m_pBecomingHotScrollRegion;
249 m_pBecomingHotScrollRegion = nullptr;
250
251 if(Enabled())
252 {
253 CLineInput *pActiveInput = CLineInput::GetActiveInput();
254 if(pActiveInput && m_pLastActiveItem && pActiveInput != m_pLastActiveItem)
255 pActiveInput->Deactivate();
256 }
257 else
258 {
259 m_pHotItem = nullptr;
260 m_pActiveItem = nullptr;
261 m_pHotScrollRegion = nullptr;
262 }
263
264 m_ProgressSpinnerOffset += Client()->RenderFrameTime() * 1.5f;
265 m_ProgressSpinnerOffset = std::fmod(x: m_ProgressSpinnerOffset, y: 1.0f);
266}
267
268void CUi::DebugRender(float X, float Y)
269{
270 MapScreen();
271
272 char aBuf[128];
273 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "hot=%p nexthot=%p active=%p lastactive=%p", HotItem(), NextHotItem(), ActiveItem(), m_pLastActiveItem);
274 TextRender()->Text(x: X, y: Y, Size: 10.0f, pText: aBuf);
275}
276
277bool CUi::MouseInside(const CUIRect *pRect) const
278{
279 return pRect->Inside(Point: MousePos());
280}
281
282void CUi::ConvertMouseMove(float *pX, float *pY, IInput::ECursorType CursorType) const
283{
284 float Factor = 1.0f;
285 switch(CursorType)
286 {
287 case IInput::CURSOR_MOUSE:
288 Factor = g_Config.m_UiMousesens / 100.0f;
289 break;
290 case IInput::CURSOR_JOYSTICK:
291 Factor = g_Config.m_UiControllerSens / 100.0f;
292 break;
293 default:
294 dbg_assert_failed("CUi::ConvertMouseMove CursorType %d", (int)CursorType);
295 }
296
297 if(m_MouseSlow)
298 Factor *= 0.05f;
299
300 *pX *= Factor;
301 *pY *= Factor;
302}
303
304void CUi::UpdateTouchState(CTouchState &State) const
305{
306 const std::vector<IInput::CTouchFingerState> &vTouchFingerStates = Input()->TouchFingerStates();
307
308 // Updated touch position as long as any finger is beinged pressed.
309 const bool WasAnyPressed = State.m_AnyPressed;
310 State.m_AnyPressed = !vTouchFingerStates.empty();
311 if(State.m_AnyPressed)
312 {
313 // We always use the position of first finger being pressed down. Multi-touch UI is
314 // not possible and always choosing the last finger would cause the cursor to briefly
315 // warp without having any effect if multiple fingers are used.
316 const IInput::CTouchFingerState &PrimaryTouchFingerState = vTouchFingerStates.front();
317 State.m_PrimaryPosition = PrimaryTouchFingerState.m_Position;
318 State.m_PrimaryDelta = PrimaryTouchFingerState.m_Delta;
319 }
320
321 // Update primary (left click) and secondary (right click) action.
322 if(State.m_SecondaryPressedNext)
323 {
324 // The secondary action is delayed by one frame until the primary has been released,
325 // otherwise most UI elements cannot be activated by the secondary action because they
326 // never become the hot-item unless all mouse buttons are released for one frame.
327 State.m_SecondaryPressedNext = false;
328 State.m_SecondaryPressed = true;
329 }
330 else if(vTouchFingerStates.size() != 1)
331 {
332 // Consider primary and secondary to be pressed only when exactly one finger is pressed,
333 // to avoid UI elements and console text selection being activated while scrolling.
334 State.m_PrimaryPressed = false;
335 State.m_SecondaryPressed = false;
336 }
337 else if(!WasAnyPressed)
338 {
339 State.m_PrimaryPressed = true;
340 State.m_SecondaryActivationTime = Client()->GlobalTime();
341 State.m_SecondaryActivationDelta = vec2(0.0f, 0.0f);
342 }
343 else if(State.m_PrimaryPressed)
344 {
345 // Activate secondary by pressing and holding roughly on the same position for some time.
346 const float SecondaryActivationDelay = 0.5f;
347 const float SecondaryActivationMaxDistance = 0.001f;
348 State.m_SecondaryActivationDelta += State.m_PrimaryDelta;
349 if(Client()->GlobalTime() - State.m_SecondaryActivationTime >= SecondaryActivationDelay &&
350 length(a: State.m_SecondaryActivationDelta) <= SecondaryActivationMaxDistance)
351 {
352 State.m_PrimaryPressed = false;
353 State.m_SecondaryPressedNext = true;
354 }
355 }
356
357 // Handle two fingers being moved roughly in same direction as a scrolling gesture.
358 if(vTouchFingerStates.size() == 2)
359 {
360 const vec2 Delta0 = vTouchFingerStates[0].m_Delta;
361 const vec2 Delta1 = vTouchFingerStates[1].m_Delta;
362 const float Similarity = dot(a: normalize(v: Delta0), b: normalize(v: Delta1));
363 const float SimilarityThreshold = 0.8f; // How parallel the deltas have to be (1.0f being completely parallel)
364 if(Similarity > SimilarityThreshold)
365 {
366 const float DirectionThreshold = 3.0f; // How much longer the delta of one axis has to be compared to other axis
367
368 // Vertical scrolling (y-delta must be larger than x-delta)
369 if(absolute(a: Delta0.y) > DirectionThreshold * absolute(a: Delta0.x) &&
370 absolute(a: Delta1.y) > DirectionThreshold * absolute(a: Delta1.x) &&
371 Delta0.y * Delta1.y > 0.0f) // Same y direction required
372 {
373 // Accumulate average delta of the two fingers
374 State.m_ScrollAmount.y += (Delta0.y + Delta1.y) / 2.0f;
375 }
376 }
377 }
378 else
379 {
380 // Scrolling gesture should start from zero again if released.
381 State.m_ScrollAmount = vec2(0.0f, 0.0f);
382 }
383}
384
385bool CUi::ConsumeHotkey(EHotkey Hotkey)
386{
387 const bool Pressed = m_HotkeysPressed & Hotkey;
388 m_HotkeysPressed &= ~Hotkey;
389 return Pressed;
390}
391
392bool CUi::OnInput(const IInput::CEvent &Event)
393{
394 if(!Enabled())
395 return false;
396
397 CLineInput *pActiveInput = CLineInput::GetActiveInput();
398 if(pActiveInput && pActiveInput->ProcessInput(Event))
399 return true;
400
401 if(Event.m_Flags & IInput::FLAG_PRESS)
402 {
403 unsigned LastHotkeysPressed = m_HotkeysPressed;
404 if(Event.m_Key == KEY_RETURN || Event.m_Key == KEY_KP_ENTER)
405 m_HotkeysPressed |= HOTKEY_ENTER;
406 else if(Event.m_Key == KEY_ESCAPE)
407 m_HotkeysPressed |= HOTKEY_ESCAPE;
408 else if(Event.m_Key == KEY_TAB && !Input()->AltIsPressed())
409 m_HotkeysPressed |= HOTKEY_TAB;
410 else if(Event.m_Key == KEY_DELETE)
411 m_HotkeysPressed |= HOTKEY_DELETE;
412 else if(Event.m_Key == KEY_UP)
413 m_HotkeysPressed |= HOTKEY_UP;
414 else if(Event.m_Key == KEY_DOWN)
415 m_HotkeysPressed |= HOTKEY_DOWN;
416 else if(Event.m_Key == KEY_LEFT)
417 m_HotkeysPressed |= HOTKEY_LEFT;
418 else if(Event.m_Key == KEY_RIGHT)
419 m_HotkeysPressed |= HOTKEY_RIGHT;
420 else if(Event.m_Key == KEY_MOUSE_WHEEL_UP)
421 m_HotkeysPressed |= HOTKEY_SCROLL_UP;
422 else if(Event.m_Key == KEY_MOUSE_WHEEL_DOWN)
423 m_HotkeysPressed |= HOTKEY_SCROLL_DOWN;
424 else if(Event.m_Key == KEY_PAGEUP)
425 m_HotkeysPressed |= HOTKEY_PAGE_UP;
426 else if(Event.m_Key == KEY_PAGEDOWN)
427 m_HotkeysPressed |= HOTKEY_PAGE_DOWN;
428 else if(Event.m_Key == KEY_HOME)
429 m_HotkeysPressed |= HOTKEY_HOME;
430 else if(Event.m_Key == KEY_END)
431 m_HotkeysPressed |= HOTKEY_END;
432 return LastHotkeysPressed != m_HotkeysPressed;
433 }
434 return false;
435}
436
437float CUi::ButtonColorMul(const void *pId)
438{
439 if(CheckActiveItem(pId))
440 return ButtonColorMulActive();
441 else if(HotItem() == pId)
442 return ButtonColorMulHot();
443 return ButtonColorMulDefault();
444}
445
446const CUIRect *CUi::Screen()
447{
448 m_Screen.h = 600.0f;
449 m_Screen.w = Graphics()->ScreenAspect() * m_Screen.h;
450 return &m_Screen;
451}
452
453void CUi::MapScreen()
454{
455 const CUIRect *pScreen = Screen();
456 Graphics()->MapScreen(TopLeftX: pScreen->x, TopLeftY: pScreen->y, BottomRightX: pScreen->w, BottomRightY: pScreen->h);
457}
458
459float CUi::PixelSize()
460{
461 return Screen()->w / Graphics()->ScreenWidth();
462}
463
464void CUi::ClipEnable(const CUIRect *pRect)
465{
466 if(IsClipped())
467 {
468 const CUIRect *pOldRect = ClipArea();
469 CUIRect Intersection;
470 Intersection.x = std::max(a: pRect->x, b: pOldRect->x);
471 Intersection.y = std::max(a: pRect->y, b: pOldRect->y);
472 Intersection.w = std::min(a: pRect->x + pRect->w, b: pOldRect->x + pOldRect->w) - pRect->x;
473 Intersection.h = std::min(a: pRect->y + pRect->h, b: pOldRect->y + pOldRect->h) - pRect->y;
474 m_vClips.push_back(x: Intersection);
475 }
476 else
477 {
478 m_vClips.push_back(x: *pRect);
479 }
480 UpdateClipping();
481}
482
483void CUi::ClipDisable()
484{
485 dbg_assert(IsClipped(), "no clip region");
486 m_vClips.pop_back();
487 UpdateClipping();
488}
489
490const CUIRect *CUi::ClipArea() const
491{
492 dbg_assert(IsClipped(), "no clip region");
493 return &m_vClips.back();
494}
495
496void CUi::UpdateClipping()
497{
498 if(IsClipped())
499 {
500 const CUIRect *pRect = ClipArea();
501 const float XScale = Graphics()->ScreenWidth() / Screen()->w;
502 const float YScale = Graphics()->ScreenHeight() / Screen()->h;
503
504 const float ScaledX = pRect->x * XScale;
505 const float ScaledY = pRect->y * YScale;
506 const float RoundX = std::round(x: ScaledX);
507 const float RoundY = std::round(x: ScaledY);
508 Graphics()->ClipEnable(x: RoundX, y: RoundY, w: std::round(x: pRect->w * XScale + (ScaledX - RoundX)), h: std::round(x: pRect->h * YScale + (ScaledY - RoundY)));
509 }
510 else
511 {
512 Graphics()->ClipDisable();
513 }
514}
515
516int CUi::DoButtonLogic(const void *pId, int Checked, const CUIRect *pRect, const unsigned Flags)
517{
518 int ReturnValue = 0;
519 const bool Inside = MouseHovered(pRect);
520
521 if(CheckActiveItem(pId))
522 {
523 dbg_assert(m_ActiveButtonLogicButton >= 0, "m_ActiveButtonLogicButton invalid");
524 if(!MouseButton(Index: m_ActiveButtonLogicButton))
525 {
526 if(Inside && Checked >= 0)
527 ReturnValue = 1 + m_ActiveButtonLogicButton;
528 SetActiveItem(nullptr);
529 m_ActiveButtonLogicButton = -1;
530 }
531 }
532
533 bool NoRelevantButtonsPressed = true;
534 for(int Button = 0; Button < 3; ++Button)
535 {
536 if((Flags & (BUTTONFLAG_LEFT << Button)) && MouseButton(Index: Button))
537 {
538 NoRelevantButtonsPressed = false;
539 if(HotItem() == pId)
540 {
541 SetActiveItem(pId);
542 m_ActiveButtonLogicButton = Button;
543 }
544 }
545 }
546
547 if(Inside && NoRelevantButtonsPressed)
548 SetHotItem(pId);
549
550 return ReturnValue;
551}
552
553int CUi::DoDraggableButtonLogic(const void *pId, int Checked, const CUIRect *pRect, bool *pClicked, bool *pAbrupted)
554{
555 // logic
556 int ReturnValue = 0;
557 const bool Inside = MouseHovered(pRect);
558
559 if(pClicked != nullptr)
560 *pClicked = false;
561 if(pAbrupted != nullptr)
562 *pAbrupted = false;
563
564 if(CheckActiveItem(pId))
565 {
566 dbg_assert(m_ActiveDraggableButtonLogicButton >= 0, "m_ActiveDraggableButtonLogicButton invalid");
567 if(m_ActiveDraggableButtonLogicButton == 0)
568 {
569 if(Checked >= 0)
570 ReturnValue = 1 + m_ActiveDraggableButtonLogicButton;
571 if(!MouseButton(Index: m_ActiveDraggableButtonLogicButton))
572 {
573 if(pClicked != nullptr)
574 *pClicked = true;
575 SetActiveItem(nullptr);
576 m_ActiveDraggableButtonLogicButton = -1;
577 }
578 if(MouseButton(Index: 1))
579 {
580 if(pAbrupted != nullptr)
581 *pAbrupted = true;
582 SetActiveItem(nullptr);
583 m_ActiveDraggableButtonLogicButton = -1;
584 }
585 }
586 else if(!MouseButton(Index: m_ActiveDraggableButtonLogicButton))
587 {
588 if(Inside && Checked >= 0)
589 ReturnValue = 1 + m_ActiveDraggableButtonLogicButton;
590 if(pClicked != nullptr)
591 *pClicked = true;
592 SetActiveItem(nullptr);
593 m_ActiveDraggableButtonLogicButton = -1;
594 }
595 }
596 else if(HotItem() == pId)
597 {
598 for(int i = 0; i < 3; ++i)
599 {
600 if(MouseButton(Index: i))
601 {
602 SetActiveItem(pId);
603 m_ActiveDraggableButtonLogicButton = i;
604 }
605 }
606 }
607
608 if(Inside && !MouseButton(Index: 0) && !MouseButton(Index: 1) && !MouseButton(Index: 2))
609 SetHotItem(pId);
610
611 return ReturnValue;
612}
613
614bool CUi::DoDoubleClickLogic(const void *pId)
615{
616 if(m_DoubleClickState.m_pLastClickedId == pId &&
617 Client()->GlobalTime() - m_DoubleClickState.m_LastClickTime < 0.5f &&
618 distance(a: m_DoubleClickState.m_LastClickPos, b: MousePos()) <= 32.0f * Screen()->h / Graphics()->ScreenHeight())
619 {
620 m_DoubleClickState.m_pLastClickedId = nullptr;
621 return true;
622 }
623 m_DoubleClickState.m_pLastClickedId = pId;
624 m_DoubleClickState.m_LastClickTime = Client()->GlobalTime();
625 m_DoubleClickState.m_LastClickPos = MousePos();
626 return false;
627}
628
629EEditState CUi::DoPickerLogic(const void *pId, const CUIRect *pRect, float *pX, float *pY)
630{
631 if(MouseHovered(pRect))
632 SetHotItem(pId);
633
634 EEditState Res = EEditState::EDITING;
635
636 if(HotItem() == pId && MouseButtonClicked(Index: 0))
637 {
638 SetActiveItem(pId);
639 if(!m_pLastEditingItem)
640 {
641 m_pLastEditingItem = pId;
642 Res = EEditState::START;
643 }
644 }
645
646 if(CheckActiveItem(pId) && !MouseButton(Index: 0))
647 {
648 SetActiveItem(nullptr);
649 if(m_pLastEditingItem == pId)
650 {
651 m_pLastEditingItem = nullptr;
652 Res = EEditState::END;
653 }
654 }
655
656 if(!CheckActiveItem(pId) && Res == EEditState::EDITING)
657 return EEditState::NONE;
658
659 if(Input()->ShiftIsPressed())
660 m_MouseSlow = true;
661
662 if(pX)
663 *pX = std::clamp(val: MouseX() - pRect->x, lo: 0.0f, hi: pRect->w);
664 if(pY)
665 *pY = std::clamp(val: MouseY() - pRect->y, lo: 0.0f, hi: pRect->h);
666
667 return Res;
668}
669
670void CUi::DoSmoothScrollLogic(float *pScrollOffset, float *pScrollOffsetChange, float ViewPortSize, float TotalSize, bool SmoothClamp, float ScrollSpeed) const
671{
672 // reset scrolling if it's not necessary anymore
673 if(TotalSize < ViewPortSize)
674 {
675 *pScrollOffsetChange = -*pScrollOffset;
676 }
677
678 // instant scrolling if distance too long
679 if(absolute(a: *pScrollOffsetChange) > 2.0f * ViewPortSize)
680 {
681 *pScrollOffset += *pScrollOffsetChange;
682 *pScrollOffsetChange = 0.0f;
683 }
684
685 // smooth scrolling
686 if(*pScrollOffsetChange)
687 {
688 const float Delta = *pScrollOffsetChange * std::clamp(val: Client()->RenderFrameTime() * ScrollSpeed, lo: 0.0f, hi: 1.0f);
689 *pScrollOffset += Delta;
690 *pScrollOffsetChange -= Delta;
691 }
692
693 // clamp to first item
694 if(*pScrollOffset < 0.0f)
695 {
696 if(SmoothClamp && *pScrollOffset < -0.1f)
697 {
698 *pScrollOffsetChange = -*pScrollOffset;
699 }
700 else
701 {
702 *pScrollOffset = 0.0f;
703 *pScrollOffsetChange = 0.0f;
704 }
705 }
706
707 // clamp to last item
708 if(TotalSize > ViewPortSize && *pScrollOffset > TotalSize - ViewPortSize)
709 {
710 if(SmoothClamp && *pScrollOffset - (TotalSize - ViewPortSize) > 0.1f)
711 {
712 *pScrollOffsetChange = (TotalSize - ViewPortSize) - *pScrollOffset;
713 }
714 else
715 {
716 *pScrollOffset = TotalSize - ViewPortSize;
717 *pScrollOffsetChange = 0.0f;
718 }
719 }
720}
721
722struct SCursorAndBoundingBox
723{
724 vec2 m_TextSize;
725 float m_BiggestCharacterHeight;
726 int m_LineCount;
727};
728
729static SCursorAndBoundingBox CalcFontSizeCursorHeightAndBoundingBox(ITextRender *pTextRender, const char *pText, int Flags, float &Size, float MaxWidth, const SLabelProperties &LabelProps)
730{
731 const float MaxTextWidth = LabelProps.m_MaxWidth != -1.0f ? LabelProps.m_MaxWidth : MaxWidth;
732 const int FlagsWithoutStop = Flags & ~(TEXTFLAG_STOP_AT_END | TEXTFLAG_ELLIPSIS_AT_END);
733 const float MaxTextWidthWithoutStop = Flags == FlagsWithoutStop ? LabelProps.m_MaxWidth : -1.0f;
734
735 float TextBoundingHeight = 0.0f;
736 float TextHeight = 0.0f;
737 int LineCount = 0;
738 STextSizeProperties TextSizeProps{};
739 TextSizeProps.m_pHeight = &TextHeight;
740 TextSizeProps.m_pMaxCharacterHeightInLine = &TextBoundingHeight;
741 TextSizeProps.m_pLineCount = &LineCount;
742
743 float TextWidth;
744 do
745 {
746 Size = maximum(a: Size, b: LabelProps.m_MinimumFontSize);
747 // Only consider stop-at-end and ellipsis-at-end when minimum font size reached or font scaling disabled
748 if((Size == LabelProps.m_MinimumFontSize || !LabelProps.m_EnableWidthCheck) && Flags != FlagsWithoutStop)
749 TextWidth = pTextRender->TextWidth(Size, pText, StrLength: -1, LineWidth: LabelProps.m_MaxWidth, Flags, TextSizeProps);
750 else
751 TextWidth = pTextRender->TextWidth(Size, pText, StrLength: -1, LineWidth: MaxTextWidthWithoutStop, Flags: FlagsWithoutStop, TextSizeProps);
752 if(TextWidth <= MaxTextWidth + 0.001f || !LabelProps.m_EnableWidthCheck || Size == LabelProps.m_MinimumFontSize)
753 break;
754 Size--;
755 } while(true);
756
757 SCursorAndBoundingBox Res{};
758 Res.m_TextSize = vec2(TextWidth, TextHeight);
759 Res.m_BiggestCharacterHeight = TextBoundingHeight;
760 Res.m_LineCount = LineCount;
761 return Res;
762}
763
764static int GetFlagsForLabelProperties(const SLabelProperties &LabelProps, const CTextCursor *pReadCursor)
765{
766 if(pReadCursor != nullptr)
767 return pReadCursor->m_Flags & ~TEXTFLAG_RENDER;
768
769 int Flags = 0;
770 Flags |= LabelProps.m_StopAtEnd ? TEXTFLAG_STOP_AT_END : 0;
771 Flags |= LabelProps.m_EllipsisAtEnd ? TEXTFLAG_ELLIPSIS_AT_END : 0;
772 return Flags;
773}
774
775vec2 CUi::CalcAlignedCursorPos(const CUIRect *pRect, vec2 TextSize, int Align, const float *pBiggestCharHeight)
776{
777 vec2 Cursor(pRect->x, pRect->y);
778
779 const int HorizontalAlign = Align & TEXTALIGN_MASK_HORIZONTAL;
780 if(HorizontalAlign == TEXTALIGN_CENTER)
781 {
782 Cursor.x += (pRect->w - TextSize.x) / 2.0f;
783 }
784 else if(HorizontalAlign == TEXTALIGN_RIGHT)
785 {
786 Cursor.x += pRect->w - TextSize.x;
787 }
788
789 const int VerticalAlign = Align & TEXTALIGN_MASK_VERTICAL;
790 if(VerticalAlign == TEXTALIGN_MIDDLE)
791 {
792 Cursor.y += pBiggestCharHeight != nullptr ? ((pRect->h - *pBiggestCharHeight) / 2.0f - (TextSize.y - *pBiggestCharHeight)) : (pRect->h - TextSize.y) / 2.0f;
793 }
794 else if(VerticalAlign == TEXTALIGN_BOTTOM)
795 {
796 Cursor.y += pRect->h - TextSize.y;
797 }
798
799 return Cursor;
800}
801
802CLabelResult CUi::DoLabel(const CUIRect *pRect, const char *pText, float Size, int Align, const SLabelProperties &LabelProps) const
803{
804 const int Flags = GetFlagsForLabelProperties(LabelProps, pReadCursor: nullptr);
805 const SCursorAndBoundingBox TextBounds = CalcFontSizeCursorHeightAndBoundingBox(pTextRender: TextRender(), pText, Flags, Size, MaxWidth: pRect->w, LabelProps);
806 const vec2 CursorPos = CalcAlignedCursorPos(pRect, TextSize: TextBounds.m_TextSize, Align, pBiggestCharHeight: TextBounds.m_LineCount == 1 ? &TextBounds.m_BiggestCharacterHeight : nullptr);
807
808 CTextCursor Cursor;
809 Cursor.SetPosition(CursorPos);
810 Cursor.m_FontSize = Size;
811 Cursor.m_Flags |= Flags;
812 Cursor.m_vColorSplits = LabelProps.m_vColorSplits;
813 Cursor.m_LineWidth = (float)LabelProps.m_MaxWidth;
814 TextRender()->TextEx(pCursor: &Cursor, pText, Length: -1);
815 return CLabelResult{.m_Truncated = Cursor.m_Truncated};
816}
817
818void CUi::DoLabel(CUIElement::SUIElementRect &RectEl, const CUIRect *pRect, const char *pText, float Size, int Align, const SLabelProperties &LabelProps, int StrLen, const CTextCursor *pReadCursor) const
819{
820 const int Flags = GetFlagsForLabelProperties(LabelProps, pReadCursor);
821 const SCursorAndBoundingBox TextBounds = CalcFontSizeCursorHeightAndBoundingBox(pTextRender: TextRender(), pText, Flags, Size, MaxWidth: pRect->w, LabelProps);
822
823 CTextCursor Cursor;
824 if(pReadCursor)
825 {
826 Cursor = *pReadCursor;
827 }
828 else
829 {
830 Cursor.SetPosition(CalcAlignedCursorPos(pRect, TextSize: TextBounds.m_TextSize, Align));
831 Cursor.m_FontSize = Size;
832 Cursor.m_Flags |= Flags;
833 }
834 Cursor.m_LineWidth = LabelProps.m_MaxWidth;
835
836 RectEl.m_TextColor = TextRender()->GetTextColor();
837 RectEl.m_TextOutlineColor = TextRender()->GetTextOutlineColor();
838 TextRender()->TextColor(Color: TextRender()->DefaultTextColor());
839 TextRender()->TextOutlineColor(Color: TextRender()->DefaultTextOutlineColor());
840 TextRender()->CreateTextContainer(TextContainerIndex&: RectEl.m_UITextContainer, pCursor: &Cursor, pText, Length: StrLen);
841 TextRender()->TextColor(Color: RectEl.m_TextColor);
842 TextRender()->TextOutlineColor(Color: RectEl.m_TextOutlineColor);
843 RectEl.m_Cursor = Cursor;
844}
845
846void CUi::DoLabelStreamed(CUIElement::SUIElementRect &RectEl, const CUIRect *pRect, const char *pText, float Size, int Align, const SLabelProperties &LabelProps, int StrLen, const CTextCursor *pReadCursor) const
847{
848 const int ReadCursorGlyphCount = pReadCursor == nullptr ? -1 : pReadCursor->m_GlyphCount;
849 bool NeedsRecreate = false;
850 bool ColorChanged = RectEl.m_TextColor != TextRender()->GetTextColor() || RectEl.m_TextOutlineColor != TextRender()->GetTextOutlineColor();
851 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)
852 {
853 NeedsRecreate = true;
854 }
855 else
856 {
857 if(StrLen <= -1)
858 {
859 if(str_comp(a: RectEl.m_Text.c_str(), b: pText) != 0)
860 NeedsRecreate = true;
861 }
862 else
863 {
864 if(StrLen != (int)RectEl.m_Text.size() || str_comp_num(a: RectEl.m_Text.c_str(), b: pText, num: StrLen) != 0)
865 NeedsRecreate = true;
866 }
867 }
868 RectEl.m_X = pRect->x;
869 RectEl.m_Y = pRect->y;
870 if(NeedsRecreate)
871 {
872 TextRender()->DeleteTextContainer(TextContainerIndex&: RectEl.m_UITextContainer);
873
874 RectEl.m_Width = pRect->w;
875 RectEl.m_Height = pRect->h;
876
877 if(StrLen > 0)
878 RectEl.m_Text = std::string(pText, StrLen);
879 else if(StrLen < 0)
880 RectEl.m_Text = pText;
881 else
882 RectEl.m_Text.clear();
883
884 RectEl.m_ReadCursorGlyphCount = ReadCursorGlyphCount;
885
886 CUIRect TmpRect;
887 TmpRect.x = 0;
888 TmpRect.y = 0;
889 TmpRect.w = pRect->w;
890 TmpRect.h = pRect->h;
891
892 DoLabel(RectEl, pRect: &TmpRect, pText, Size, Align: TEXTALIGN_TL, LabelProps, StrLen, pReadCursor);
893 }
894
895 if(RectEl.m_UITextContainer.Valid())
896 {
897 const vec2 CursorPos = CalcAlignedCursorPos(pRect, TextSize: vec2(RectEl.m_Cursor.m_LongestLineWidth, RectEl.m_Cursor.Height()), Align);
898 TextRender()->RenderTextContainer(TextContainerIndex: RectEl.m_UITextContainer, TextColor: RectEl.m_TextColor, TextOutlineColor: RectEl.m_TextOutlineColor, X: CursorPos.x, Y: CursorPos.y);
899 }
900}
901
902CLabelResult CUi::DoLabel_AutoLineSize(const char *pText, float FontSize, int Align, CUIRect *pRect, float LineSize, const SLabelProperties &LabelProps) const
903{
904 CUIRect LabelRect;
905 pRect->HSplitTop(Cut: LineSize, pTop: &LabelRect, pBottom: pRect);
906
907 return DoLabel(pRect: &LabelRect, pText, Size: FontSize, Align);
908}
909
910bool CUi::DoEditBox(CLineInput *pLineInput, const CUIRect *pRect, float FontSize, int Corners, const std::vector<STextColorSplit> &vColorSplits)
911{
912 const bool Inside = MouseHovered(pRect);
913 const bool Active = m_pLastActiveItem == pLineInput;
914 const bool Changed = pLineInput->WasChanged();
915 const bool CursorChanged = pLineInput->WasCursorChanged();
916
917 const float VSpacing = 2.0f;
918 CUIRect Textbox;
919 pRect->VMargin(Cut: VSpacing, pOtherRect: &Textbox);
920
921 bool JustGotActive = false;
922 if(CheckActiveItem(pId: pLineInput))
923 {
924 if(MouseButton(Index: 0))
925 {
926 if(pLineInput->IsActive() && (Input()->HasComposition() || Input()->GetCandidateCount()))
927 {
928 // Clear IME composition/candidates on mouse press
929 Input()->StopTextInput();
930 Input()->StartTextInput();
931 }
932 }
933 else
934 {
935 SetActiveItem(nullptr);
936 }
937 }
938 else if(HotItem() == pLineInput)
939 {
940 if(MouseButton(Index: 0))
941 {
942 if(!Active)
943 JustGotActive = true;
944 SetActiveItem(pLineInput);
945 }
946 }
947
948 if(Inside && !MouseButton(Index: 0))
949 SetHotItem(pLineInput);
950
951 if(Enabled() && Active && !JustGotActive)
952 pLineInput->Activate(Priority: EInputPriority::UI);
953 else
954 pLineInput->Deactivate();
955
956 float ScrollOffset = pLineInput->GetScrollOffset();
957 float ScrollOffsetChange = pLineInput->GetScrollOffsetChange();
958
959 // Update mouse selection information
960 CLineInput::SMouseSelection *pMouseSelection = pLineInput->GetMouseSelection();
961 if(Inside)
962 {
963 if(!pMouseSelection->m_Selecting && MouseButtonClicked(Index: 0))
964 {
965 pMouseSelection->m_Selecting = true;
966 pMouseSelection->m_PressMouse = MousePos();
967 pMouseSelection->m_Offset.x = ScrollOffset;
968 }
969 }
970 if(pMouseSelection->m_Selecting)
971 {
972 pMouseSelection->m_ReleaseMouse = MousePos();
973 if(!MouseButton(Index: 0))
974 {
975 pMouseSelection->m_Selecting = false;
976 if(Active)
977 {
978 Input()->EnsureScreenKeyboardShown();
979 }
980 }
981 }
982 if(ScrollOffset != pMouseSelection->m_Offset.x)
983 {
984 // When the scroll offset is changed, update the position that the mouse was pressed at,
985 // so the existing text selection still stays mostly the same.
986 // TODO: The selection may change by one character temporarily, due to different character widths.
987 // Needs text render adjustment: keep selection start based on character.
988 pMouseSelection->m_PressMouse.x -= ScrollOffset - pMouseSelection->m_Offset.x;
989 pMouseSelection->m_Offset.x = ScrollOffset;
990 }
991
992 // Render
993 pRect->Draw(Color: ms_LightButtonColorFunction.GetColor(Active, Hovered: HotItem() == pLineInput), Corners, Rounding: 3.0f);
994 ClipEnable(pRect);
995 Textbox.x -= ScrollOffset;
996 const STextBoundingBox BoundingBox = pLineInput->Render(pRect: &Textbox, FontSize, Align: TEXTALIGN_ML, Changed: Changed || CursorChanged, LineWidth: -1.0f, LineSpacing: 0.0f, vColorSplits);
997 ClipDisable();
998
999 // Scroll left or right if necessary
1000 if(Active && !JustGotActive && (Changed || CursorChanged || Input()->HasComposition()))
1001 {
1002 const float CaretPositionX = pLineInput->GetCaretPosition().x - Textbox.x - ScrollOffset - ScrollOffsetChange;
1003 if(CaretPositionX > Textbox.w)
1004 ScrollOffsetChange += CaretPositionX - Textbox.w;
1005 else if(CaretPositionX < 0.0f)
1006 ScrollOffsetChange += CaretPositionX;
1007 }
1008
1009 DoSmoothScrollLogic(pScrollOffset: &ScrollOffset, pScrollOffsetChange: &ScrollOffsetChange, ViewPortSize: Textbox.w, TotalSize: BoundingBox.m_W, SmoothClamp: true);
1010
1011 pLineInput->SetScrollOffset(ScrollOffset);
1012 pLineInput->SetScrollOffsetChange(ScrollOffsetChange);
1013
1014 return Changed;
1015}
1016
1017bool CUi::DoClearableEditBox(CLineInput *pLineInput, const CUIRect *pRect, float FontSize, int Corners, const std::vector<STextColorSplit> &vColorSplits)
1018{
1019 CUIRect EditBox, ClearButton;
1020 pRect->VSplitRight(Cut: pRect->h, pLeft: &EditBox, pRight: &ClearButton);
1021
1022 bool ReturnValue = DoEditBox(pLineInput, pRect: &EditBox, FontSize, Corners: Corners & ~IGraphics::CORNER_R, vColorSplits);
1023
1024 ClearButton.Draw(Color: ColorRGBA(1.0f, 1.0f, 1.0f, 0.33f * ButtonColorMul(pId: pLineInput->GetClearButtonId())), Corners: Corners & ~IGraphics::CORNER_L, Rounding: 3.0f);
1025 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);
1026 DoLabel(pRect: &ClearButton, pText: "×", Size: ClearButton.h * CUi::ms_FontmodHeight * 0.8f, Align: TEXTALIGN_MC);
1027 TextRender()->SetRenderFlags(0);
1028 if(DoButtonLogic(pId: pLineInput->GetClearButtonId(), Checked: 0, pRect: &ClearButton, Flags: BUTTONFLAG_LEFT))
1029 {
1030 pLineInput->Clear();
1031 SetActiveItem(pLineInput);
1032 ReturnValue = true;
1033 }
1034
1035 return ReturnValue;
1036}
1037
1038bool CUi::DoEditBox_Search(CLineInput *pLineInput, const CUIRect *pRect, float FontSize, bool HotkeyEnabled)
1039{
1040 CUIRect QuickSearch = *pRect;
1041 TextRender()->SetFontPreset(EFontPreset::ICON_FONT);
1042 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);
1043 DoLabel(pRect: &QuickSearch, pText: FontIcon::MAGNIFYING_GLASS, Size: FontSize, Align: TEXTALIGN_ML);
1044 const float SearchWidth = TextRender()->TextWidth(Size: FontSize, pText: FontIcon::MAGNIFYING_GLASS);
1045 TextRender()->SetRenderFlags(0);
1046 TextRender()->SetFontPreset(EFontPreset::DEFAULT_FONT);
1047 QuickSearch.VSplitLeft(Cut: SearchWidth + 5.0f, pLeft: nullptr, pRight: &QuickSearch);
1048 if(HotkeyEnabled && Input()->ModifierIsPressed() && Input()->KeyPress(Key: KEY_F))
1049 {
1050 SetActiveItem(pLineInput);
1051 pLineInput->SelectAll();
1052 }
1053 pLineInput->SetEmptyText(Localize(pStr: "Search"));
1054 return DoClearableEditBox(pLineInput, pRect: &QuickSearch, FontSize);
1055}
1056
1057int CUi::DoButton_Menu(CUIElement &UIElement, const CButtonContainer *pId, const std::function<const char *()> &GetTextLambda, const CUIRect *pRect, const SMenuButtonProperties &Props)
1058{
1059 CUIRect Text = *pRect, DropDownIcon;
1060 Text.HMargin(Cut: pRect->h >= 20.0f ? 2.0f : 1.0f, pOtherRect: &Text);
1061 Text.HMargin(Cut: (Text.h * Props.m_FontFactor) / 2.0f, pOtherRect: &Text);
1062 if(Props.m_ShowDropDownIcon)
1063 {
1064 Text.VSplitRight(Cut: pRect->h * 0.25f, pLeft: &Text, pRight: nullptr);
1065 Text.VSplitRight(Cut: pRect->h * 0.75f, pLeft: &Text, pRight: &DropDownIcon);
1066 }
1067
1068 if(!UIElement.AreRectsInit() || Props.m_HintRequiresStringCheck || Props.m_HintCanChangePositionOrSize || !UIElement.Rect(Index: 0)->m_UITextContainer.Valid())
1069 {
1070 bool NeedsRecalc = !UIElement.AreRectsInit() || !UIElement.Rect(Index: 0)->m_UITextContainer.Valid();
1071 if(Props.m_HintCanChangePositionOrSize)
1072 {
1073 if(UIElement.AreRectsInit())
1074 {
1075 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)
1076 {
1077 NeedsRecalc = true;
1078 }
1079 }
1080 }
1081 const char *pText = nullptr;
1082 if(Props.m_HintRequiresStringCheck)
1083 {
1084 if(UIElement.AreRectsInit())
1085 {
1086 pText = GetTextLambda();
1087 if(str_comp(a: UIElement.Rect(Index: 0)->m_Text.c_str(), b: pText) != 0)
1088 {
1089 NeedsRecalc = true;
1090 }
1091 }
1092 }
1093 if(NeedsRecalc)
1094 {
1095 if(!UIElement.AreRectsInit())
1096 {
1097 UIElement.InitRects(RequestedRectCount: 3);
1098 }
1099 ResetUIElement(UIElement);
1100
1101 for(int i = 0; i < 3; ++i)
1102 {
1103 ColorRGBA Color = Props.m_Color;
1104 if(i == 0)
1105 Color.a *= ButtonColorMulActive();
1106 else if(i == 1)
1107 Color.a *= ButtonColorMulHot();
1108 else if(i == 2)
1109 Color.a *= ButtonColorMulDefault();
1110 Graphics()->SetColor(Color);
1111
1112 CUIElement::SUIElementRect &NewRect = *UIElement.Rect(Index: i);
1113 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);
1114
1115 NewRect.m_X = pRect->x;
1116 NewRect.m_Y = pRect->y;
1117 NewRect.m_Width = pRect->w;
1118 NewRect.m_Height = pRect->h;
1119 NewRect.m_Rounding = Props.m_Rounding;
1120 NewRect.m_Corners = Props.m_Corners;
1121 if(i == 0)
1122 {
1123 if(pText == nullptr)
1124 pText = GetTextLambda();
1125 NewRect.m_Text = pText;
1126 if(Props.m_UseIconFont)
1127 TextRender()->SetFontPreset(EFontPreset::ICON_FONT);
1128 DoLabel(RectEl&: NewRect, pRect: &Text, pText, Size: Text.h * CUi::ms_FontmodHeight, Align: TEXTALIGN_MC);
1129 if(Props.m_UseIconFont)
1130 TextRender()->SetFontPreset(EFontPreset::DEFAULT_FONT);
1131 }
1132 }
1133 Graphics()->SetColor(r: 1.0f, g: 1.0f, b: 1.0f, a: 1.0f);
1134 }
1135 }
1136 // render
1137 size_t Index = 2;
1138 if(CheckActiveItem(pId))
1139 Index = 0;
1140 else if(HotItem() == pId)
1141 Index = 1;
1142 Graphics()->TextureClear();
1143 Graphics()->RenderQuadContainer(ContainerIndex: UIElement.Rect(Index)->m_UIRectQuadContainer, QuadDrawNum: -1);
1144 if(Props.m_ShowDropDownIcon)
1145 {
1146 TextRender()->SetFontPreset(EFontPreset::ICON_FONT);
1147 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);
1148 DoLabel(pRect: &DropDownIcon, pText: FontIcon::CIRCLE_CHEVRON_DOWN, Size: DropDownIcon.h * CUi::ms_FontmodHeight, Align: TEXTALIGN_MR);
1149 TextRender()->SetRenderFlags(0);
1150 TextRender()->SetFontPreset(EFontPreset::DEFAULT_FONT);
1151 }
1152 ColorRGBA ColorText(TextRender()->DefaultTextColor());
1153 ColorRGBA ColorTextOutline(TextRender()->DefaultTextOutlineColor());
1154 if(UIElement.Rect(Index: 0)->m_UITextContainer.Valid())
1155 TextRender()->RenderTextContainer(TextContainerIndex: UIElement.Rect(Index: 0)->m_UITextContainer, TextColor: ColorText, TextOutlineColor: ColorTextOutline);
1156 return DoButtonLogic(pId, Checked: Props.m_Checked, pRect, Flags: Props.m_Flags);
1157}
1158
1159int 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)
1160{
1161 pRect->Draw(Color: ButtonColor.value_or(u: ColorRGBA(1.0f, 1.0f, 1.0f, (Checked ? 0.1f : 0.5f) * ButtonColorMul(pId: pButtonContainer))), Corners, Rounding: 5.0f);
1162
1163 TextRender()->SetFontPreset(EFontPreset::ICON_FONT);
1164 TextRender()->SetRenderFlags(ETextRenderFlags::TEXT_RENDER_FLAG_ONLY_ADVANCE_WIDTH | ETextRenderFlags::TEXT_RENDER_FLAG_NO_X_BEARING | ETextRenderFlags::TEXT_RENDER_FLAG_NO_Y_BEARING);
1165 TextRender()->TextOutlineColor(Color: TextRender()->DefaultTextOutlineColor());
1166 TextRender()->TextColor(Color: TextRender()->DefaultTextColor());
1167
1168 CUIRect Label;
1169 pRect->HMargin(Cut: 2.0f, pOtherRect: &Label);
1170 DoLabel(pRect: &Label, pText, Size: Label.h * ms_FontmodHeight, Align: TEXTALIGN_MC);
1171
1172 if(!Enabled)
1173 {
1174 TextRender()->TextColor(Color: ColorRGBA(1.0f, 0.0f, 0.0f, 1.0f));
1175 TextRender()->TextOutlineColor(Color: ColorRGBA(0.0f, 0.0f, 0.0f, 0.0f));
1176 DoLabel(pRect: &Label, pText: FontIcon::SLASH, Size: Label.h * ms_FontmodHeight, Align: TEXTALIGN_MC);
1177 TextRender()->TextOutlineColor(Color: TextRender()->DefaultTextOutlineColor());
1178 TextRender()->TextColor(Color: TextRender()->DefaultTextColor());
1179 }
1180
1181 TextRender()->SetRenderFlags(0);
1182 TextRender()->SetFontPreset(EFontPreset::DEFAULT_FONT);
1183
1184 return DoButtonLogic(pId: pButtonContainer, Checked, pRect, Flags);
1185}
1186
1187int 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)
1188{
1189 if(!TransparentInactive || CheckActiveItem(pId: pButtonContainer) || HotItem() == pButtonContainer)
1190 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);
1191
1192 CUIRect Label;
1193 pRect->Margin(Cut: Padding, pOtherRect: &Label);
1194 DoLabel(pRect: &Label, pText, Size, Align);
1195
1196 return Enabled ? DoButtonLogic(pId: pButtonContainer, Checked: 0, pRect, Flags: BUTTONFLAG_LEFT) : 0;
1197}
1198
1199int64_t CUi::DoValueSelector(const void *pId, const CUIRect *pRect, const char *pLabel, int64_t Current, int64_t Min, int64_t Max, const SValueSelectorProperties &Props)
1200{
1201 return DoValueSelectorWithState(pId, pRect, pLabel, Current, Min, Max, Props).m_Value;
1202}
1203
1204SEditResult<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)
1205{
1206 // logic
1207 const bool Inside = MouseInside(pRect);
1208 const int Base = Props.m_IsHex ? 16 : 10;
1209
1210 if(HotItem() == pId && m_ActiveValueSelectorState.m_Button >= 0 && !MouseButton(Index: m_ActiveValueSelectorState.m_Button))
1211 {
1212 DisableMouseLock();
1213 if(CheckActiveItem(pId))
1214 {
1215 SetActiveItem(nullptr);
1216 }
1217 if(Inside && ((m_ActiveValueSelectorState.m_Button == 0 && !m_ActiveValueSelectorState.m_DidScroll && DoDoubleClickLogic(pId)) || m_ActiveValueSelectorState.m_Button == 1))
1218 {
1219 m_ActiveValueSelectorState.m_pLastTextId = pId;
1220 m_ActiveValueSelectorState.m_NumberInput.SetInteger64(Number: Current, Base, HexPrefix: Props.m_HexPrefix);
1221 m_ActiveValueSelectorState.m_NumberInput.SelectAll();
1222 }
1223 m_ActiveValueSelectorState.m_Button = -1;
1224 }
1225
1226 if(m_ActiveValueSelectorState.m_pLastTextId == pId)
1227 {
1228 SetActiveItem(&m_ActiveValueSelectorState.m_NumberInput);
1229 DoEditBox(pLineInput: &m_ActiveValueSelectorState.m_NumberInput, pRect, FontSize: 10.0f);
1230
1231 if(ConsumeHotkey(Hotkey: HOTKEY_ENTER) || ((MouseButtonClicked(Index: 1) || MouseButtonClicked(Index: 0)) && !Inside))
1232 {
1233 Current = std::clamp(val: m_ActiveValueSelectorState.m_NumberInput.GetInteger64(Base), lo: Min, hi: Max);
1234 DisableMouseLock();
1235 SetActiveItem(nullptr);
1236 m_ActiveValueSelectorState.m_pLastTextId = nullptr;
1237 }
1238
1239 if(ConsumeHotkey(Hotkey: HOTKEY_ESCAPE))
1240 {
1241 DisableMouseLock();
1242 SetActiveItem(nullptr);
1243 m_ActiveValueSelectorState.m_pLastTextId = nullptr;
1244 }
1245 }
1246 else
1247 {
1248 if(CheckActiveItem(pId))
1249 {
1250 dbg_assert(m_ActiveValueSelectorState.m_Button >= 0, "m_ActiveValueSelectorState.m_Button invalid");
1251 if(Props.m_UseScroll && m_ActiveValueSelectorState.m_Button == 0 && MouseButton(Index: 0))
1252 {
1253 m_ActiveValueSelectorState.m_ScrollValue += MouseDeltaX() * (Input()->ShiftIsPressed() ? 0.05f : 1.0f);
1254
1255 if(absolute(a: m_ActiveValueSelectorState.m_ScrollValue) > Props.m_Scale)
1256 {
1257 const int64_t Count = (int64_t)(m_ActiveValueSelectorState.m_ScrollValue / Props.m_Scale);
1258 m_ActiveValueSelectorState.m_ScrollValue = std::fmod(x: m_ActiveValueSelectorState.m_ScrollValue, y: Props.m_Scale);
1259 Current += Props.m_Step * Count;
1260 Current = std::clamp(val: Current, lo: Min, hi: Max);
1261 m_ActiveValueSelectorState.m_DidScroll = true;
1262
1263 // Constrain to discrete steps
1264 if(Count > 0)
1265 Current = Current / Props.m_Step * Props.m_Step;
1266 else
1267 Current = std::ceil(x: Current / (float)Props.m_Step) * Props.m_Step;
1268 }
1269 }
1270 }
1271 else if(HotItem() == pId)
1272 {
1273 if(MouseButton(Index: 0))
1274 {
1275 m_ActiveValueSelectorState.m_Button = 0;
1276 m_ActiveValueSelectorState.m_DidScroll = false;
1277 m_ActiveValueSelectorState.m_ScrollValue = 0.0f;
1278 SetActiveItem(pId);
1279 if(Props.m_UseScroll)
1280 EnableMouseLock(pId);
1281 }
1282 else if(MouseButton(Index: 1))
1283 {
1284 m_ActiveValueSelectorState.m_Button = 1;
1285 SetActiveItem(pId);
1286 }
1287 }
1288
1289 // render
1290 char aBuf[128];
1291 if(pLabel[0] != '\0')
1292 {
1293 if(Props.m_IsHex)
1294 str_format(aBuf, sizeof(aBuf), "%s #%0*" PRIX64, pLabel, Props.m_HexPrefix, Current);
1295 else
1296 str_format(aBuf, sizeof(aBuf), "%s %" PRId64, pLabel, Current);
1297 }
1298 else
1299 {
1300 if(Props.m_IsHex)
1301 str_format(aBuf, sizeof(aBuf), "#%0*" PRIX64, Props.m_HexPrefix, Current);
1302 else
1303 str_format(aBuf, sizeof(aBuf), "%" PRId64, Current);
1304 }
1305 pRect->Draw(Color: Props.m_Color, Corners: IGraphics::CORNER_ALL, Rounding: 3.0f);
1306 DoLabel(pRect, pText: aBuf, Size: 10.0f, Align: TEXTALIGN_MC);
1307 }
1308
1309 if(Inside && !MouseButton(Index: 0) && !MouseButton(Index: 1))
1310 SetHotItem(pId);
1311
1312 EEditState State = EEditState::NONE;
1313 if(m_pLastEditingItem == pId)
1314 {
1315 State = EEditState::EDITING;
1316 }
1317 if(((CheckActiveItem(pId) && CheckMouseLock()) || m_ActiveValueSelectorState.m_pLastTextId == pId) && m_pLastEditingItem != pId)
1318 {
1319 State = EEditState::START;
1320 m_pLastEditingItem = pId;
1321 }
1322 if(!CheckMouseLock() && m_ActiveValueSelectorState.m_pLastTextId != pId && m_pLastEditingItem == pId)
1323 {
1324 State = EEditState::END;
1325 m_pLastEditingItem = nullptr;
1326 }
1327
1328 return SEditResult<int64_t>{.m_State: State, .m_Value: Current};
1329}
1330
1331float CUi::DoScrollbarV(const void *pId, const CUIRect *pRect, float Current)
1332{
1333 Current = std::clamp(val: Current, lo: 0.0f, hi: 1.0f);
1334
1335 // layout
1336 CUIRect Rail;
1337 pRect->Margin(Cut: 5.0f, pOtherRect: &Rail);
1338
1339 CUIRect Handle;
1340 Rail.HSplitTop(Cut: std::clamp(val: 33.0f, lo: Rail.w, hi: Rail.h / 3.0f), pTop: &Handle, pBottom: nullptr);
1341 Handle.y = Rail.y + (Rail.h - Handle.h) * Current;
1342
1343 // logic
1344 const bool InsideRail = MouseHovered(pRect: &Rail);
1345 const bool InsideHandle = MouseHovered(pRect: &Handle);
1346 bool Grabbed = false; // whether to apply the offset
1347
1348 if(CheckActiveItem(pId))
1349 {
1350 if(MouseButton(Index: 0))
1351 {
1352 Grabbed = true;
1353 if(Input()->ShiftIsPressed())
1354 m_MouseSlow = true;
1355 }
1356 else
1357 {
1358 SetActiveItem(nullptr);
1359 }
1360 }
1361 else if(HotItem() == pId)
1362 {
1363 if(InsideHandle)
1364 {
1365 if(MouseButton(Index: 0))
1366 {
1367 SetActiveItem(pId);
1368 m_ActiveScrollbarOffset = MouseY() - Handle.y;
1369 Grabbed = true;
1370 }
1371 }
1372 else if(MouseButtonClicked(Index: 0))
1373 {
1374 SetActiveItem(pId);
1375 m_ActiveScrollbarOffset = Handle.h / 2.0f;
1376 Grabbed = true;
1377 }
1378 }
1379
1380 if(InsideRail && !MouseButton(Index: 0))
1381 {
1382 SetHotItem(pId);
1383 }
1384
1385 float ReturnValue = Current;
1386 if(Grabbed)
1387 {
1388 const float Min = Rail.y;
1389 const float Max = Rail.h - Handle.h;
1390 const float Cur = MouseY() - m_ActiveScrollbarOffset;
1391 ReturnValue = std::clamp(val: (Cur - Min) / Max, lo: 0.0f, hi: 1.0f);
1392 }
1393
1394 // render
1395 Rail.Draw(Color: ColorRGBA(1.0f, 1.0f, 1.0f, 0.25f), Corners: IGraphics::CORNER_ALL, Rounding: Rail.w / 2.0f);
1396 Handle.Draw(Color: ms_ScrollBarColorFunction.GetColor(Active: CheckActiveItem(pId), Hovered: HotItem() == pId), Corners: IGraphics::CORNER_ALL, Rounding: Handle.w / 2.0f);
1397
1398 return ReturnValue;
1399}
1400
1401float CUi::DoScrollbarH(const void *pId, const CUIRect *pRect, float Current, const ColorRGBA *pColorInner)
1402{
1403 Current = std::clamp(val: Current, lo: 0.0f, hi: 1.0f);
1404
1405 // layout
1406 CUIRect Rail;
1407 if(pColorInner)
1408 Rail = *pRect;
1409 else
1410 pRect->HMargin(Cut: 5.0f, pOtherRect: &Rail);
1411
1412 CUIRect Handle;
1413 Rail.VSplitLeft(Cut: pColorInner ? 8.0f : std::clamp(val: 33.0f, lo: Rail.h, hi: Rail.w / 3.0f), pLeft: &Handle, pRight: nullptr);
1414 Handle.x += (Rail.w - Handle.w) * Current;
1415
1416 CUIRect HandleArea = Handle;
1417 if(!pColorInner)
1418 {
1419 HandleArea.h = pRect->h * 0.9f;
1420 HandleArea.y = pRect->y + pRect->h * 0.05f;
1421 HandleArea.w += 6.0f;
1422 HandleArea.x -= 3.0f;
1423 }
1424
1425 // logic
1426 const bool InsideRail = MouseHovered(pRect: &Rail);
1427 const bool InsideHandle = MouseHovered(pRect: &HandleArea);
1428 bool Grabbed = false; // whether to apply the offset
1429
1430 if(CheckActiveItem(pId))
1431 {
1432 if(MouseButton(Index: 0))
1433 {
1434 Grabbed = true;
1435 if(Input()->ShiftIsPressed())
1436 m_MouseSlow = true;
1437 }
1438 else
1439 {
1440 SetActiveItem(nullptr);
1441 }
1442 }
1443 else if(HotItem() == pId)
1444 {
1445 if(InsideHandle)
1446 {
1447 if(MouseButton(Index: 0))
1448 {
1449 SetActiveItem(pId);
1450 m_pLastActiveScrollbar = pId;
1451 m_ActiveScrollbarOffset = MouseX() - Handle.x;
1452 Grabbed = true;
1453 }
1454 }
1455 else if(MouseButtonClicked(Index: 0))
1456 {
1457 SetActiveItem(pId);
1458 m_pLastActiveScrollbar = pId;
1459 m_ActiveScrollbarOffset = Handle.w / 2.0f;
1460 Grabbed = true;
1461 }
1462 }
1463
1464 if(!pColorInner && (InsideHandle || Grabbed) && (CheckActiveItem(pId) || HotItem() == pId))
1465 {
1466 Handle.h += 3.0f;
1467 Handle.y -= 1.5f;
1468 }
1469
1470 if(InsideRail && !MouseButton(Index: 0))
1471 {
1472 SetHotItem(pId);
1473 }
1474
1475 float ReturnValue = Current;
1476 if(Grabbed)
1477 {
1478 const float Min = Rail.x;
1479 const float Max = Rail.w - Handle.w;
1480 const float Cur = MouseX() - m_ActiveScrollbarOffset;
1481 ReturnValue = std::clamp(val: (Cur - Min) / Max, lo: 0.0f, hi: 1.0f);
1482 }
1483
1484 // render
1485 const ColorRGBA HandleColor = ms_ScrollBarColorFunction.GetColor(Active: CheckActiveItem(pId), Hovered: HotItem() == pId);
1486 if(pColorInner)
1487 {
1488 CUIRect Slider;
1489 Handle.VMargin(Cut: -2.0f, pOtherRect: &Slider);
1490 Slider.HMargin(Cut: -3.0f, pOtherRect: &Slider);
1491 Slider.Draw(Color: ColorRGBA(0.15f, 0.15f, 0.15f, 1.0f).Multiply(Other: HandleColor), Corners: IGraphics::CORNER_ALL, Rounding: 5.0f);
1492 Slider.Margin(Cut: 2.0f, pOtherRect: &Slider);
1493 Slider.Draw(Color: pColorInner->Multiply(Other: HandleColor), Corners: IGraphics::CORNER_ALL, Rounding: 3.0f);
1494 }
1495 else
1496 {
1497 Rail.Draw(Color: ColorRGBA(1.0f, 1.0f, 1.0f, 0.25f), Corners: IGraphics::CORNER_ALL, Rounding: Rail.h / 2.0f);
1498 Handle.Draw(Color: HandleColor, Corners: IGraphics::CORNER_ALL, Rounding: Rail.h / 2.0f);
1499 }
1500
1501 return ReturnValue;
1502}
1503
1504bool 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)
1505{
1506 const bool Infinite = Flags & CUi::SCROLLBAR_OPTION_INFINITE;
1507 const bool NoClampValue = Flags & CUi::SCROLLBAR_OPTION_NOCLAMPVALUE;
1508 const bool MultiLine = Flags & CUi::SCROLLBAR_OPTION_MULTILINE;
1509 const bool DelayUpdate = Flags & CUi::SCROLLBAR_OPTION_DELAYUPDATE;
1510
1511 int PrevValue = (DelayUpdate && m_pLastActiveScrollbar == pId && CheckActiveItem(pId)) ? m_ScrollbarValue : *pOption;
1512 int Value = PrevValue;
1513 if(Infinite)
1514 {
1515 Max += 1;
1516 if(Value == 0)
1517 Value = Max;
1518 }
1519
1520 char aBuf[256];
1521 if(!Infinite || Value != Max)
1522 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "%s: %i%s", pStr, Value, pSuffix);
1523 else
1524 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "%s: ∞", pStr);
1525
1526 if(NoClampValue)
1527 {
1528 // clamp the value internally for the scrollbar
1529 Value = std::clamp(val: Value, lo: Min, hi: Max);
1530 }
1531
1532 CUIRect Label, ScrollBar;
1533 if(MultiLine)
1534 pRect->HSplitMid(pTop: &Label, pBottom: &ScrollBar);
1535 else
1536 pRect->VSplitMid(pLeft: &Label, pRight: &ScrollBar, Spacing: minimum(a: 10.0f, b: pRect->w * 0.05f));
1537
1538 const float FontSize = Label.h * CUi::ms_FontmodHeight * 0.8f;
1539 DoLabel(pRect: &Label, pText: aBuf, Size: FontSize, Align: TEXTALIGN_ML);
1540
1541 Value = pScale->ToAbsolute(RelativeValue: DoScrollbarH(pId, pRect: &ScrollBar, Current: pScale->ToRelative(AbsoluteValue: Value, Min, Max)), Min, Max);
1542 if(NoClampValue && ((Value == Min && PrevValue < Min) || (Value == Max && PrevValue > Max)))
1543 {
1544 Value = PrevValue; // use previous out of range value instead if the scrollbar is at the edge
1545 }
1546 else if(Infinite)
1547 {
1548 if(Value == Max)
1549 Value = 0;
1550 }
1551
1552 if(DelayUpdate && m_pLastActiveScrollbar == pId && CheckActiveItem(pId))
1553 {
1554 m_ScrollbarValue = Value;
1555 return false;
1556 }
1557
1558 if(*pOption != Value)
1559 {
1560 *pOption = Value;
1561 return true;
1562 }
1563 return false;
1564}
1565
1566void CUi::RenderProgressBar(CUIRect ProgressBar, float Progress)
1567{
1568 const float Rounding = minimum(a: 5.0f, b: ProgressBar.h / 2.0f);
1569 ProgressBar.Draw(Color: ColorRGBA(1.0f, 1.0f, 1.0f, 0.25f), Corners: IGraphics::CORNER_ALL, Rounding);
1570 ProgressBar.w = maximum(a: ProgressBar.w * Progress, b: 2 * Rounding);
1571 ProgressBar.Draw(Color: ColorRGBA(1.0f, 1.0f, 1.0f, 0.5f), Corners: IGraphics::CORNER_ALL, Rounding);
1572}
1573
1574void CUi::RenderTime(CUIRect TimeRect, float FontSize, int Seconds, bool NotFinished, int Millis, bool TrueMilliseconds) const
1575{
1576 if(NotFinished)
1577 return;
1578
1579 char aBuf[128];
1580
1581 str_time(centisecs: ((int64_t)absolute(a: Seconds)) * 100, format: ETimeFormat::HOURS, buffer: aBuf, buffer_size: sizeof(aBuf));
1582
1583 // align in vertical middle
1584 vec2 Cursor = TimeRect.TopLeft();
1585 float TextHeight = 0.0f;
1586 float SecondsMaxHeight = 0.0f;
1587 STextSizeProperties TextSizeProps{};
1588 TextSizeProps.m_pMaxCharacterHeightInLine = &SecondsMaxHeight;
1589 TextSizeProps.m_pHeight = &TextHeight;
1590
1591 float SecondsWidth = std::min(a: TextRender()->TextWidth(Size: FontSize, pText: aBuf, StrLength: -1, LineWidth: -1.0f, Flags: 0, TextSizeProps), b: TimeRect.w);
1592 Cursor.x += TimeRect.w - SecondsWidth; // align right
1593 Cursor.y += ((TimeRect.h - SecondsMaxHeight) / 2.0f - (FontSize - SecondsMaxHeight));
1594
1595 // show milliseconds or centiseconds if we are under an hour
1596 if(Millis >= 0 && Seconds < 60 * 60)
1597 {
1598 constexpr float GoldenRatio = 0.61803398875f;
1599 const float CentisecondFontSize = FontSize * GoldenRatio;
1600
1601 // format 2 or 3 digits
1602 char aMillis[4];
1603 Millis %= 1000;
1604 if(!TrueMilliseconds)
1605 str_format(buffer: aMillis, buffer_size: sizeof(aMillis), format: "%02d", (int)std::round(x: Millis / 10));
1606 else
1607 str_format(buffer: aMillis, buffer_size: sizeof(aMillis), format: "%03d", Millis);
1608
1609 float MillisWidth = TextRender()->TextWidth(Size: CentisecondFontSize, pText: aMillis, StrLength: -1, LineWidth: -1.0f, Flags: 0, TextSizeProps);
1610
1611 // make space for millis, but put them 1/6th of a char tighter together
1612 Cursor.x -= MillisWidth - (TrueMilliseconds ? MillisWidth / (3 * 6) : MillisWidth / (2 * 6));
1613
1614 vec2 CursorMillis = TimeRect.TopLeft();
1615 CursorMillis.x += TimeRect.w - MillisWidth; // align right
1616 CursorMillis.y += ((TimeRect.h - SecondsMaxHeight) / 2.0f - (CentisecondFontSize - SecondsMaxHeight));
1617 CursorMillis.y -= (CursorMillis.y - Cursor.y) * GoldenRatio;
1618
1619 TextRender()->Text(x: Cursor.x, y: Cursor.y, Size: FontSize, pText: aBuf);
1620 TextRender()->Text(x: CursorMillis.x, y: CursorMillis.y, Size: CentisecondFontSize, pText: aMillis);
1621 }
1622 else
1623 {
1624 str_time(centisecs: ((int64_t)absolute(a: Seconds)) * 100, format: ETimeFormat::HOURS, buffer: aBuf, buffer_size: sizeof(aBuf));
1625 TextRender()->Text(x: Cursor.x, y: Cursor.y, Size: FontSize, pText: aBuf);
1626 }
1627}
1628
1629void CUi::RenderProgressSpinner(vec2 Center, float OuterRadius, const SProgressSpinnerProperties &Props) const
1630{
1631 Graphics()->TextureClear();
1632 Graphics()->QuadsBegin();
1633
1634 // The filled and unfilled segments need to begin at the same angle offset
1635 // or the differences in pixel alignment will make the filled segments flicker.
1636 const float SegmentsAngle = 2.0f * pi / Props.m_Segments;
1637 const float InnerRadius = OuterRadius * 0.75f;
1638 const float AngleOffset = -0.5f * pi;
1639 Graphics()->SetColor(Props.m_Color.WithMultipliedAlpha(alpha: 0.5f));
1640 for(int i = 0; i < Props.m_Segments; ++i)
1641 {
1642 const vec2 Dir1 = direction(angle: AngleOffset + i * SegmentsAngle);
1643 const vec2 Dir2 = direction(angle: AngleOffset + (i + 1) * SegmentsAngle);
1644 IGraphics::CFreeformItem Item = IGraphics::CFreeformItem(
1645 Center + Dir1 * InnerRadius, Center + Dir2 * InnerRadius,
1646 Center + Dir1 * OuterRadius, Center + Dir2 * OuterRadius);
1647 Graphics()->QuadsDrawFreeform(pArray: &Item, Num: 1);
1648 }
1649
1650 const float FilledRatio = Props.m_Progress < 0.0f ? 0.333f : Props.m_Progress;
1651 const int FilledSegmentOffset = Props.m_Progress < 0.0f ? round_to_int(f: m_ProgressSpinnerOffset * Props.m_Segments) : 0;
1652 const int FilledNumSegments = minimum<int>(a: Props.m_Segments * FilledRatio + (Props.m_Progress < 0.0f ? 0 : 1), b: Props.m_Segments);
1653 Graphics()->SetColor(Props.m_Color);
1654 for(int i = 0; i < FilledNumSegments; ++i)
1655 {
1656 const float Angle1 = AngleOffset + (i + FilledSegmentOffset) * SegmentsAngle;
1657 const float Angle2 = AngleOffset + ((i + 1 == FilledNumSegments && Props.m_Progress >= 0.0f) ? (2.0f * pi * Props.m_Progress) : ((i + FilledSegmentOffset + 1) * SegmentsAngle));
1658 IGraphics::CFreeformItem Item = IGraphics::CFreeformItem(
1659 Center.x + std::cos(x: Angle1) * InnerRadius, Center.y + std::sin(x: Angle1) * InnerRadius,
1660 Center.x + std::cos(x: Angle2) * InnerRadius, Center.y + std::sin(x: Angle2) * InnerRadius,
1661 Center.x + std::cos(x: Angle1) * OuterRadius, Center.y + std::sin(x: Angle1) * OuterRadius,
1662 Center.x + std::cos(x: Angle2) * OuterRadius, Center.y + std::sin(x: Angle2) * OuterRadius);
1663 Graphics()->QuadsDrawFreeform(pArray: &Item, Num: 1);
1664 }
1665
1666 Graphics()->QuadsEnd();
1667}
1668
1669void CUi::DoPopupMenu(const SPopupMenuId *pId, float X, float Y, float Width, float Height, void *pContext, FPopupMenuFunction pfnFunc, const SPopupMenuProperties &Props)
1670{
1671 constexpr float Margin = SPopupMenu::POPUP_BORDER + SPopupMenu::POPUP_MARGIN;
1672 if(X + Width > Screen()->w - Margin)
1673 X = maximum<float>(a: X - Width, b: Margin);
1674 if(Y + Height > Screen()->h - Margin)
1675 Y = maximum<float>(a: Y - Height, b: Margin);
1676
1677 m_vPopupMenus.emplace_back();
1678 SPopupMenu *pNewMenu = &m_vPopupMenus.back();
1679 pNewMenu->m_pId = pId;
1680 pNewMenu->m_Props = Props;
1681 pNewMenu->m_Rect.x = X;
1682 pNewMenu->m_Rect.y = Y;
1683 pNewMenu->m_Rect.w = Width;
1684 pNewMenu->m_Rect.h = Height;
1685 pNewMenu->m_pContext = pContext;
1686 pNewMenu->m_pfnFunc = pfnFunc;
1687}
1688
1689void CUi::RenderPopupMenus()
1690{
1691 for(size_t i = 0; i < m_vPopupMenus.size(); ++i)
1692 {
1693 const SPopupMenu &PopupMenu = m_vPopupMenus[i];
1694 const SPopupMenuId *pId = PopupMenu.m_pId;
1695 const bool Inside = MouseInside(pRect: &PopupMenu.m_Rect);
1696 const bool Active = i == m_vPopupMenus.size() - 1;
1697
1698 if(Active)
1699 {
1700 // Prevent UI elements below the popup menu from being activated.
1701 SetHotItem(pId);
1702 }
1703
1704 if(CheckActiveItem(pId))
1705 {
1706 if(!MouseButton(Index: 0))
1707 {
1708 if(!Inside)
1709 {
1710 ClosePopupMenu(pId);
1711 --i;
1712 continue;
1713 }
1714 SetActiveItem(nullptr);
1715 }
1716 }
1717 else if(HotItem() == pId)
1718 {
1719 if(MouseButton(Index: 0))
1720 SetActiveItem(pId);
1721 }
1722
1723 if(Inside)
1724 {
1725 // Prevent scroll regions directly behind popup menus from using the mouse scroll events.
1726 SetHotScrollRegion(nullptr);
1727 }
1728
1729 CUIRect PopupRect = PopupMenu.m_Rect;
1730 PopupRect.Draw(Color: PopupMenu.m_Props.m_BorderColor, Corners: PopupMenu.m_Props.m_Corners, Rounding: 3.0f);
1731 PopupRect.Margin(Cut: SPopupMenu::POPUP_BORDER, pOtherRect: &PopupRect);
1732 PopupRect.Draw(Color: PopupMenu.m_Props.m_BackgroundColor, Corners: PopupMenu.m_Props.m_Corners, Rounding: 3.0f);
1733 PopupRect.Margin(Cut: SPopupMenu::POPUP_MARGIN, pOtherRect: &PopupRect);
1734
1735 // The popup render function can open/close popups, which may resize the vector and thus
1736 // invalidate the variable PopupMenu. We therefore store pId in a separate variable.
1737 EPopupMenuFunctionResult Result = PopupMenu.m_pfnFunc(PopupMenu.m_pContext, PopupRect, Active);
1738 if(Result != POPUP_KEEP_OPEN || (Active && ConsumeHotkey(Hotkey: HOTKEY_ESCAPE)))
1739 ClosePopupMenu(pId, IncludeDescendants: Result == POPUP_CLOSE_CURRENT_AND_DESCENDANTS);
1740 }
1741}
1742
1743void CUi::ClosePopupMenu(const SPopupMenuId *pId, bool IncludeDescendants)
1744{
1745 auto PopupMenuToClose = std::find_if(first: m_vPopupMenus.begin(), last: m_vPopupMenus.end(), pred: [pId](const SPopupMenu PopupMenu) { return PopupMenu.m_pId == pId; });
1746 if(PopupMenuToClose != m_vPopupMenus.end())
1747 {
1748 if(IncludeDescendants)
1749 m_vPopupMenus.erase(first: PopupMenuToClose, last: m_vPopupMenus.end());
1750 else
1751 m_vPopupMenus.erase(position: PopupMenuToClose);
1752 SetActiveItem(nullptr);
1753 if(m_pfnPopupMenuClosedCallback)
1754 m_pfnPopupMenuClosedCallback();
1755 }
1756}
1757
1758void CUi::ClosePopupMenus()
1759{
1760 if(m_vPopupMenus.empty())
1761 return;
1762
1763 m_vPopupMenus.clear();
1764 SetActiveItem(nullptr);
1765 if(m_pfnPopupMenuClosedCallback)
1766 m_pfnPopupMenuClosedCallback();
1767}
1768
1769bool CUi::IsPopupOpen() const
1770{
1771 return !m_vPopupMenus.empty();
1772}
1773
1774bool CUi::IsPopupOpen(const SPopupMenuId *pId) const
1775{
1776 return std::any_of(first: m_vPopupMenus.begin(), last: m_vPopupMenus.end(), pred: [pId](const SPopupMenu PopupMenu) { return PopupMenu.m_pId == pId; });
1777}
1778
1779bool CUi::IsPopupHovered() const
1780{
1781 return std::any_of(first: m_vPopupMenus.begin(), last: m_vPopupMenus.end(), pred: [this](const SPopupMenu PopupMenu) { return MouseHovered(pRect: &PopupMenu.m_Rect); });
1782}
1783
1784void CUi::SetPopupMenuClosedCallback(FPopupMenuClosedCallback pfnCallback)
1785{
1786 m_pfnPopupMenuClosedCallback = std::move(pfnCallback);
1787}
1788
1789void CUi::SMessagePopupContext::DefaultColor(ITextRender *pTextRender)
1790{
1791 m_TextColor = pTextRender->DefaultTextColor();
1792}
1793
1794void CUi::SMessagePopupContext::ErrorColor()
1795{
1796 m_TextColor = ColorRGBA(1.0f, 0.0f, 0.0f, 1.0f);
1797}
1798
1799CUi::EPopupMenuFunctionResult CUi::PopupMessage(void *pContext, CUIRect View, bool Active)
1800{
1801 SMessagePopupContext *pMessagePopup = static_cast<SMessagePopupContext *>(pContext);
1802 CUi *pUI = pMessagePopup->m_pUI;
1803
1804 pUI->TextRender()->TextColor(Color: pMessagePopup->m_TextColor);
1805 pUI->TextRender()->Text(x: View.x, y: View.y, Size: SMessagePopupContext::POPUP_FONT_SIZE, pText: pMessagePopup->m_aMessage, LineWidth: View.w);
1806 pUI->TextRender()->TextColor(Color: pUI->TextRender()->DefaultTextColor());
1807
1808 return (Active && pUI->ConsumeHotkey(Hotkey: HOTKEY_ENTER)) ? CUi::POPUP_CLOSE_CURRENT : CUi::POPUP_KEEP_OPEN;
1809}
1810
1811void CUi::ShowPopupMessage(float X, float Y, SMessagePopupContext *pContext)
1812{
1813 const float TextWidth = minimum(a: std::ceil(x: TextRender()->TextWidth(Size: SMessagePopupContext::POPUP_FONT_SIZE, pText: pContext->m_aMessage, StrLength: -1, LineWidth: -1.0f) + 0.5f), b: SMessagePopupContext::POPUP_MAX_WIDTH);
1814 float TextHeight = 0.0f;
1815 STextSizeProperties TextSizeProps{};
1816 TextSizeProps.m_pHeight = &TextHeight;
1817 TextRender()->TextWidth(Size: SMessagePopupContext::POPUP_FONT_SIZE, pText: pContext->m_aMessage, StrLength: -1, LineWidth: TextWidth, Flags: 0, TextSizeProps);
1818 pContext->m_pUI = this;
1819 DoPopupMenu(pId: pContext, X, Y, Width: TextWidth + 10.0f, Height: TextHeight + 10.0f, pContext, pfnFunc: PopupMessage);
1820}
1821
1822CUi::SConfirmPopupContext::SConfirmPopupContext()
1823{
1824 Reset();
1825}
1826
1827void CUi::SConfirmPopupContext::Reset()
1828{
1829 m_Result = SConfirmPopupContext::UNSET;
1830}
1831
1832void CUi::SConfirmPopupContext::YesNoButtons()
1833{
1834 str_copy(dst&: m_aPositiveButtonLabel, src: Localize(pStr: "Yes"));
1835 str_copy(dst&: m_aNegativeButtonLabel, src: Localize(pStr: "No"));
1836}
1837
1838void CUi::ShowPopupConfirm(float X, float Y, SConfirmPopupContext *pContext)
1839{
1840 const float TextWidth = minimum(a: std::ceil(x: TextRender()->TextWidth(Size: SConfirmPopupContext::POPUP_FONT_SIZE, pText: pContext->m_aMessage, StrLength: -1, LineWidth: -1.0f) + 0.5f), b: SConfirmPopupContext::POPUP_MAX_WIDTH);
1841 float TextHeight = 0.0f;
1842 STextSizeProperties TextSizeProps{};
1843 TextSizeProps.m_pHeight = &TextHeight;
1844 TextRender()->TextWidth(Size: SConfirmPopupContext::POPUP_FONT_SIZE, pText: pContext->m_aMessage, StrLength: -1, LineWidth: TextWidth, Flags: 0, TextSizeProps);
1845 const float PopupHeight = TextHeight + SConfirmPopupContext::POPUP_BUTTON_HEIGHT + SConfirmPopupContext::POPUP_BUTTON_SPACING + 10.0f;
1846 pContext->m_pUI = this;
1847 pContext->m_Result = SConfirmPopupContext::UNSET;
1848 DoPopupMenu(pId: pContext, X, Y, Width: TextWidth + 10.0f, Height: PopupHeight, pContext, pfnFunc: PopupConfirm);
1849}
1850
1851CUi::EPopupMenuFunctionResult CUi::PopupConfirm(void *pContext, CUIRect View, bool Active)
1852{
1853 SConfirmPopupContext *pConfirmPopup = static_cast<SConfirmPopupContext *>(pContext);
1854 CUi *pUI = pConfirmPopup->m_pUI;
1855
1856 CUIRect Label, ButtonBar, CancelButton, ConfirmButton;
1857 View.HSplitBottom(Cut: SConfirmPopupContext::POPUP_BUTTON_HEIGHT, pTop: &Label, pBottom: &ButtonBar);
1858 ButtonBar.VSplitMid(pLeft: &CancelButton, pRight: &ConfirmButton, Spacing: SConfirmPopupContext::POPUP_BUTTON_SPACING);
1859
1860 pUI->TextRender()->Text(x: Label.x, y: Label.y, Size: SConfirmPopupContext::POPUP_FONT_SIZE, pText: pConfirmPopup->m_aMessage, LineWidth: Label.w);
1861
1862 if(pUI->DoButton_PopupMenu(pButtonContainer: &pConfirmPopup->m_CancelButton, pText: pConfirmPopup->m_aNegativeButtonLabel, pRect: &CancelButton, Size: SConfirmPopupContext::POPUP_FONT_SIZE, Align: TEXTALIGN_MC))
1863 {
1864 pConfirmPopup->m_Result = SConfirmPopupContext::CANCELED;
1865 return CUi::POPUP_CLOSE_CURRENT;
1866 }
1867
1868 if(pUI->DoButton_PopupMenu(pButtonContainer: &pConfirmPopup->m_ConfirmButton, pText: pConfirmPopup->m_aPositiveButtonLabel, pRect: &ConfirmButton, Size: SConfirmPopupContext::POPUP_FONT_SIZE, Align: TEXTALIGN_MC) || (Active && pUI->ConsumeHotkey(Hotkey: HOTKEY_ENTER)))
1869 {
1870 pConfirmPopup->m_Result = SConfirmPopupContext::CONFIRMED;
1871 return CUi::POPUP_CLOSE_CURRENT;
1872 }
1873
1874 return CUi::POPUP_KEEP_OPEN;
1875}
1876
1877CUi::SSelectionPopupContext::SSelectionPopupContext()
1878{
1879 Reset();
1880}
1881
1882void CUi::SSelectionPopupContext::Reset()
1883{
1884 m_Props = SPopupMenuProperties();
1885 m_aMessage[0] = '\0';
1886 m_pSelection = nullptr;
1887 m_SelectionIndex = -1;
1888 m_vEntries.clear();
1889 m_vButtonContainers.clear();
1890 m_EntryHeight = 12.0f;
1891 m_EntryPadding = 0.0f;
1892 m_EntrySpacing = 5.0f;
1893 m_FontSize = 10.0f;
1894 m_Width = 300.0f + (SPopupMenu::POPUP_BORDER + SPopupMenu::POPUP_MARGIN) * 2;
1895 m_AlignmentHeight = -1.0f;
1896 m_TransparentButtons = false;
1897}
1898
1899CUi::EPopupMenuFunctionResult CUi::PopupSelection(void *pContext, CUIRect View, bool Active)
1900{
1901 SSelectionPopupContext *pSelectionPopup = static_cast<SSelectionPopupContext *>(pContext);
1902 CUi *pUI = pSelectionPopup->m_pUI;
1903 CScrollRegion *pScrollRegion = pSelectionPopup->m_pScrollRegion;
1904
1905 CScrollRegionParams ScrollParams;
1906 ScrollParams.m_ScrollbarWidth = 10.0f;
1907 ScrollParams.m_ScrollbarMargin = SPopupMenu::POPUP_MARGIN;
1908 ScrollParams.m_ScrollbarNoMarginRight = true;
1909 ScrollParams.m_ScrollUnit = 3 * (pSelectionPopup->m_EntryHeight + pSelectionPopup->m_EntrySpacing);
1910 pScrollRegion->Begin(pClipRect: &View, pParams: &ScrollParams);
1911
1912 CUIRect Slot;
1913 if(pSelectionPopup->m_aMessage[0] != '\0')
1914 {
1915 const STextBoundingBox TextBoundingBox = pUI->TextRender()->TextBoundingBox(Size: pSelectionPopup->m_FontSize, pText: pSelectionPopup->m_aMessage, StrLength: -1, LineWidth: pSelectionPopup->m_Width);
1916 View.HSplitTop(Cut: TextBoundingBox.m_H, pTop: &Slot, pBottom: &View);
1917 if(pScrollRegion->AddRect(Rect: Slot))
1918 {
1919 pUI->TextRender()->Text(x: Slot.x, y: Slot.y, Size: pSelectionPopup->m_FontSize, pText: pSelectionPopup->m_aMessage, LineWidth: Slot.w);
1920 }
1921 }
1922
1923 pSelectionPopup->m_vButtonContainers.resize(sz: pSelectionPopup->m_vEntries.size());
1924
1925 size_t Index = 0;
1926 for(const auto &Entry : pSelectionPopup->m_vEntries)
1927 {
1928 if(pSelectionPopup->m_aMessage[0] != '\0' || Index != 0)
1929 View.HSplitTop(Cut: pSelectionPopup->m_EntrySpacing, pTop: nullptr, pBottom: &View);
1930 View.HSplitTop(Cut: pSelectionPopup->m_EntryHeight, pTop: &Slot, pBottom: &View);
1931 if(pScrollRegion->AddRect(Rect: Slot))
1932 {
1933 if(pUI->DoButton_PopupMenu(pButtonContainer: &pSelectionPopup->m_vButtonContainers[Index], pText: Entry.c_str(), pRect: &Slot, Size: pSelectionPopup->m_FontSize, Align: TEXTALIGN_ML, Padding: pSelectionPopup->m_EntryPadding, TransparentInactive: pSelectionPopup->m_TransparentButtons))
1934 {
1935 pSelectionPopup->m_pSelection = &Entry;
1936 pSelectionPopup->m_SelectionIndex = Index;
1937 }
1938 }
1939 ++Index;
1940 }
1941
1942 pScrollRegion->End();
1943
1944 return pSelectionPopup->m_pSelection == nullptr ? CUi::POPUP_KEEP_OPEN : CUi::POPUP_CLOSE_CURRENT;
1945}
1946
1947void CUi::ShowPopupSelection(float X, float Y, SSelectionPopupContext *pContext)
1948{
1949 const STextBoundingBox TextBoundingBox = TextRender()->TextBoundingBox(Size: pContext->m_FontSize, pText: pContext->m_aMessage, StrLength: -1, LineWidth: pContext->m_Width);
1950 const float PopupHeight = minimum(a: (pContext->m_aMessage[0] == '\0' ? -pContext->m_EntrySpacing : TextBoundingBox.m_H) + pContext->m_vEntries.size() * (pContext->m_EntryHeight + pContext->m_EntrySpacing) + (SPopupMenu::POPUP_BORDER + SPopupMenu::POPUP_MARGIN) * 2, b: Screen()->h * 0.4f);
1951 pContext->m_pUI = this;
1952 pContext->m_pSelection = nullptr;
1953 pContext->m_SelectionIndex = -1;
1954 pContext->m_Props.m_Corners = IGraphics::CORNER_ALL;
1955 if(pContext->m_AlignmentHeight >= 0.0f)
1956 {
1957 constexpr float Margin = SPopupMenu::POPUP_BORDER + SPopupMenu::POPUP_MARGIN;
1958 if(X + pContext->m_Width > Screen()->w - Margin)
1959 {
1960 X = maximum<float>(a: X - pContext->m_Width, b: Margin);
1961 }
1962 if(Y + pContext->m_AlignmentHeight + PopupHeight > Screen()->h - Margin)
1963 {
1964 Y -= PopupHeight;
1965 pContext->m_Props.m_Corners = IGraphics::CORNER_T;
1966 }
1967 else
1968 {
1969 Y += pContext->m_AlignmentHeight;
1970 pContext->m_Props.m_Corners = IGraphics::CORNER_B;
1971 }
1972 }
1973 DoPopupMenu(pId: pContext, X, Y, Width: pContext->m_Width, Height: PopupHeight, pContext, pfnFunc: PopupSelection, Props: pContext->m_Props);
1974}
1975
1976int CUi::DoDropDown(CUIRect *pRect, int CurSelection, const char **pStrs, int Num, SDropDownState &State)
1977{
1978 if(!State.m_Init)
1979 {
1980 State.m_UiElement.Init(pUI: this, RequestedRectCount: -1);
1981 State.m_Init = true;
1982 }
1983
1984 const auto LabelFunc = [CurSelection, pStrs]() {
1985 return CurSelection > -1 ? pStrs[CurSelection] : "";
1986 };
1987
1988 SMenuButtonProperties Props;
1989 Props.m_HintRequiresStringCheck = true;
1990 Props.m_HintCanChangePositionOrSize = true;
1991 Props.m_ShowDropDownIcon = true;
1992 if(IsPopupOpen(pId: &State.m_SelectionPopupContext))
1993 Props.m_Corners = IGraphics::CORNER_ALL & (~State.m_SelectionPopupContext.m_Props.m_Corners);
1994 if(DoButton_Menu(UIElement&: State.m_UiElement, pId: &State.m_ButtonContainer, GetTextLambda: LabelFunc, pRect, Props))
1995 {
1996 State.m_SelectionPopupContext.Reset();
1997 State.m_SelectionPopupContext.m_Props.m_BorderColor = ColorRGBA(0.7f, 0.7f, 0.7f, 0.9f);
1998 State.m_SelectionPopupContext.m_Props.m_BackgroundColor = ColorRGBA(0.0f, 0.0f, 0.0f, 0.25f);
1999 for(int i = 0; i < Num; ++i)
2000 State.m_SelectionPopupContext.m_vEntries.emplace_back(args&: pStrs[i]);
2001 State.m_SelectionPopupContext.m_EntryHeight = pRect->h;
2002 State.m_SelectionPopupContext.m_EntryPadding = pRect->h >= 20.0f ? 2.0f : 1.0f;
2003 State.m_SelectionPopupContext.m_FontSize = (State.m_SelectionPopupContext.m_EntryHeight - 2 * State.m_SelectionPopupContext.m_EntryPadding) * CUi::ms_FontmodHeight;
2004 State.m_SelectionPopupContext.m_Width = pRect->w;
2005 State.m_SelectionPopupContext.m_AlignmentHeight = pRect->h;
2006 State.m_SelectionPopupContext.m_TransparentButtons = true;
2007 ShowPopupSelection(X: pRect->x, Y: pRect->y, pContext: &State.m_SelectionPopupContext);
2008 }
2009
2010 if(State.m_SelectionPopupContext.m_SelectionIndex >= 0)
2011 {
2012 const int NewSelection = State.m_SelectionPopupContext.m_SelectionIndex;
2013 State.m_SelectionPopupContext.Reset();
2014 return NewSelection;
2015 }
2016
2017 return CurSelection;
2018}
2019
2020CUi::EPopupMenuFunctionResult CUi::PopupColorPicker(void *pContext, CUIRect View, bool Active)
2021{
2022 SColorPickerPopupContext *pColorPicker = static_cast<SColorPickerPopupContext *>(pContext);
2023 CUi *pUI = pColorPicker->m_pUI;
2024 pColorPicker->m_State = EEditState::NONE;
2025
2026 CUIRect ColorsArea, HueArea, BottomArea, ModeButtonArea, HueRect, SatRect, ValueRect, HexRect, AlphaRect;
2027
2028 View.HSplitTop(Cut: 140.0f, pTop: &ColorsArea, pBottom: &BottomArea);
2029 ColorsArea.VSplitRight(Cut: 20.0f, pLeft: &ColorsArea, pRight: &HueArea);
2030
2031 BottomArea.HSplitTop(Cut: 3.0f, pTop: nullptr, pBottom: &BottomArea);
2032 HueArea.VSplitLeft(Cut: 3.0f, pLeft: nullptr, pRight: &HueArea);
2033
2034 BottomArea.HSplitTop(Cut: 20.0f, pTop: &HueRect, pBottom: &BottomArea);
2035 BottomArea.HSplitTop(Cut: 3.0f, pTop: nullptr, pBottom: &BottomArea);
2036
2037 constexpr float ValuePadding = 5.0f;
2038 const float HsvValueWidth = (HueRect.w - ValuePadding * 2) / 3.0f;
2039 const float HexValueWidth = HsvValueWidth * 2 + ValuePadding;
2040
2041 HueRect.VSplitLeft(Cut: HsvValueWidth, pLeft: &HueRect, pRight: &SatRect);
2042 SatRect.VSplitLeft(Cut: ValuePadding, pLeft: nullptr, pRight: &SatRect);
2043 SatRect.VSplitLeft(Cut: HsvValueWidth, pLeft: &SatRect, pRight: &ValueRect);
2044 ValueRect.VSplitLeft(Cut: ValuePadding, pLeft: nullptr, pRight: &ValueRect);
2045
2046 BottomArea.HSplitTop(Cut: 20.0f, pTop: &HexRect, pBottom: &BottomArea);
2047 BottomArea.HSplitTop(Cut: 3.0f, pTop: nullptr, pBottom: &BottomArea);
2048 HexRect.VSplitLeft(Cut: HexValueWidth, pLeft: &HexRect, pRight: &AlphaRect);
2049 AlphaRect.VSplitLeft(Cut: ValuePadding, pLeft: nullptr, pRight: &AlphaRect);
2050 BottomArea.HSplitTop(Cut: 20.0f, pTop: &ModeButtonArea, pBottom: &BottomArea);
2051
2052 const ColorRGBA BlackColor = ColorRGBA(0.0f, 0.0f, 0.0f, 0.5f);
2053
2054 HueArea.Draw(Color: BlackColor, Corners: IGraphics::CORNER_NONE, Rounding: 0.0f);
2055 HueArea.Margin(Cut: 1.0f, pOtherRect: &HueArea);
2056
2057 ColorsArea.Draw(Color: BlackColor, Corners: IGraphics::CORNER_NONE, Rounding: 0.0f);
2058 ColorsArea.Margin(Cut: 1.0f, pOtherRect: &ColorsArea);
2059
2060 ColorHSVA PickerColorHSV = pColorPicker->m_HsvaColor;
2061 ColorRGBA PickerColorRGB = pColorPicker->m_RgbaColor;
2062 ColorHSLA PickerColorHSL = pColorPicker->m_HslaColor;
2063
2064 // Color Area
2065 ColorRGBA TL, TR, BL, BR;
2066 TL = BL = color_cast<ColorRGBA>(hsv: ColorHSVA(PickerColorHSV.x, 0.0f, 1.0f));
2067 TR = BR = color_cast<ColorRGBA>(hsv: ColorHSVA(PickerColorHSV.x, 1.0f, 1.0f));
2068 ColorsArea.Draw4(ColorTopLeft: TL, ColorTopRight: TR, ColorBottomLeft: BL, ColorBottomRight: BR, Corners: IGraphics::CORNER_NONE, Rounding: 0.0f);
2069
2070 TL = TR = ColorRGBA(0.0f, 0.0f, 0.0f, 0.0f);
2071 BL = BR = ColorRGBA(0.0f, 0.0f, 0.0f, 1.0f);
2072 ColorsArea.Draw4(ColorTopLeft: TL, ColorTopRight: TR, ColorBottomLeft: BL, ColorBottomRight: BR, Corners: IGraphics::CORNER_NONE, Rounding: 0.0f);
2073
2074 // Hue Area
2075 static const float s_aaColorIndices[7][3] = {
2076 {1.0f, 0.0f, 0.0f}, // red
2077 {1.0f, 0.0f, 1.0f}, // magenta
2078 {0.0f, 0.0f, 1.0f}, // blue
2079 {0.0f, 1.0f, 1.0f}, // cyan
2080 {0.0f, 1.0f, 0.0f}, // green
2081 {1.0f, 1.0f, 0.0f}, // yellow
2082 {1.0f, 0.0f, 0.0f}, // red
2083 };
2084
2085 const float HuePickerOffset = HueArea.h / 6.0f;
2086 CUIRect HuePartialArea = HueArea;
2087 HuePartialArea.h = HuePickerOffset;
2088
2089 for(size_t j = 0; j < std::size(s_aaColorIndices) - 1; j++)
2090 {
2091 TL = ColorRGBA(s_aaColorIndices[j][0], s_aaColorIndices[j][1], s_aaColorIndices[j][2], 1.0f);
2092 BL = ColorRGBA(s_aaColorIndices[j + 1][0], s_aaColorIndices[j + 1][1], s_aaColorIndices[j + 1][2], 1.0f);
2093
2094 HuePartialArea.y = HueArea.y + HuePickerOffset * j;
2095 HuePartialArea.Draw4(ColorTopLeft: TL, ColorTopRight: TL, ColorBottomLeft: BL, ColorBottomRight: BL, Corners: IGraphics::CORNER_NONE, Rounding: 0.0f);
2096 }
2097
2098 const auto &&RenderAlphaSelector = [&](unsigned OldA) -> SEditResult<int64_t> {
2099 if(pColorPicker->m_Alpha)
2100 {
2101 return pUI->DoValueSelectorWithState(pId: &pColorPicker->m_aValueSelectorIds[3], pRect: &AlphaRect, pLabel: "A:", Current: OldA, Min: 0, Max: 255);
2102 }
2103 else
2104 {
2105 char aBuf[8];
2106 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "A: %d", OldA);
2107 pUI->DoLabel(pRect: &AlphaRect, pText: aBuf, Size: 10.0f, Align: TEXTALIGN_MC);
2108 AlphaRect.Draw(Color: ColorRGBA(0.0f, 0.0f, 0.0f, 0.65f), Corners: IGraphics::CORNER_ALL, Rounding: 3.0f);
2109 return {.m_State: EEditState::NONE, .m_Value: OldA};
2110 }
2111 };
2112
2113 // Editboxes Area
2114 if(pColorPicker->m_ColorMode == SColorPickerPopupContext::MODE_HSVA)
2115 {
2116 const unsigned OldH = round_to_int(f: PickerColorHSV.h * 255.0f);
2117 const unsigned OldS = round_to_int(f: PickerColorHSV.s * 255.0f);
2118 const unsigned OldV = round_to_int(f: PickerColorHSV.v * 255.0f);
2119 const unsigned OldA = round_to_int(f: PickerColorHSV.a * 255.0f);
2120
2121 const auto [StateH, H] = pUI->DoValueSelectorWithState(pId: &pColorPicker->m_aValueSelectorIds[0], pRect: &HueRect, pLabel: "H:", Current: OldH, Min: 0, Max: 255);
2122 const auto [StateS, S] = pUI->DoValueSelectorWithState(pId: &pColorPicker->m_aValueSelectorIds[1], pRect: &SatRect, pLabel: "S:", Current: OldS, Min: 0, Max: 255);
2123 const auto [StateV, V] = pUI->DoValueSelectorWithState(pId: &pColorPicker->m_aValueSelectorIds[2], pRect: &ValueRect, pLabel: "V:", Current: OldV, Min: 0, Max: 255);
2124 const auto [StateA, A] = RenderAlphaSelector(OldA);
2125
2126 if(OldH != H || OldS != S || OldV != V || OldA != A)
2127 {
2128 PickerColorHSV = ColorHSVA(H / 255.0f, S / 255.0f, V / 255.0f, A / 255.0f);
2129 PickerColorHSL = color_cast<ColorHSLA>(hsv: PickerColorHSV);
2130 PickerColorRGB = color_cast<ColorRGBA>(hsl: PickerColorHSL);
2131 }
2132
2133 for(auto State : {StateH, StateS, StateV, StateA})
2134 {
2135 if(State != EEditState::NONE)
2136 {
2137 pColorPicker->m_State = State;
2138 break;
2139 }
2140 }
2141 }
2142 else if(pColorPicker->m_ColorMode == SColorPickerPopupContext::MODE_RGBA)
2143 {
2144 const unsigned OldR = round_to_int(f: PickerColorRGB.r * 255.0f);
2145 const unsigned OldG = round_to_int(f: PickerColorRGB.g * 255.0f);
2146 const unsigned OldB = round_to_int(f: PickerColorRGB.b * 255.0f);
2147 const unsigned OldA = round_to_int(f: PickerColorRGB.a * 255.0f);
2148
2149 const auto [StateR, R] = pUI->DoValueSelectorWithState(pId: &pColorPicker->m_aValueSelectorIds[0], pRect: &HueRect, pLabel: "R:", Current: OldR, Min: 0, Max: 255);
2150 const auto [StateG, G] = pUI->DoValueSelectorWithState(pId: &pColorPicker->m_aValueSelectorIds[1], pRect: &SatRect, pLabel: "G:", Current: OldG, Min: 0, Max: 255);
2151 const auto [StateB, B] = pUI->DoValueSelectorWithState(pId: &pColorPicker->m_aValueSelectorIds[2], pRect: &ValueRect, pLabel: "B:", Current: OldB, Min: 0, Max: 255);
2152 const auto [StateA, A] = RenderAlphaSelector(OldA);
2153
2154 if(OldR != R || OldG != G || OldB != B || OldA != A)
2155 {
2156 PickerColorRGB = ColorRGBA(R / 255.0f, G / 255.0f, B / 255.0f, A / 255.0f);
2157 PickerColorHSL = color_cast<ColorHSLA>(rgb: PickerColorRGB);
2158 PickerColorHSV = color_cast<ColorHSVA>(hsl: PickerColorHSL);
2159 }
2160
2161 for(auto State : {StateR, StateG, StateB, StateA})
2162 {
2163 if(State != EEditState::NONE)
2164 {
2165 pColorPicker->m_State = State;
2166 break;
2167 }
2168 }
2169 }
2170 else if(pColorPicker->m_ColorMode == SColorPickerPopupContext::MODE_HSLA)
2171 {
2172 const unsigned OldH = round_to_int(f: PickerColorHSL.h * 255.0f);
2173 const unsigned OldS = round_to_int(f: PickerColorHSL.s * 255.0f);
2174 const unsigned OldL = round_to_int(f: PickerColorHSL.l * 255.0f);
2175 const unsigned OldA = round_to_int(f: PickerColorHSL.a * 255.0f);
2176
2177 const auto [StateH, H] = pUI->DoValueSelectorWithState(pId: &pColorPicker->m_aValueSelectorIds[0], pRect: &HueRect, pLabel: "H:", Current: OldH, Min: 0, Max: 255);
2178 const auto [StateS, S] = pUI->DoValueSelectorWithState(pId: &pColorPicker->m_aValueSelectorIds[1], pRect: &SatRect, pLabel: "S:", Current: OldS, Min: 0, Max: 255);
2179 const auto [StateL, L] = pUI->DoValueSelectorWithState(pId: &pColorPicker->m_aValueSelectorIds[2], pRect: &ValueRect, pLabel: "L:", Current: OldL, Min: 0, Max: 255);
2180 const auto [StateA, A] = RenderAlphaSelector(OldA);
2181
2182 if(OldH != H || OldS != S || OldL != L || OldA != A)
2183 {
2184 PickerColorHSL = ColorHSLA(H / 255.0f, S / 255.0f, L / 255.0f, A / 255.0f);
2185 PickerColorHSV = color_cast<ColorHSVA>(hsl: PickerColorHSL);
2186 PickerColorRGB = color_cast<ColorRGBA>(hsl: PickerColorHSL);
2187 }
2188
2189 for(auto State : {StateH, StateS, StateL, StateA})
2190 {
2191 if(State != EEditState::NONE)
2192 {
2193 pColorPicker->m_State = State;
2194 break;
2195 }
2196 }
2197 }
2198 else
2199 {
2200 dbg_assert_failed("Color picker mode invalid: %d", (int)pColorPicker->m_ColorMode);
2201 }
2202
2203 SValueSelectorProperties Props;
2204 Props.m_UseScroll = false;
2205 Props.m_IsHex = true;
2206 Props.m_HexPrefix = pColorPicker->m_Alpha ? 8 : 6;
2207 const unsigned OldHex = PickerColorRGB.PackAlphaLast(Alpha: pColorPicker->m_Alpha);
2208 auto [HexState, Hex] = pUI->DoValueSelectorWithState(pId: &pColorPicker->m_aValueSelectorIds[4], pRect: &HexRect, pLabel: "Hex:", Current: OldHex, Min: 0, Max: pColorPicker->m_Alpha ? 0xFFFFFFFFll : 0xFFFFFFll, Props);
2209 if(OldHex != Hex)
2210 {
2211 const float OldAlpha = PickerColorRGB.a;
2212 PickerColorRGB = ColorRGBA::UnpackAlphaLast<ColorRGBA>(Color: Hex, Alpha: pColorPicker->m_Alpha);
2213 if(!pColorPicker->m_Alpha)
2214 PickerColorRGB.a = OldAlpha;
2215 PickerColorHSL = color_cast<ColorHSLA>(rgb: PickerColorRGB);
2216 PickerColorHSV = color_cast<ColorHSVA>(hsl: PickerColorHSL);
2217 }
2218
2219 if(HexState != EEditState::NONE)
2220 pColorPicker->m_State = HexState;
2221
2222 // Logic
2223 float PickerX, PickerY;
2224 EEditState ColorPickerRes = pUI->DoPickerLogic(pId: &pColorPicker->m_ColorPickerId, pRect: &ColorsArea, pX: &PickerX, pY: &PickerY);
2225 if(ColorPickerRes != EEditState::NONE)
2226 {
2227 PickerColorHSV.y = PickerX / ColorsArea.w;
2228 PickerColorHSV.z = 1.0f - PickerY / ColorsArea.h;
2229 PickerColorHSL = color_cast<ColorHSLA>(hsv: PickerColorHSV);
2230 PickerColorRGB = color_cast<ColorRGBA>(hsl: PickerColorHSL);
2231 pColorPicker->m_State = ColorPickerRes;
2232 }
2233
2234 EEditState HuePickerRes = pUI->DoPickerLogic(pId: &pColorPicker->m_HuePickerId, pRect: &HueArea, pX: &PickerX, pY: &PickerY);
2235 if(HuePickerRes != EEditState::NONE)
2236 {
2237 PickerColorHSV.x = 1.0f - PickerY / HueArea.h;
2238 PickerColorHSL = color_cast<ColorHSLA>(hsv: PickerColorHSV);
2239 PickerColorRGB = color_cast<ColorRGBA>(hsl: PickerColorHSL);
2240 pColorPicker->m_State = HuePickerRes;
2241 }
2242
2243 // Marker Color Area
2244 const float MarkerX = ColorsArea.x + ColorsArea.w * PickerColorHSV.y;
2245 const float MarkerY = ColorsArea.y + ColorsArea.h * (1.0f - PickerColorHSV.z);
2246
2247 const float MarkerOutlineInd = PickerColorHSV.z > 0.5f ? 0.0f : 1.0f;
2248 const ColorRGBA MarkerOutline = ColorRGBA(MarkerOutlineInd, MarkerOutlineInd, MarkerOutlineInd, 1.0f);
2249
2250 pUI->Graphics()->TextureClear();
2251 pUI->Graphics()->QuadsBegin();
2252 pUI->Graphics()->SetColor(MarkerOutline);
2253 pUI->Graphics()->DrawCircle(CenterX: MarkerX, CenterY: MarkerY, Radius: 4.5f, Segments: 32);
2254 pUI->Graphics()->SetColor(PickerColorRGB);
2255 pUI->Graphics()->DrawCircle(CenterX: MarkerX, CenterY: MarkerY, Radius: 3.5f, Segments: 32);
2256 pUI->Graphics()->QuadsEnd();
2257
2258 // Marker Hue Area
2259 CUIRect HueMarker;
2260 HueArea.Margin(Cut: -2.5f, pOtherRect: &HueMarker);
2261 HueMarker.h = 6.5f;
2262 HueMarker.y = (HueArea.y + HueArea.h * (1.0f - PickerColorHSV.x)) - HueMarker.h / 2.0f;
2263
2264 const ColorRGBA HueMarkerColor = color_cast<ColorRGBA>(hsv: ColorHSVA(PickerColorHSV.x, 1.0f, 1.0f, 1.0f));
2265 const float HueMarkerOutlineColor = PickerColorHSV.x > 0.75f ? 1.0f : 0.0f;
2266 const ColorRGBA HueMarkerOutline = ColorRGBA(HueMarkerOutlineColor, HueMarkerOutlineColor, HueMarkerOutlineColor, 1.0f);
2267
2268 HueMarker.Draw(Color: HueMarkerOutline, Corners: IGraphics::CORNER_ALL, Rounding: 1.2f);
2269 HueMarker.Margin(Cut: 1.2f, pOtherRect: &HueMarker);
2270 HueMarker.Draw(Color: HueMarkerColor, Corners: IGraphics::CORNER_ALL, Rounding: 1.2f);
2271
2272 pColorPicker->m_HsvaColor = PickerColorHSV;
2273 pColorPicker->m_RgbaColor = PickerColorRGB;
2274 pColorPicker->m_HslaColor = PickerColorHSL;
2275 if(pColorPicker->m_pHslaColor != nullptr)
2276 *pColorPicker->m_pHslaColor = PickerColorHSL.Pack(Alpha: pColorPicker->m_Alpha);
2277
2278 static constexpr SColorPickerPopupContext::EColorPickerMode PICKER_MODES[] = {SColorPickerPopupContext::MODE_HSVA, SColorPickerPopupContext::MODE_RGBA, SColorPickerPopupContext::MODE_HSLA};
2279 static constexpr const char *PICKER_MODE_LABELS[] = {"HSVA", "RGBA", "HSLA"};
2280 static_assert(std::size(PICKER_MODES) == std::size(PICKER_MODE_LABELS));
2281 for(SColorPickerPopupContext::EColorPickerMode Mode : PICKER_MODES)
2282 {
2283 CUIRect ModeButton;
2284 ModeButtonArea.VSplitLeft(Cut: HsvValueWidth, pLeft: &ModeButton, pRight: &ModeButtonArea);
2285 ModeButtonArea.VSplitLeft(Cut: ValuePadding, pLeft: nullptr, pRight: &ModeButtonArea);
2286 if(pUI->DoButton_PopupMenu(pButtonContainer: &pColorPicker->m_aModeButtons[(int)Mode], pText: PICKER_MODE_LABELS[Mode], pRect: &ModeButton, Size: 10.0f, Align: TEXTALIGN_MC, Padding: 2.0f, TransparentInactive: false, Enabled: pColorPicker->m_ColorMode != Mode))
2287 {
2288 pColorPicker->m_ColorMode = Mode;
2289 }
2290 }
2291
2292 return CUi::POPUP_KEEP_OPEN;
2293}
2294
2295void CUi::ShowPopupColorPicker(float X, float Y, SColorPickerPopupContext *pContext)
2296{
2297 pContext->m_pUI = this;
2298 if(pContext->m_ColorMode == SColorPickerPopupContext::MODE_UNSET)
2299 pContext->m_ColorMode = SColorPickerPopupContext::MODE_HSVA;
2300 DoPopupMenu(pId: pContext, X, Y, Width: 160.0f + 10.0f, Height: 209.0f + 10.0f, pContext, pfnFunc: PopupColorPicker);
2301}
2302