|
6 | 6 | # >> IMPORTS
|
7 | 7 | # =============================================================================
|
8 | 8 | # Source.Python Imports
|
| 9 | +# Core |
| 10 | +from core import AutoUnload |
9 | 11 | # Cvars
|
10 | 12 | from _cvars import ConVar
|
11 | 13 | from _cvars import _Cvar
|
|
24 | 26 | # >> ALL DECLARATION
|
25 | 27 | # =============================================================================
|
26 | 28 | __all__ = ('ConVar',
|
| 29 | + 'ConVarChanged', |
27 | 30 | 'cvar',
|
28 | 31 | )
|
| 32 | + |
| 33 | + |
| 34 | +# ============================================================================= |
| 35 | +# >> CLASSES |
| 36 | +# ============================================================================= |
| 37 | +class ConVarChanged(AutoUnload): |
| 38 | + """ConVarChanged decorator class.""" |
| 39 | + |
| 40 | + def __init__(self, *convars): |
| 41 | + """Store the convars.""" |
| 42 | + self._convars = () |
| 43 | + self.callback = None |
| 44 | + |
| 45 | + # Validate convars |
| 46 | + if not convars: |
| 47 | + raise ValueError('At least one convar is required.') |
| 48 | + |
| 49 | + _convars = [] |
| 50 | + for convar in convars: |
| 51 | + if not isinstance(convar, (str, ConVar)): |
| 52 | + raise ValueError('Given convar is not ConVar or ConVar name.') |
| 53 | + |
| 54 | + elif isinstance(convar, str): |
| 55 | + convar_name = convar |
| 56 | + convar = cvar.find_var(convar_name) |
| 57 | + if convar is None: |
| 58 | + raise ValueError( |
| 59 | + f'"{convar_name}" is not a valid ConVar name.') |
| 60 | + |
| 61 | + _convars.append(convar) |
| 62 | + |
| 63 | + self._convars = tuple(_convars) |
| 64 | + |
| 65 | + def __call__(self, callback): |
| 66 | + """Store the callback and add it to convars.""" |
| 67 | + # Store the callback |
| 68 | + self.callback = callback |
| 69 | + |
| 70 | + # Loop through all convars |
| 71 | + for convar in self._convars: |
| 72 | + |
| 73 | + # Add the callback |
| 74 | + convar.add_changed_callback(self.callback) |
| 75 | + |
| 76 | + # Return the callback |
| 77 | + return self.callback |
| 78 | + |
| 79 | + def _unload_instance(self): |
| 80 | + """Remove the callback from convars.""" |
| 81 | + # Was no callback registered? |
| 82 | + if self.callback is None: |
| 83 | + return |
| 84 | + |
| 85 | + # Loop through all convars |
| 86 | + for convar in self._convars: |
| 87 | + |
| 88 | + # Remove the callback |
| 89 | + convar.remove_changed_callback(self.callback) |
0 commit comments