|
5 | 5 | # ============================================================================= |
6 | 6 | # >> IMPORTS |
7 | 7 | # ============================================================================= |
| 8 | +# Python |
| 9 | +from contextlib import contextmanager |
| 10 | + |
8 | 11 | # Source.Python Imports |
9 | 12 | # Core |
10 | 13 | from core import AutoUnload |
11 | 14 | # Memory |
12 | 15 | from _memory import HookType |
| 16 | +from _memory import set_hooks_disabled |
| 17 | +from _memory import get_hooks_disabled |
13 | 18 | from memory import Function |
14 | 19 |
|
15 | 20 |
|
|
19 | 24 | __all__ = ('HookType', |
20 | 25 | 'PostHook', |
21 | 26 | 'PreHook', |
| 27 | + 'set_hooks_disabled', |
| 28 | + 'get_hooks_disabled', |
| 29 | + 'hooks_disabled' |
22 | 30 | ) |
23 | 31 |
|
24 | 32 |
|
@@ -73,3 +81,44 @@ class PostHook(_Hook): |
73 | 81 | """Decorator class used to create post hooks that auto unload.""" |
74 | 82 |
|
75 | 83 | hook_type = HookType.POST |
| 84 | + |
| 85 | + |
| 86 | +# ============================================================================= |
| 87 | +# >> FUNCTIONS |
| 88 | +# ============================================================================= |
| 89 | +@contextmanager |
| 90 | +def hooks_disabled(disabled=True): |
| 91 | + """Temporarily disable or enable all hook callbacks. By default hooks are |
| 92 | + enabled. Thus, this context manager is mainly used to temporarily disable |
| 93 | + hook callbacks. If the context ends, the original value is restored. This |
| 94 | + can be used e. g. to avoid recursive calls when damaging a player in a |
| 95 | + ``on_take_damage`` hook or ``player_hurt`` event. |
| 96 | +
|
| 97 | + .. note:: |
| 98 | +
|
| 99 | + This would only disable hooks created with Source.Python. Hooks that |
| 100 | + have been created by other server plugins will still be called. |
| 101 | +
|
| 102 | + Example: |
| 103 | +
|
| 104 | + .. code:: python |
| 105 | +
|
| 106 | + from players.entity import Player |
| 107 | + from memory.hooks import hooks_disabled |
| 108 | +
|
| 109 | + # Get a Player instance of the player with index 1 |
| 110 | + player = Player(1) |
| 111 | +
|
| 112 | + # Damage the player. This would call e. g. on_take_damage hooks |
| 113 | + player.take_damage(5) |
| 114 | +
|
| 115 | + # To avoid calling the on_take_damage hooks, use the following: |
| 116 | + with hooks_disabled() |
| 117 | + player.take_damage(5) |
| 118 | + """ |
| 119 | + old = get_hooks_disabled() |
| 120 | + set_hooks_disabled(disabled) |
| 121 | + try: |
| 122 | + yield |
| 123 | + finally: |
| 124 | + set_hooks_disabled(old) |
0 commit comments