ZenitUI
Retained-mode C++20 UI framework
Loading...
Searching...
No Matches
StyleAttr.hpp
Go to the documentation of this file.
1#pragma once
2
18
19#include "Common.hpp"
20#include "Logger.hpp"
21#include "CoreTypes.hpp"
22#include "Easing.hpp"
23#include "Unit.hpp"
24#include "Style.hpp"
25#include "StyleSpecs.hpp"
26
27#include <charconv>
28#include <cctype>
29#include <optional>
30#include <sstream>
31
32namespace ZenitUI
33{
34
38
40 namespace detail
41 {
43 inline bool parseFloatSV(std::string_view s, float &out)
44 {
45 if (s.empty())
46 return false;
47 auto [ptr, ec] = std::from_chars(s.data(), s.data() + s.size(), out);
48 return ec == std::errc();
49 }
50
52 struct CalcToken
53 {
54 enum class Kind
55 {
56 Number,
57 Ident,
58 Percent,
59 Plus,
60 Minus,
61 Star,
62 Slash,
63 LParen,
64 RParen,
65 Comma,
66 End
67 };
68 Kind kind{Kind::End};
69 float num{0.0f};
70 std::string ident;
71 };
72
76 inline std::vector<CalcToken> tokenizeCalc(std::string_view s)
77 {
78 std::vector<CalcToken> out;
79 size_t i = 0;
80 while (i < s.size())
81 {
82 char c = s[i];
83 if (std::isspace((unsigned char)c))
84 {
85 ++i;
86 continue;
87 }
88 if (c == '+')
89 {
90 out.push_back({CalcToken::Kind::Plus});
91 ++i;
92 continue;
93 }
94 if (c == '-')
95 {
96 out.push_back({CalcToken::Kind::Minus});
97 ++i;
98 continue;
99 }
100 if (c == '*')
101 {
102 out.push_back({CalcToken::Kind::Star});
103 ++i;
104 continue;
105 }
106 if (c == '/')
107 {
108 out.push_back({CalcToken::Kind::Slash});
109 ++i;
110 continue;
111 }
112 if (c == '(')
113 {
114 out.push_back({CalcToken::Kind::LParen});
115 ++i;
116 continue;
117 }
118 if (c == ')')
119 {
120 out.push_back({CalcToken::Kind::RParen});
121 ++i;
122 continue;
123 }
124 if (c == '%')
125 {
126 out.push_back({CalcToken::Kind::Percent});
127 ++i;
128 continue;
129 }
130 if (c == ',')
131 {
132 out.push_back({CalcToken::Kind::Comma});
133 ++i;
134 continue;
135 }
136
137 if (std::isdigit((unsigned char)c) || c == '.')
138 {
139 size_t start = i;
140 while (i < s.size() && (std::isdigit((unsigned char)s[i]) || s[i] == '.'))
141 ++i;
142 float v = 0.0f;
143 (void)parseFloatSV(s.substr(start, i - start), v);
144 CalcToken t;
145 t.kind = CalcToken::Kind::Number;
146 t.num = v;
147 out.push_back(t);
148 continue;
149 }
150 if (std::isalpha((unsigned char)c) || c == '_')
151 {
152 size_t start = i;
153 while (i < s.size() && (std::isalnum((unsigned char)s[i]) || s[i] == '_'))
154 ++i;
155 CalcToken t;
156 t.kind = CalcToken::Kind::Ident;
157 t.ident = std::string(s.substr(start, i - start));
158 out.push_back(t);
159 continue;
160 }
161 ++i;
162 }
163 out.push_back({CalcToken::Kind::End});
164 return out;
165 }
166
168 inline bool parseOptFloatSV(std::string_view s, Opt<float> &out)
169 {
170 if (s.empty())
171 return false;
172 float v = 0.0f;
173 auto [ptr, ec] = std::from_chars(s.data(), s.data() + s.size(), v);
174 if (ec != std::errc())
175 return false;
176 out = v;
177 return true;
178 }
179
188 class CalcParser
189 {
190 public:
191 explicit CalcParser(const std::vector<CalcToken> &toks) : toks(toks) {}
192
193 bool parse(Value &out)
194 {
195 out = parseExpr();
196 return !errored && pos < toks.size() && toks[pos].kind == CalcToken::Kind::End;
197 }
198
199 private:
200 const std::vector<CalcToken> &toks;
201 size_t pos{0};
202 bool errored{false};
203
204 const CalcToken &peek() const { return toks[pos]; }
205 void advance()
206 {
207 if (pos + 1 < toks.size())
208 ++pos;
209 }
210 void error() { errored = true; }
211
212 Value parseExpr()
213 {
214 Value left = parseTerm();
215 while (!errored && (peek().kind == CalcToken::Kind::Plus ||
216 peek().kind == CalcToken::Kind::Minus))
217 {
218 auto op = peek().kind;
219 advance();
220 Value right = parseTerm();
221 left = (op == CalcToken::Kind::Plus) ? (left + right) : (left - right);
222 }
223 return left;
224 }
225
226 Value parseTerm()
227 {
228 Value left = parseFactor();
229 while (!errored && (peek().kind == CalcToken::Kind::Star ||
230 peek().kind == CalcToken::Kind::Slash))
231 {
232 auto op = peek().kind;
233 advance();
234 Value right = parseFactor();
235 left = (op == CalcToken::Kind::Star) ? left.mulWith(right)
236 : left.divWith(right);
237 }
238 return left;
239 }
240
241 Value parseFactor()
242 {
243 if (errored)
244 return Value::px(0.0f);
245 if (peek().kind == CalcToken::Kind::Minus)
246 {
247 advance();
248 return -parseFactor();
249 }
250 if (peek().kind == CalcToken::Kind::Plus)
251 {
252 advance();
253 return parseFactor();
254 }
255 if (peek().kind == CalcToken::Kind::LParen)
256 {
257 advance();
258 Value v = parseExpr();
259 if (peek().kind != CalcToken::Kind::RParen)
260 {
261 error();
262 return v;
263 }
264 advance();
265 return v;
266 }
267 if (peek().kind == CalcToken::Kind::Ident)
268 {
269 std::string func = peek().ident;
270 advance();
271 if (peek().kind == CalcToken::Kind::LParen)
272 {
273 advance();
274 std::vector<Value> fargs;
275 if (peek().kind != CalcToken::Kind::RParen)
276 {
277 fargs.push_back(parseExpr());
278 while (!errored && peek().kind == CalcToken::Kind::Comma)
279 {
280 advance();
281 fargs.push_back(parseExpr());
282 }
283 }
284 if (peek().kind != CalcToken::Kind::RParen)
285 {
286 error();
287 return Value::px(0.0f);
288 }
289 advance();
290if (func == "calc")
291 {
292 if (fargs.size() == 1)
293 return fargs[0];
294 error();
295 return Value::px(0.0f);
296 }
297
298 ValueOp vop = ValueOp::None;
299 if (func == "min")
300 vop = ValueOp::Min;
301 else if (func == "max")
302 vop = ValueOp::Max;
303 else if (func == "clamp")
304 vop = ValueOp::Clamp;
305 else if (func == "round")
306 vop = ValueOp::Round;
307 else if (func == "floor")
308 vop = ValueOp::Floor;
309 else if (func == "ceil")
310 vop = ValueOp::Ceil;
311 else if (func == "mod")
312 vop = ValueOp::Mod;
313 else
314 {
315 error();
316 return Value::px(0.0f);
317 }
318 return Value::makeOp(vop, std::move(fargs));
319 }
320 error();
321 return Value::px(0.0f);
322 }
323 if (peek().kind == CalcToken::Kind::Number)
324 {
325 float num = peek().num;
326 advance();
327 if (peek().kind == CalcToken::Kind::Percent)
328 {
329 advance();
330 return Value::percent(num);
331 }
332 if (peek().kind == CalcToken::Kind::Ident)
333 {
334 const std::string &u = peek().ident;
335 advance();
336 if (u == "px")
337 return Value::px(num);
338 if (u == "vw")
339 return Value::vw(num);
340 if (u == "vh")
341 return Value::vh(num);
342 if (u == "pw")
343 return Value::pw(num);
344 if (u == "ph")
345 return Value::ph(num);
346 return Value::px(num);
347 }
348 return Value::number(num);
349 }
350 error();
351 return Value::px(0.0f);
352 }
353 };
354
358 inline FontStack parseFontStack(std::string_view raw)
359 {
360 FontStack out;
361 size_t i = 0;
362 while (i < raw.size())
363 {
364 while (i < raw.size() &&
365 (std::isspace((unsigned char)raw[i]) || raw[i] == ','))
366 ++i;
367 if (i >= raw.size())
368 break;
369
370 char quote = 0;
371 if (raw[i] == '"' || raw[i] == '\'')
372 {
373 quote = raw[i];
374 ++i;
375 }
376
377 size_t start = i;
378 if (quote)
379 {
380 while (i < raw.size() && raw[i] != quote)
381 ++i;
382 out.push_back(std::string(raw.substr(start, i - start)));
383 if (i < raw.size())
384 ++i;
385 }
386 else
387 {
388 while (i < raw.size() &&
389 raw[i] != ',' &&
390 !std::isspace((unsigned char)raw[i]))
391 ++i;
392 out.push_back(std::string(raw.substr(start, i - start)));
393 }
394 }
395 return out;
396 }
397
398 } // namespace detail
399
404 inline std::optional<Value> parseValueToken(std::string_view s)
405 {
406 if (s.empty())
407 return std::nullopt;
408 if (s == "auto")
409 return Value::autoSize();
410
411 if (s.starts_with("calc(") || s.starts_with("min(") || s.starts_with("max(") ||
412 s.starts_with("clamp(") || s.starts_with("round(") || s.starts_with("floor(") ||
413 s.starts_with("ceil(") || s.starts_with("mod("))
414 {
415
416 auto toks = detail::tokenizeCalc(s);
417 detail::CalcParser p(toks);
418 Value out;
419 if (!p.parse(out))
420 {
421 logWarn("StyleParser", "", 0, 0, "invalid math expression '" + std::string(s) + "'");
422 return std::nullopt;
423 }
424 return out;
425 }
426
427 size_t n = 0;
428 while (n < s.size() && (std::isdigit((unsigned char)s[n]) ||
429 s[n] == '.' || s[n] == '-' || s[n] == '+'))
430 ++n;
431
432 float amount = 0.0f;
433 if (!detail::parseFloatSV(s.substr(0, n), amount))
434 return std::nullopt;
435
436 std::string_view unit = s.substr(n);
437 if (unit.empty() || unit == "px")
438 return Px(amount);
439 if (unit == "%")
440 return Percent(amount);
441 if (unit == "vw")
442 return VW(amount);
443 if (unit == "vh")
444 return VH(amount);
445 if (unit == "pw")
446 return PW(amount);
447 if (unit == "ph")
448 return PH(amount);
449 return std::nullopt;
450 }
451
456 inline std::optional<Color> parseColorToken(std::string_view s)
457 {
458 if (s == "white")
459 return Colors::White;
460 if (s == "black")
461 return Colors::Black;
462 if (s == "transparent")
463 return Colors::Blank;
464 if (s == "blank")
465 return Colors::Blank;
466 if (s == "red")
467 return Colors::Red;
468 if (s == "maroon")
469 return Colors::Maroon;
470 if (s == "green")
471 return Colors::Green;
472 if (s == "blue")
473 return Colors::Blue;
474 if (s == "yellow")
475 return Colors::Yellow;
476 if (s == "gray")
477 return Colors::Gray;
478 if (s == "darkgray")
479 return Colors::DarkGray;
480 if (s == "lightgray")
481 return Colors::LightGray;
482 if (s.size() > 4 && s[0] == 'r' && s[1] == 'g' && s[2] == 'b')
483 {
484 bool hasAlpha = (s[3] == 'a');
485 size_t paren = s.find('(');
486 if (paren != std::string_view::npos && s.back() == ')')
487 {
488 std::string_view inner = s.substr(paren + 1, s.size() - paren - 2);
489 std::vector<float> parts;
490 std::string cur;
491 for (char c : inner)
492 {
493 if (c == ',')
494 {
495 try
496 {
497 parts.push_back(std::stof(cur));
498 }
499 catch (...)
500 {
501 return std::nullopt;
502 }
503 cur.clear();
504 }
505 else if (!std::isspace((unsigned char)c))
506 {
507 cur.push_back(c);
508 }
509 }
510 if (!cur.empty())
511 {
512 try
513 {
514 parts.push_back(std::stof(cur));
515 }
516 catch (...)
517 {
518 return std::nullopt;
519 }
520 }
521
522 const size_t expected = hasAlpha ? 4 : 3;
523 if (parts.size() != expected)
524 return std::nullopt;
525
526 auto clamp255 = [](float v) -> uint8_t
527 {
528 return (uint8_t)std::clamp((int)std::lround(v), 0, 255);
529 };
530
531 uint8_t r = clamp255(parts[0]);
532 uint8_t g = clamp255(parts[1]);
533 uint8_t b = clamp255(parts[2]);
534 uint8_t a = hasAlpha
535 ? clamp255(parts[3] * 255.0f)
536 : (uint8_t)255;
537
538 return Color{r, g, b, a};
539 }
540 }
541 if (!s.empty() && s[0] == '#')
542 {
543 std::string_view h = s.substr(1);
544 auto hex = [](char c) -> int
545 {
546 if (c >= '0' && c <= '9')
547 return c - '0';
548 if (c >= 'a' && c <= 'f')
549 return c - 'a' + 10;
550 if (c >= 'A' && c <= 'F')
551 return c - 'A' + 10;
552 return -1;
553 };
554 for (char c : h)
555 {
556 if (hex(c) < 0)
557 return std::nullopt;
558 }
559 if (h.size() == 3)
560 return Color{(uint8_t)(hex(h[0]) * 17), (uint8_t)(hex(h[1]) * 17), (uint8_t)(hex(h[2]) * 17), 255};
561 if (h.size() == 4)
562 return Color{(uint8_t)(hex(h[0]) * 17), (uint8_t)(hex(h[1]) * 17), (uint8_t)(hex(h[2]) * 17), (uint8_t)(hex(h[3]) * 17)};
563 if (h.size() == 6)
564 return Color{(uint8_t)(hex(h[0]) * 16 + hex(h[1])), (uint8_t)(hex(h[2]) * 16 + hex(h[3])), (uint8_t)(hex(h[4]) * 16 + hex(h[5])), 255};
565 if (h.size() == 8)
566 return Color{(uint8_t)(hex(h[0]) * 16 + hex(h[1])), (uint8_t)(hex(h[2]) * 16 + hex(h[3])), (uint8_t)(hex(h[4]) * 16 + hex(h[5])), (uint8_t)(hex(h[6]) * 16 + hex(h[7]))};
567 }
568 return std::nullopt;
569 }
570
575 inline std::optional<Spacing> parseSpacingToken(std::string_view s)
576 {
577 std::vector<Value> vals;
578 size_t i = 0;
579 while (i < s.size())
580 {
581 while (i < s.size() && std::isspace((unsigned char)s[i]))
582 ++i;
583 size_t start = i;
584 int depth = 0;
585 while (i < s.size())
586 {
587 char c = s[i];
588 if (c == '(')
589 ++depth;
590 else if (c == ')' && depth > 0)
591 --depth;
592 else if (depth == 0 && std::isspace((unsigned char)c))
593 break;
594 ++i;
595 }
596 if (start == i)
597 break;
598 auto v = parseValueToken(s.substr(start, i - start));
599 if (!v)
600 return std::nullopt;
601 vals.push_back(*v);
602 }
603 if (vals.size() == 1)
604 return Spacing(vals[0]);
605 if (vals.size() == 2)
606 return Spacing(vals[0], vals[1]);
607 if (vals.size() == 3)
608 return Spacing(vals[0], vals[1], vals[2]);
609 if (vals.size() == 4)
610 return Spacing(vals[0], vals[1], vals[2], vals[3]);
611 return std::nullopt;
612 }
613
614 inline std::optional<Align> parseAlignToken(std::string_view s)
615 {
616 if (s == "auto")
617 return Align::Auto;
618 if (s == "start")
619 return Align::Start;
620 if (s == "center")
621 return Align::Center;
622 if (s == "end")
623 return Align::End;
624 if (s == "stretch")
625 return Align::Stretch;
626 return std::nullopt;
627 }
628
629 inline std::optional<Direction> parseDirectionToken(std::string_view s)
630 {
631 if (s == "row")
632 return Direction::Row;
633 if (s == "column")
634 return Direction::Column;
635 if (s == "auto")
636 return Direction::Auto;
637 return std::nullopt;
638 }
639
640 inline std::optional<TextDirection> parseTextDirectionToken(std::string_view s)
641 {
642 if (s == "auto")
643 return TextDirection::Auto;
644 if (s == "ltr")
645 return TextDirection::LTR;
646 if (s == "rtl")
647 return TextDirection::RTL;
648 return std::nullopt;
649 }
650
651 inline std::optional<Justify> parseJustifyToken(std::string_view s)
652 {
653 if (s == "start")
654 return Justify::Start;
655 if (s == "center")
656 return Justify::Center;
657 if (s == "end")
658 return Justify::End;
659 if (s == "space-between")
661 return std::nullopt;
662 }
663
664 inline std::optional<WhiteSpace> parseWhiteSpaceToken(std::string_view s)
665 {
666 if (s == "normal")
667 return WhiteSpace::Normal;
668 if (s == "nowrap")
669 return WhiteSpace::Nowrap;
670 return std::nullopt;
671 }
672
673 inline std::optional<TextOverflow> parseTextOverflowToken(std::string_view s)
674 {
675 if (s == "visible")
676 return TextOverflow::Visible;
677 if (s == "ellipsis")
678 return TextOverflow::Ellipsis;
679 return std::nullopt;
680 }
681
682 inline std::optional<CursorShape> parseCursorToken(std::string_view s)
683 {
684 if (s == "auto")
685 return CursorShape::Auto;
686 if (s == "default")
688 if (s == "pointer")
690 if (s == "text")
691 return CursorShape::Text;
692 if (s == "move")
693 return CursorShape::Move;
694 if (s == "grab")
695 return CursorShape::Grab;
696 if (s == "grabbing")
698 if (s == "ew-resize" || s == "col-resize")
700 if (s == "ns-resize" || s == "row-resize")
702 if (s == "nesw-resize")
704 if (s == "nwse-resize")
706 if (s == "not-allowed")
708 if (s == "crosshair")
710 if (s == "wait" || s == "progress")
711 return CursorShape::Wait;
712 return std::nullopt;
713 }
714
721 inline bool applyStyleAttr(Style &st, std::string_view key, std::string_view val)
722 {
723 if (const PropSpec *spec = findStylePropSpec(key))
724 {
725 if (spec->apply)
726 {
727 ParseCtx ctx{};
728 (void)spec->apply(st, val, ctx);
729 return true;
730 }
731 }
732
733 return false;
734 }
735
739 inline std::string substituteVarRefs(
740 std::string v,
741 const std::unordered_map<std::string, std::string> &customProps)
742 {
743 auto trimLocal = [](std::string s)
744 {
745 size_t a = 0, b = s.size();
746 while (a < b && std::isspace((unsigned char)s[a]))
747 a++;
748 while (b > a && std::isspace((unsigned char)s[b - 1]))
749 b--;
750 return s.substr(a, b - a);
751 };
752
753 bool changed = true;
754 int safety = 0;
755 while (changed && safety++ < 10)
756 {
757 changed = false;
758 size_t pos = 0;
759 while ((pos = v.find("var(", pos)) != std::string::npos)
760 {
761 size_t close = v.find(')', pos);
762 if (close == std::string::npos)
763 break;
764 std::string name = trimLocal(v.substr(pos + 4, close - pos - 4));
765 auto it = customProps.find(name);
766 if (it == customProps.end())
767 {
768 pos = close + 1;
769 continue;
770 }
771 v.replace(pos, close - pos + 1, it->second);
772 changed = true;
773 }
774 }
775 return v;
776 }
777
782 const std::unordered_map<std::string, std::string> &unresolved,
783 const std::unordered_map<std::string, std::string> &customProps)
784 {
785 Style out;
786 for (auto &[k, raw] : unresolved)
787 {
788 std::string resolved = substituteVarRefs(raw, customProps);
789 applyStyleAttr(out, k, resolved);
790 }
791 return out;
792 }
793
794} // namespace ZenitUI
Centralized standard library includes used throughout ZenitUI.
Small value types shared by the layout, rendering and input layers.
Easing curves used by transitions and CSS animations.
Lightweight, replaceable logging facility used across ZenitUI.
Executable metadata table for ZStyle properties, shorthands, and syntax constructs.
The Style / ComputedStyle pair and all style-related value types.
Length units and the compact 8-byte tagged Value expression representation.
@ Center
Center the whole set.
Definition CoreTypes.hpp:464
@ End
Pack at the trailing edge.
Definition CoreTypes.hpp:465
@ Start
Pack at the leading edge.
Definition CoreTypes.hpp:463
@ SpaceBetween
Distribute leftover space between items.
Definition CoreTypes.hpp:466
@ Auto
Defer to the parent's alignItems.
Definition CoreTypes.hpp:453
@ Center
Center within the available space.
Definition CoreTypes.hpp:455
@ End
Pack at the trailing edge.
Definition CoreTypes.hpp:456
@ Start
Pack at the leading edge.
Definition CoreTypes.hpp:454
@ Stretch
Stretch to fill the cross axis.
Definition CoreTypes.hpp:457
@ Auto
Infer paragraph direction from first strong Bidi character (fallback LTR).
Definition UIEnums.hpp:84
@ LTR
Explicit left-to-right direction.
Definition UIEnums.hpp:85
@ RTL
Explicit right-to-left direction.
Definition UIEnums.hpp:86
@ Auto
Inherit or fall back to Default.
Definition UIEnums.hpp:62
@ Crosshair
Precision crosshair (crosshair).
Definition UIEnums.hpp:74
@ Wait
Busy / loading indicator (wait, progress).
Definition UIEnums.hpp:75
@ ResizeEW
Horizontal resize (ew-resize, col-resize).
Definition UIEnums.hpp:69
@ ResizeNS
Vertical resize (ns-resize, row-resize).
Definition UIEnums.hpp:70
@ Pointer
Pointing hand (buttons, links, interactive controls).
Definition UIEnums.hpp:64
@ ResizeNESW
Diagonal NE-SW resize (nesw-resize).
Definition UIEnums.hpp:71
@ Move
Four-way move cursor.
Definition UIEnums.hpp:66
@ Grabbing
Closed hand (active drag).
Definition UIEnums.hpp:68
@ Default
Standard arrow cursor.
Definition UIEnums.hpp:63
@ ResizeNWSE
Diagonal NW-SE resize (nwse-resize).
Definition UIEnums.hpp:72
@ Text
I-beam (editable text fields).
Definition UIEnums.hpp:65
@ Grab
Open hand (draggable item).
Definition UIEnums.hpp:67
@ NotAllowed
Forbidden / disabled action (not-allowed).
Definition UIEnums.hpp:73
bool applyStyleAttr(Style &st, std::string_view key, std::string_view val)
Apply a single key: value declaration to st.
Definition StyleAttr.hpp:721
std::optional< Color > parseColorToken(std::string_view s)
Parse a color token.
Definition StyleAttr.hpp:456
Style resolveUnresolvedProps(const std::unordered_map< std::string, std::string > &unresolved, const std::unordered_map< std::string, std::string > &customProps)
Resolve every pending var(...) declaration in unresolved.
Definition StyleAttr.hpp:781
std::optional< Value > parseValueToken(std::string_view s)
Parse a single Value token.
Definition StyleAttr.hpp:404
std::optional< Spacing > parseSpacingToken(std::string_view s)
Parse a 1-4 value shorthand.
Definition StyleAttr.hpp:575
std::string substituteVarRefs(std::string v, const std::unordered_map< std::string, std::string > &customProps)
Recursively substitute var(--name) references in v.
Definition StyleAttr.hpp:739
const PropSpec * findStylePropSpec(std::string_view key)
O(1) lookup by ZStyle key; returns nullptr if unknown.
8-bit-per-channel RGBA color, non-premultiplied.
Definition CoreTypes.hpp:78
Context passed to executable property parsers.
Definition StyleSpecs.hpp:37
Executable + documentation descriptor for one ZStyle key.
Definition StyleSpecs.hpp:47
Four-sided Value tuple used for padding, margin and border-width.
Definition Style.hpp:486
Sparse style: every property is Opt<T>, unset by default.
Definition Style.hpp:932
8-byte tagged length expression:
Definition Unit.hpp:58