Debian Codegraph @

plugins/dm.gui/gui/GuiExpression.cpp

raw
1 #include "GuiExpression.h"
2
3 #include <list>
4 #include <stack>
5 #include <sigc++/connection.h>
6
7 #include "itextstream.h"
8
9 #include "string/trim.h"
10 #include "string/convert.h"
11 #include "string/predicate.h"
12
13 namespace gui
14 {
15
16 // An expression referring to a GUI state variable
17 GuiStateVariableExpression::GuiStateVariableExpression(IGui& gui, const std::string& variableName) :
18 _gui(gui),
19 _variableName(variableName)
20 {
21 if (!_variableName.empty())
22 {
23 // Register to the GUI state change signal
24 _gui.getChangedSignalForState(_variableName).connect([this]()
25 {
26 signal_valueChanged().emit();
27 });
28 }
29 }
30
31 float GuiStateVariableExpression::getFloatValue()
32 {
33 return string::convert<float>(_gui.getStateString(_variableName));
34 }
35
36 std::string GuiStateVariableExpression::getStringValue()
37 {
38 return _gui.getStateString(_variableName);
39 }
40
41 namespace detail
42 {
43
44 // Abstract base class for an expression taking two sub-expression as arguments
45 // Additions, Multiplications, Divisions, Modulo, comparisons, etc.
46 class BinaryExpression :
47 public GuiExpression
48 {
49 public:
50 // The operator precedence, smaller values mean higher priority
51 enum Precedence
52 {
53 LOGICAL_NOT = 0, // !
54 MULTIPLICATION = 0, // *
55 DIVISION = 0, // /
56 MODULO = 0, // %
57 ADDITION = 1, // +
58 SUBTRACTION = 1, // -
59 RELATIONAL_COMPARISON = 2, // > >= < <=
60 EQUALITY_COMPARISON = 3, // == !=
61 LOGICAL_AND = 4, // &&
62 LOGICAL_OR = 5, // ||
63 };
64
65 protected:
66 GuiExpressionPtr _a;
67 GuiExpressionPtr _b;
68 Precedence _precedence;
69
70 sigc::connection _aChanged;
71 sigc::connection _bChanged;
72
73 public:
74 BinaryExpression(Precedence precedence,
75 const GuiExpressionPtr& a = GuiExpressionPtr(),
76 const GuiExpressionPtr& b = GuiExpressionPtr()) :
77 GuiExpression(),
78 _a(a),
79 _b(b),
80 _precedence(precedence)
81 {
82 if (_a)
83 {
84 _aChanged = _a->signal_valueChanged().connect([this]()
85 {
86 signal_valueChanged().emit();
87 });
88 }
89
90 if (_b)
91 {
92 _bChanged = _b->signal_valueChanged().connect([this]()
93 {
94 signal_valueChanged().emit();
95 });
96 }
97 }
98
99 Precedence getPrecedence() const
100 {
101 return _precedence;
102 }
103
104 void setA(const GuiExpressionPtr& a)
105 {
106 // Disconnect from any previous signal
107 _aChanged.disconnect();
108
109 _a = a;
110
111 if (_a)
112 {
113 _aChanged = _a->signal_valueChanged().connect([this]()
114 {
115 signal_valueChanged().emit();
116 });
117 }
118 }
119
120 void setB(const GuiExpressionPtr& b)
121 {
122 // Disconnect from any previous signal
123 _bChanged.disconnect();
124
125 _b = b;
126
127 if (_b)
128 {
129 _bChanged = _b->signal_valueChanged().connect([this]()
130 {
131 signal_valueChanged().emit();
132 });
133 }
134 }
135
136 virtual std::string getStringValue() override
137 {
138 return string::to_string(getFloatValue());
139 }
140 };
141 typedef std::shared_ptr<BinaryExpression> BinaryExpressionPtr;
142
143 // An expression adding the value of two expressions
144 class AddExpression :
145 public BinaryExpression
146 {
147 public:
148 AddExpression(const GuiExpressionPtr& a = GuiExpressionPtr(),
149 const GuiExpressionPtr& b = GuiExpressionPtr()) :
150 BinaryExpression(ADDITION, a, b)
151 {}
152
153 virtual float getFloatValue() override
154 {
155 return _a->getFloatValue() + _b->getFloatValue();
156 }
157 };
158
159 // An expression subtracting the value of two expressions
160 class SubtractExpression :
161 public BinaryExpression
162 {
163 public:
164 SubtractExpression(const GuiExpressionPtr& a = GuiExpressionPtr(),
165 const GuiExpressionPtr& b = GuiExpressionPtr()) :
166 BinaryExpression(SUBTRACTION, a, b)
167 {}
168
169 virtual float getFloatValue() override
170 {
171 return _a->getFloatValue() - _b->getFloatValue();
172 }
173 };
174
175 // An expression multiplying the value of two expressions
176 class MultiplyExpression :
177 public BinaryExpression
178 {
179 public:
180 MultiplyExpression(const GuiExpressionPtr& a = GuiExpressionPtr(),
181 const GuiExpressionPtr& b = GuiExpressionPtr()) :
182 BinaryExpression(MULTIPLICATION, a, b)
183 {}
184
185 virtual float getFloatValue() override
186 {
187 return _a->getFloatValue() * _b->getFloatValue();
188 }
189 };
190
191 // An expression dividing the value of two expressions
192 class DivideExpression :
193 public BinaryExpression
194 {
195 public:
196 DivideExpression(const GuiExpressionPtr& a = GuiExpressionPtr(),
197 const GuiExpressionPtr& b = GuiExpressionPtr()) :
198 BinaryExpression(DIVISION, a, b)
199 {}
200
201 virtual float getFloatValue() override
202 {
203 return _a->getFloatValue() / _b->getFloatValue();
204 }
205 };
206
207 // An expression returning modulo of A % B
208 class ModuloExpression :
209 public BinaryExpression
210 {
211 public:
212 ModuloExpression(const GuiExpressionPtr& a = GuiExpressionPtr(),
213 const GuiExpressionPtr& b = GuiExpressionPtr()) :
214 BinaryExpression(MODULO, a, b)
215 {}
216
217 virtual float getFloatValue() override
218 {
219 return fmod(_a->getFloatValue(), _b->getFloatValue());
220 }
221 };
222
223 // An expression returning 1 if A < B, otherwise 0
224 class LesserThanExpression :
225 public BinaryExpression
226 {
227 public:
228 LesserThanExpression(const GuiExpressionPtr& a = GuiExpressionPtr(),
229 const GuiExpressionPtr& b = GuiExpressionPtr()) :
230 BinaryExpression(RELATIONAL_COMPARISON, a, b)
231 {}
232
233 virtual float getFloatValue() override
234 {
235 return _a->getFloatValue() < _b->getFloatValue() ? 1.0f : 0;
236 }
237 };
238
239 // An expression returning 1 if A <= B, otherwise 0
240 class LesserThanOrEqualExpression :
241 public BinaryExpression
242 {
243 public:
244 LesserThanOrEqualExpression(const GuiExpressionPtr& a = GuiExpressionPtr(),
245 const GuiExpressionPtr& b = GuiExpressionPtr()) :
246 BinaryExpression(RELATIONAL_COMPARISON, a, b)
247 {}
248
249 virtual float getFloatValue() override
250 {
251 return _a->getFloatValue() <= _b->getFloatValue() ? 1.0f : 0;
252 }
253 };
254
255 // An expression returning 1 if A > B, otherwise 0
256 class GreaterThanExpression :
257 public BinaryExpression
258 {
259 public:
260 GreaterThanExpression(const GuiExpressionPtr& a = GuiExpressionPtr(),
261 const GuiExpressionPtr& b = GuiExpressionPtr()) :
262 BinaryExpression(RELATIONAL_COMPARISON, a, b)
263 {}
264
265 virtual float getFloatValue() override
266 {
267 return _a->getFloatValue() > _b->getFloatValue() ? 1.0f : 0;
268 }
269 };
270
271 // An expression returning 1 if A >= B, otherwise 0
272 class GreaterThanOrEqualExpression :
273 public BinaryExpression
274 {
275 public:
276 GreaterThanOrEqualExpression(const GuiExpressionPtr& a = GuiExpressionPtr(),
277 const GuiExpressionPtr& b = GuiExpressionPtr()) :
278 BinaryExpression(RELATIONAL_COMPARISON, a, b)
279 {}
280
281 virtual float getFloatValue() override
282 {
283 return _a->getFloatValue() >= _b->getFloatValue() ? 1.0f : 0;
284 }
285 };
286
287 // An expression returning 1 if A == B, otherwise 0
288 class EqualityExpression :
289 public BinaryExpression
290 {
291 public:
292 EqualityExpression(const GuiExpressionPtr& a = GuiExpressionPtr(),
293 const GuiExpressionPtr& b = GuiExpressionPtr()) :
294 BinaryExpression(EQUALITY_COMPARISON, a, b)
295 {}
296
297 virtual float getFloatValue() override
298 {
299 return _a->getFloatValue() == _b->getFloatValue() ? 1.0f : 0;
300 }
301 };
302
303 // An expression returning 1 if A != B, otherwise 0
304 class InequalityExpression :
305 public BinaryExpression
306 {
307 public:
308 InequalityExpression(const GuiExpressionPtr& a = GuiExpressionPtr(),
309 const GuiExpressionPtr& b = GuiExpressionPtr()) :
310 BinaryExpression(EQUALITY_COMPARISON, a, b)
311 {}
312
313 virtual float getFloatValue() override
314 {
315 return _a->getFloatValue() != _b->getFloatValue() ? 1.0f : 0;
316 }
317 };
318
319 // An expression returning the opposite of the contained expression
320 class LogicalNotExpression :
321 public BinaryExpression
322 {
323 private:
324 GuiExpressionPtr _contained;
325
326 public:
327 LogicalNotExpression(const GuiExpressionPtr& contained = GuiExpressionPtr()) :
328 BinaryExpression(LOGICAL_NOT, contained)
329 {}
330
331 virtual float getFloatValue() override
332 {
333 return _a->getFloatValue() != 0.0f ? 1.0f : 0.0f;
334 }
335
336 virtual std::string getStringValue() override
337 {
338 return ""; // not implemented for string values
339 }
340 };
341
342 // An expression returning 1 if both A and B are true (non-zero), otherwise 0
343 class LogicalAndExpression :
344 public BinaryExpression
345 {
346 public:
347 LogicalAndExpression(const GuiExpressionPtr& a = GuiExpressionPtr(),
348 const GuiExpressionPtr& b = GuiExpressionPtr()) :
349 BinaryExpression(LOGICAL_AND, a, b)
350 {}
351
352 virtual float getFloatValue() override
353 {
354 return (_a->getFloatValue() != 0 && _b->getFloatValue() != 0) ? 1.0f : 0;
355 }
356 };
357
358 // An expression returning 1 if either A or B are true (non-zero), otherwise 0
359 class LogicalOrExpression :
360 public BinaryExpression
361 {
362 public:
363 LogicalOrExpression(const GuiExpressionPtr& a = GuiExpressionPtr(),
364 const GuiExpressionPtr& b = GuiExpressionPtr()) :
365 BinaryExpression(LOGICAL_OR, a, b)
366 {}
367
368 virtual float getFloatValue() override
369 {
370 return (_a->getFloatValue() != 0 || _b->getFloatValue() != 0) ? 1.0f : 0;
371 }
372 };
373
374 // Fixme: Maybe merge this with ShaderExpressionTokeniser
375 class GuiExpressionTokeniser :
376 public parser::DefTokeniser
377 {
378 private:
379 parser::DefTokeniser& _tokeniser;
380
381 // buffer containing tokens pulled from the wrapped tokeniser
382 std::list<std::string> _buffer;
383
384 const char* _delims;
385
386 public:
387 GuiExpressionTokeniser(parser::DefTokeniser& tokeniser) :
388 _tokeniser(tokeniser),
389 _delims("+-%*/=!<>&|")
390 {}
391
392 bool hasMoreTokens() const override
393 {
394 return !_buffer.empty() || _tokeniser.hasMoreTokens();
395 }
396
397 std::string nextToken() override
398 {
399 if (_buffer.empty())
400 {
401 // Pull a new token from the underlying stream and split it up
402 fillBuffer(_tokeniser.nextToken());
403 }
404
405 std::string result = _buffer.front();
406 _buffer.pop_front();
407
408 return result;
409 }
410
411 std::string peek() const override
412 {
413 if (!_buffer.empty())
414 {
415 // We have items in the buffer, return that one
416 return _buffer.front();
417 }
418
419 // No items in the buffer, take a peek in the underlying stream
420 std::string rawToken = _tokeniser.peek();
421
422 if (rawToken.empty())
423 {
424 return rawToken; // don't tokenise empty strings, just return it as it is
425 }
426
427 // Split up the token by using a sub-tokeniser, keeping all delimiters
428 parser::BasicDefTokeniser<std::string> subtokeniser(rawToken, "", _delims);
429
430 // Return the first of these tokens, then exit
431 return subtokeniser.nextToken();
432 }
433
434 private:
435 void fillBuffer(const std::string& token)
436 {
437 if (token.empty())
438 {
439 // It's possible to retrieve an empty token if the DefTokeniser encounters an empty string ""
440 // This is valid, so push the empty token
441 _buffer.push_back(token);
442 return;
443 }
444
445 // Use a separate tokeniser and keep all delimiters
446 parser::BasicDefTokeniser<std::string> subtokeniser(token, "", _delims);
447
448 while (subtokeniser.hasMoreTokens())
449 {
450 _buffer.push_back(subtokeniser.nextToken());
451 }
452 }
453 };
454
455 class GuiExpressionParser
456 {
457 private:
458 IGui& _gui;
459 GuiExpressionTokeniser& _tokeniser;
460
461 typedef std::stack<GuiExpressionPtr> OperandStack;
462 typedef std::stack<BinaryExpressionPtr> OperatorStack;
463
464 public:
465 GuiExpressionParser(IGui& gui, GuiExpressionTokeniser& tokeniser) :
466 _gui(gui),
467 _tokeniser(tokeniser)
468 {}
469
470 GuiExpressionPtr getExpression()
471 {
472 // The local variable and operator stack
473 OperandStack operands;
474 OperatorStack operators;
475
476 enum {
477 SearchingForOperand,
478 SearchingForOperator,
479 } searchState;
480
481 searchState = SearchingForOperand;
482
483 while (_tokeniser.hasMoreTokens())
484 {
485 if (searchState == SearchingForOperand)
486 {
487 // Don't actually pull the token from the tokeniser, we might want to
488 // return the tokeniser to the caller if the token is not part of the expression
489 // The token will be exhausted from the stream once it is recognised as keyword
490 std::string token = _tokeniser.peek();
491
492 // The parsed operand
493 GuiExpressionPtr term;
494
495 if (token == "(")
496 {
497 _tokeniser.nextToken(); // valid token, exhaust
498
499 // New scope, treat this as new expression
500 term = getExpression();
501 }
502 else if (token == ")")
503 {
504 _tokeniser.nextToken(); // valid token, exhaust
505
506 // End of scope reached, break the loop and roll up the expression
507 break;
508 }
509 else if (string::starts_with(token, "gui::"))
510 {
511 // This is a GUI state variable, extract the variable name
512 _tokeniser.nextToken();
513 term = std::make_shared<GuiStateVariableExpression>(_gui, token.substr(5));
514 }
515 // If this is a + or -, take it as a sign operator
516 else if (token == "+")
517 {
518 // A leading +, just ignore it
519 _tokeniser.nextToken();
520 continue;
521 }
522 else if (token == "-")
523 {
524 // A leading -, interpret it as -1 *
525 operands.push(std::make_shared<FloatExpression>(-1.0f));
526 operators.push(std::make_shared<MultiplyExpression>());
527
528 // Discard the - token
529 _tokeniser.nextToken();
530 continue;
531 }
532 else
533 {
534 // This might either be a float or a string constant
535 term = std::make_shared<StringExpression>(_tokeniser.nextToken());
536 }
537
538 if (!term)
539 {
540 break; // We've run out of terms
541 }
542
543 // The token has already been pulled from the tokeniser
544 operands.push(term);
545
546 // Look for an operator next
547 searchState = SearchingForOperator;
548 continue;
549 }
550 else if (searchState == SearchingForOperator)
551 {
552 // Get an operator
553 BinaryExpressionPtr op = getOperator();
554
555 if (op)
556 {
557 // Check precedence if we have previous operators
558 while (!operators.empty())
559 {
560 if (operators.top()->getPrecedence() <= op->getPrecedence())
561 {
562 finaliseOperator(operands, operators);
563 }
564 else
565 {
566 break;
567 }
568 }
569
570 // Push this one on the operator stack
571 operators.push(op);
572 searchState = SearchingForOperand; // back to operand search mode
573 continue;
574 }
575
576 // We might also hit a closing parenthesis after an operand
577 if (_tokeniser.peek() == ")")
578 {
579 // Exhaust and break the loop
580 _tokeniser.nextToken();
581 }
582
583 // Not an operator, break the loop
584 break;
585 }
586 }
587
588 // Roll up the operations
589 while (!operators.empty())
590 {
591 finaliseOperator(operands, operators);
592 }
593
594 if (operands.empty())
595 {
596 throw parser::ParseException("Missing expression");
597 }
598
599 GuiExpressionPtr rv = operands.top();
600 operands.pop();
601
602 assert(operands.empty()); // there should be nothing left on the stack
603
604 return rv;
605 }
606
607 private:
608 void finaliseOperator(OperandStack& operands, OperatorStack& operators)
609 {
610 const BinaryExpressionPtr& op = operators.top();
611
612 // Set operand B first, we're dealing with a LIFO stack
613 // Do not push a second operand in the case of a logical NOT
614 if (!std::dynamic_pointer_cast<LogicalNotExpression>(op))
615 {
616 // Need two operands for an operator
617 if (operands.size() < 2)
618 {
619 throw parser::ParseException("Too few operands for operator.");
620 }
621
622 op->setB(operands.top());
623 operands.pop();
624 }
625 else
626 {
627 // Need at least one operand for a NOT operator
628 if (operands.size() < 1)
629 {
630 throw parser::ParseException("Too few operands for ! operator.");
631 }
632 }
633
634 op->setA(operands.top());
635 operands.pop();
636
637 // Push the result back on the stack, as operand
638 operands.push(op);
639
640 // Remove the operator, after we've copied it to the operand stack
641 operators.pop();
642 }
643
644 // Helper routines
645 BinaryExpressionPtr getOperator()
646 {
647 if (!_tokeniser.hasMoreTokens())
648 {
649 return BinaryExpressionPtr();
650 }
651
652 std::string token = _tokeniser.peek();
653
654 if (token == "+")
655 {
656 _tokeniser.nextToken();
657 return std::make_shared<AddExpression>();
658 }
659 else if (token == "-")
660 {
661 _tokeniser.nextToken();
662 return std::make_shared<SubtractExpression>();
663 }
664 else if (token == "*")
665 {
666 _tokeniser.nextToken();
667 return std::make_shared<MultiplyExpression>();
668 }
669 else if (token == "/")
670 {
671 _tokeniser.nextToken();
672 return std::make_shared<DivideExpression>();
673 }
674 else if (token == "%")
675 {
676 _tokeniser.nextToken();
677 return std::make_shared<ModuloExpression>();
678 }
679 else if (token == "<")
680 {
681 _tokeniser.nextToken();
682
683 if (_tokeniser.peek() == "=")
684 {
685 _tokeniser.nextToken();
686 return std::make_shared<LesserThanOrEqualExpression>();
687 }
688
689 return std::make_shared<LesserThanExpression>();
690 }
691 else if (token == ">")
692 {
693 _tokeniser.nextToken();
694
695 if (_tokeniser.peek() == "=")
696 {
697 _tokeniser.nextToken();
698 return std::make_shared<GreaterThanOrEqualExpression>();
699 }
700
701 return std::make_shared<GreaterThanExpression>();
702 }
703 else if (token == "=")
704 {
705 _tokeniser.nextToken();
706
707 if (_tokeniser.peek() == "=")
708 {
709 _tokeniser.nextToken();
710 return std::make_shared<EqualityExpression>();
711 }
712
713 rError() << "Assignment operator '=' found in expression, did you mean '=='?" << std::endl;
714 }
715 else if (token == "!")
716 {
717 _tokeniser.nextToken();
718
719 if (_tokeniser.peek() == "=")
720 {
721 _tokeniser.nextToken();
722 return std::make_shared<InequalityExpression>();
723 }
724
725 return std::make_shared<LogicalNotExpression>();
726 }
727 else if (token == "&")
728 {
729 _tokeniser.nextToken();
730
731 if (_tokeniser.peek() == "&")
732 {
733 _tokeniser.nextToken();
734 return std::make_shared<LogicalAndExpression>();
735 }
736
737 rError() << "Bit-wise operator '&' found in expression, did you mean '&&'?" << std::endl;
738 }
739 else if (token == "|")
740 {
741 _tokeniser.nextToken();
742
743 if (_tokeniser.peek() == "|")
744 {
745 _tokeniser.nextToken();
746 return std::make_shared<LogicalOrExpression>();
747 }
748
749 rError() << "Bit-wise operator '|' found in expression, did you mean '||'?" << std::endl;
750 }
751
752 return BinaryExpressionPtr();
753 }
754 };
755
756 }
757
758 GuiExpression::GuiExpression()
759 {}
760
761 GuiExpressionPtr GuiExpression::CreateFromString(IGui& gui, const std::string& exprStr)
762 {
763 parser::BasicDefTokeniser<std::string> tokeniser(exprStr, parser::WHITESPACE, "{}(),");
764 return CreateFromTokens(gui, tokeniser);
765 }
766
767 GuiExpressionPtr GuiExpression::CreateFromTokens(IGui& gui, parser::DefTokeniser& tokeniser)
768 {
769 // Create an adapter which takes care of splitting the tokens into finer grains
770 // The incoming DefTokeniser is not splitting up expressions like "3*4" without any whitespace in them
771 detail::GuiExpressionTokeniser adapter(tokeniser);
772
773 try
774 {
775 detail::GuiExpressionParser parser(gui, adapter);
776 return parser.getExpression();
777 }
778 catch (parser::ParseException& ex)
779 {
780 rWarning() << "[GuiExpressionParser] " << ex.what() << std::endl;
781 return GuiExpressionPtr();
782 }
783 }
784
785 }
786