|
| 1 | +""" |
| 2 | +This is an experimental implementation of a restricted input field. |
| 3 | +If the implementation is successful, the feature will be merged into the existing UIInputText class. |
| 4 | +""" |
| 5 | + |
| 6 | +from typing import Optional |
| 7 | + |
| 8 | + |
| 9 | +from arcade.gui import UIEvent, UIInputText |
| 10 | + |
| 11 | + |
| 12 | +class UIRestrictedInput(UIInputText): |
| 13 | + """ |
| 14 | + A text input field that restricts the input to a certain type. |
| 15 | +
|
| 16 | + This class is meant to be subclassed to create custom input fields |
| 17 | + that restrict the input by providing a custom validation method. |
| 18 | +
|
| 19 | + Invalid inputs are dropped. |
| 20 | + """ |
| 21 | + |
| 22 | + @property |
| 23 | + def text(self): |
| 24 | + """Text of the input field.""" |
| 25 | + return self.doc.text |
| 26 | + |
| 27 | + @text.setter |
| 28 | + def text(self, text: str): |
| 29 | + if not self.validate(text): |
| 30 | + # if the text is invalid, do not update the text |
| 31 | + return |
| 32 | + |
| 33 | + # we can not call super().text = text here: https://bugs.python.org/issue14965 |
| 34 | + UIInputText.text.__set__(self, text) # type: ignore |
| 35 | + |
| 36 | + def on_event(self, event: UIEvent) -> Optional[bool]: |
| 37 | + # check if text changed during event handling, |
| 38 | + # if so we need to validate the new text |
| 39 | + old_text = self.text |
| 40 | + pos = self.caret.position |
| 41 | + |
| 42 | + result = super().on_event(event) |
| 43 | + if not self.validate(self.text): |
| 44 | + self.text = old_text |
| 45 | + self.caret.position = pos |
| 46 | + |
| 47 | + return result |
| 48 | + |
| 49 | + def validate(self, text) -> bool: |
| 50 | + """Override this method to add custom validation logic. |
| 51 | +
|
| 52 | + Be aware that an empty string should always be valid. |
| 53 | + """ |
| 54 | + return True |
| 55 | + |
| 56 | + |
| 57 | +class UIIntInput(UIRestrictedInput): |
| 58 | + def validate(self, text) -> bool: |
| 59 | + if text == "": |
| 60 | + return True |
| 61 | + |
| 62 | + try: |
| 63 | + int(text) |
| 64 | + return True |
| 65 | + except ValueError: |
| 66 | + return False |
| 67 | + |
| 68 | + |
| 69 | +class UIFloatInput(UIRestrictedInput): |
| 70 | + def validate(self, text) -> bool: |
| 71 | + if text == "": |
| 72 | + return True |
| 73 | + |
| 74 | + try: |
| 75 | + float(text) |
| 76 | + return True |
| 77 | + except ValueError: |
| 78 | + return False |
| 79 | + |
| 80 | + |
| 81 | +class UIRegexInput(UIRestrictedInput): |
| 82 | + def __init__(self, *args, pattern: str = r".*", **kwargs): |
| 83 | + super().__init__() |
| 84 | + self.pattern = pattern |
| 85 | + |
| 86 | + def validate(self, text: str) -> bool: |
| 87 | + if text == "": |
| 88 | + return True |
| 89 | + |
| 90 | + import re |
| 91 | + |
| 92 | + return re.match(self.pattern, text) is not None |
0 commit comments