Debian Codegraph @

s_tui/sources/hook.py

raw symbols SCIP
1 #!/usr/bin/env python
2 #
3 # Copyright (C) 2017-2025 Alex Manuskin, Gil Tsuker
4 #
5 # This program is free software; you can redistribute it and/or
6 # modify it under the terms of the GNU General Public License
7 # as published by the Free Software Foundation; either version 2
8 # of the License, or (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with this program; if not, write to the Free Software
17 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
18
19 from __future__ import annotations
20
21 from collections.abc import Callable
22 from datetime import datetime, timedelta
23
24
25 class Hook:
26 """
27 Event handler that invokes an arbitrary callback when invoked.
28 If the timeout_milliseconds argument is greater than 0,
29 the hook will be suspended for n milliseconds after it's being invoked.
30 """
31
32 def __init__(
33 self,
34 callback: Callable[..., object],
35 timeout_milliseconds: int = 0,
36 *callback_args: object,
37 ) -> None:
38 self.callback = callback
39 self.timeout_milliseconds = timeout_milliseconds
40 self.callback_args = callback_args
41 self.ready_time = datetime.now()
42
43 def is_ready(self) -> bool:
44 """
45 Returns whether the hook is ready to invoke its callback or not
46 """
47
48 return datetime.now() >= self.ready_time
49
50 def invoke(self) -> None:
51 """
52 Run callback, optionally passing a variable number
53 of arguments `callback_args`
54 """
55
56 # Don't sleep a hook if it has never run
57 if self.timeout_milliseconds > 0:
58 self.ready_time = datetime.now() + timedelta(
59 milliseconds=self.timeout_milliseconds
60 )
61
62 self.callback(self.callback_args)