2018-10-30 14:58:48 +00:00
|
|
|
import itertools, time, traceback, typing
|
|
|
|
from src import Logging, utils
|
2016-03-29 11:56:58 +00:00
|
|
|
|
2018-07-15 22:53:59 +00:00
|
|
|
PRIORITY_URGENT = 0
|
|
|
|
PRIORITY_HIGH = 1
|
|
|
|
PRIORITY_MEDIUM = 2
|
|
|
|
PRIORITY_LOW = 3
|
2018-09-09 16:08:38 +00:00
|
|
|
PRIORITY_MONITOR = 4
|
2018-07-15 22:53:59 +00:00
|
|
|
|
2018-09-09 16:08:38 +00:00
|
|
|
DEFAULT_PRIORITY = PRIORITY_MEDIUM
|
2018-09-26 17:26:10 +00:00
|
|
|
DEFAULT_EVENT_DELIMITER = "."
|
|
|
|
DEFAULT_MULTI_DELIMITER = "|"
|
2018-08-31 11:55:52 +00:00
|
|
|
|
2018-10-30 14:58:48 +00:00
|
|
|
CALLBACK_TYPE = typing.Callable[["Event"], typing.Any]
|
|
|
|
|
2016-03-29 11:56:58 +00:00
|
|
|
class Event(object):
|
2019-06-26 10:01:09 +00:00
|
|
|
def __init__(self, name: str, kwargs):
|
2016-07-13 23:42:17 +00:00
|
|
|
self.name = name
|
2016-03-29 11:56:58 +00:00
|
|
|
self.kwargs = kwargs
|
|
|
|
self.eaten = False
|
2018-10-30 14:58:48 +00:00
|
|
|
def __getitem__(self, key: str) -> typing.Any:
|
2016-03-29 11:56:58 +00:00
|
|
|
return self.kwargs[key]
|
2018-10-30 14:58:48 +00:00
|
|
|
def get(self, key: str, default=None) -> typing.Any:
|
2016-03-29 11:56:58 +00:00
|
|
|
return self.kwargs.get(key, default)
|
2018-10-30 14:58:48 +00:00
|
|
|
def __contains__(self, key: str) -> bool:
|
2016-03-29 11:56:58 +00:00
|
|
|
return key in self.kwargs
|
|
|
|
def eat(self):
|
|
|
|
self.eaten = True
|
|
|
|
|
2019-06-26 10:01:09 +00:00
|
|
|
class EventHook(object):
|
|
|
|
def __init__(self, event_name: str, func: CALLBACK_TYPE,
|
2019-07-28 11:35:04 +00:00
|
|
|
context: typing.Optional[str], priority: int,
|
|
|
|
kwargs: typing.List[typing.Tuple[str, typing.Any]]):
|
2019-05-18 17:35:23 +00:00
|
|
|
self.event_name = event_name
|
2019-06-26 10:01:09 +00:00
|
|
|
self.function = func
|
2019-05-10 15:11:22 +00:00
|
|
|
self.context = context
|
2019-06-26 10:01:09 +00:00
|
|
|
self.priority = priority
|
|
|
|
self.docstring = utils.parse.docstring(func.__doc__ or "")
|
2018-09-30 16:29:09 +00:00
|
|
|
|
2019-07-28 11:35:04 +00:00
|
|
|
self._kwargs = {}
|
|
|
|
self._multi_kwargs = {}
|
|
|
|
for key, value in kwargs:
|
|
|
|
if key in self._multi_kwargs:
|
|
|
|
self._multi_kwargs[key].append(value)
|
|
|
|
elif key in self._kwargs:
|
|
|
|
self._multi_kwargs[key] = [self._kwargs.pop(key), value]
|
|
|
|
else:
|
|
|
|
self._kwargs[key] = value
|
|
|
|
|
2018-10-30 14:58:48 +00:00
|
|
|
def call(self, event: Event) -> typing.Any:
|
2016-03-29 11:56:58 +00:00
|
|
|
return self.function(event)
|
|
|
|
|
2019-07-28 11:35:04 +00:00
|
|
|
def get_kwargs(self, key: str) -> typing.List[typing.Any]:
|
|
|
|
if key in self._kwargs:
|
|
|
|
return [self._kwargs[key]]
|
|
|
|
elif key in self._multi_kwargs:
|
|
|
|
return self._multi_kwargs[key].copy()
|
|
|
|
elif key in self.docstring.var_items:
|
2019-07-28 17:07:01 +00:00
|
|
|
return self.docstring.var_items[key]
|
2019-07-28 11:35:04 +00:00
|
|
|
elif key in self.docstring.items:
|
2019-07-28 17:07:01 +00:00
|
|
|
return [self.docstring.items[key]]
|
2019-07-28 11:35:04 +00:00
|
|
|
return []
|
|
|
|
def get_kwarg(self, key: str, default: typing.Any=None) -> typing.Any:
|
|
|
|
return (self.get_kwargs(key) or [default])[0]
|
2018-09-30 16:29:09 +00:00
|
|
|
|
2019-06-26 10:01:09 +00:00
|
|
|
class Events(object):
|
|
|
|
def __init__(self, root: "EventRoot", path: typing.List[str],
|
|
|
|
context: typing.Optional[str]):
|
|
|
|
self._root = root
|
|
|
|
self._path = path
|
|
|
|
self._context = context
|
|
|
|
|
|
|
|
def new_root(self):
|
|
|
|
return self._root._new_root()
|
|
|
|
|
|
|
|
def new_context(self, context: str):
|
|
|
|
return self._root._new_context(context)
|
|
|
|
|
2019-01-30 19:35:43 +00:00
|
|
|
def make_event(self, **kwargs):
|
2019-06-26 10:01:09 +00:00
|
|
|
return self._root._make_event(self._path, kwargs)
|
2018-10-30 17:49:35 +00:00
|
|
|
|
2019-06-26 10:01:09 +00:00
|
|
|
def on(self, subname):
|
|
|
|
parts = subname.split(DEFAULT_EVENT_DELIMITER)
|
|
|
|
new_path = self._path + parts
|
2018-10-01 15:04:06 +00:00
|
|
|
|
2019-06-26 10:01:09 +00:00
|
|
|
return Events(self._root, new_path, self._context)
|
|
|
|
|
|
|
|
def hook(self, func: CALLBACK_TYPE, priority: int = DEFAULT_PRIORITY,
|
|
|
|
**kwargs):
|
2019-07-28 11:35:04 +00:00
|
|
|
self._hook(func, priority, list(kwargs.items()))
|
|
|
|
def _hook(self, func: CALLBACK_TYPE, priority: int = DEFAULT_PRIORITY,
|
|
|
|
kwargs: typing.List[typing.Tuple[str, typing.Any]] = []):
|
2019-06-26 10:01:09 +00:00
|
|
|
self._root._hook(self._path, func, self._context, priority, kwargs)
|
|
|
|
|
|
|
|
def call(self, **kwargs):
|
|
|
|
return self._root._call(self._path, kwargs, True, self._context, None)
|
|
|
|
def call_unsafe(self, **kwargs):
|
|
|
|
return self._root._call(self._path, kwargs, False, self._context, None)
|
|
|
|
|
|
|
|
def _call_limited(self, maximum: int, safe: bool, kwargs):
|
|
|
|
return self._root._call(self._path, kwargs, safe, self._context,
|
|
|
|
maximum)
|
|
|
|
def call_limited(self, maximum: int, **kwargs):
|
|
|
|
return self._call_limited(maximum, True, kwargs)
|
|
|
|
def call_limited_unsafe(self, maximum: int, **kwargs):
|
|
|
|
return self._call_limited(maximum, False, kwargs)
|
|
|
|
|
|
|
|
def call_for_result(self, default=None, **kwargs):
|
2019-07-13 10:04:37 +00:00
|
|
|
return (self._call_limited(1, True, kwargs) or [default])[0]
|
2019-06-26 10:01:09 +00:00
|
|
|
def call_for_result_unsafe(self, default=None, **kwargs):
|
2019-07-13 10:04:37 +00:00
|
|
|
return (self._call_limited(1, False, kwargs) or [default])[0]
|
2019-06-26 10:01:09 +00:00
|
|
|
|
|
|
|
def get_children(self):
|
|
|
|
return self._root._get_children(self._path)
|
|
|
|
def get_hooks(self):
|
|
|
|
return self._root._get_hooks(self._path)
|
2019-06-22 11:21:44 +00:00
|
|
|
|
2019-06-26 10:01:09 +00:00
|
|
|
def purge_context(self, context: str):
|
|
|
|
self._root._purge_context(context)
|
2018-12-05 15:18:40 +00:00
|
|
|
|
2019-06-26 10:01:09 +00:00
|
|
|
class EventRoot(object):
|
|
|
|
def __init__(self, log: Logging.Log):
|
|
|
|
self.log = log
|
|
|
|
self._hooks: typing.Dict[str, typing.List[EventHook]] = {}
|
|
|
|
|
|
|
|
def _make_event(self, path: typing.List[str], kwargs: dict):
|
|
|
|
return Event(self._path_str(path), kwargs)
|
|
|
|
|
|
|
|
def _new_context(self, context: str):
|
|
|
|
return Events(self, [], context)
|
|
|
|
def _new_root(self):
|
|
|
|
return EventRoot(self.log).wrap()
|
|
|
|
|
|
|
|
def wrap(self):
|
|
|
|
return Events(self, [], None)
|
|
|
|
|
|
|
|
def _path_str(self, path: typing.List[str]):
|
|
|
|
path_lower = [p.lower() for p in path]
|
|
|
|
return DEFAULT_EVENT_DELIMITER.join(path_lower)
|
|
|
|
|
|
|
|
def _hook(self, path: typing.List[str], func: CALLBACK_TYPE,
|
|
|
|
context: typing.Optional[str], priority: int, kwargs: dict
|
|
|
|
) -> EventHook:
|
|
|
|
path_str = self._path_str(path)
|
|
|
|
new_hook = EventHook(path_str, func, context, priority, kwargs)
|
|
|
|
|
|
|
|
if not path_str in self._hooks:
|
|
|
|
self._hooks[path_str] = []
|
|
|
|
hook_array = self._hooks[path_str]
|
|
|
|
|
2019-07-30 14:09:34 +00:00
|
|
|
hook_position = 0
|
2019-06-26 10:01:09 +00:00
|
|
|
for i, other_hook in enumerate(hook_array):
|
2019-07-30 14:12:29 +00:00
|
|
|
if new_hook.priority > other_hook.priority:
|
2019-07-30 14:09:34 +00:00
|
|
|
hook_position = i
|
2019-06-26 10:01:09 +00:00
|
|
|
break
|
2019-07-30 14:09:34 +00:00
|
|
|
|
|
|
|
hook_array.insert(hook_position, new_hook)
|
2019-06-26 10:01:09 +00:00
|
|
|
return new_hook
|
|
|
|
|
|
|
|
def _call(self, path: typing.List[str], kwargs: dict, safe: bool,
|
|
|
|
context: typing.Optional[str], maximum: typing.Optional[int]
|
|
|
|
) -> typing.List[typing.Any]:
|
2019-06-26 10:42:23 +00:00
|
|
|
if not utils.is_main_thread():
|
|
|
|
raise RuntimeError("Can't call events outside of main thread")
|
|
|
|
|
2019-06-26 10:01:09 +00:00
|
|
|
returns: typing.List[typing.Any] = []
|
|
|
|
path_str = self._path_str(path)
|
|
|
|
if not path_str in self._hooks:
|
2018-12-05 15:18:40 +00:00
|
|
|
self.log.trace("not calling non-hooked event \"%s\" (params: %s)",
|
2019-07-15 13:27:55 +00:00
|
|
|
[path_str, str(kwargs)])
|
2018-12-05 15:18:40 +00:00
|
|
|
return returns
|
|
|
|
|
2018-11-26 14:23:20 +00:00
|
|
|
self.log.trace("calling event: \"%s\" (params: %s)",
|
2019-07-15 13:27:55 +00:00
|
|
|
[path_str, str(kwargs)])
|
2018-08-28 11:23:57 +00:00
|
|
|
start = time.monotonic()
|
|
|
|
|
2019-06-26 10:01:09 +00:00
|
|
|
hooks = self._hooks[path_str]
|
|
|
|
if maximum:
|
|
|
|
hooks = hooks[:maximum]
|
|
|
|
event = self._make_event(path, kwargs)
|
|
|
|
|
|
|
|
for hook in hooks:
|
2018-09-01 17:27:10 +00:00
|
|
|
if event.eaten:
|
2016-03-29 11:56:58 +00:00
|
|
|
break
|
2019-06-26 10:01:09 +00:00
|
|
|
|
2016-07-13 23:42:17 +00:00
|
|
|
try:
|
2019-06-26 10:01:09 +00:00
|
|
|
returned = hook.call(event)
|
2016-07-13 23:42:17 +00:00
|
|
|
except Exception as e:
|
2018-10-16 13:53:37 +00:00
|
|
|
if safe:
|
|
|
|
self.log.error("failed to call event \"%s\"",
|
2019-06-26 10:01:09 +00:00
|
|
|
[path_str], exc_info=True)
|
|
|
|
continue
|
2018-10-16 13:53:37 +00:00
|
|
|
else:
|
2018-10-01 15:04:06 +00:00
|
|
|
raise
|
2019-06-26 10:01:09 +00:00
|
|
|
returns.append(returned)
|
2019-02-14 10:36:11 +00:00
|
|
|
|
2018-09-01 17:27:10 +00:00
|
|
|
total_milliseconds = (time.monotonic() - start) * 1000
|
2018-11-26 14:23:20 +00:00
|
|
|
self.log.trace("event \"%s\" called in %fms",
|
2019-06-26 10:01:09 +00:00
|
|
|
[path_str, total_milliseconds])
|
2018-08-28 11:24:39 +00:00
|
|
|
|
2016-03-29 11:56:58 +00:00
|
|
|
return returns
|
2018-07-08 10:18:55 +00:00
|
|
|
|
2019-06-26 10:01:09 +00:00
|
|
|
def _purge_context(self, context: str):
|
|
|
|
context_hooks: typing.Dict[str, typing.List[EventHook]] = {}
|
|
|
|
for path in self._hooks.keys():
|
|
|
|
for hook in self._hooks[path]:
|
|
|
|
if hook.context == context:
|
|
|
|
if not path in context_hooks:
|
|
|
|
context_hooks[path] = []
|
|
|
|
context_hooks[path].append(hook)
|
|
|
|
for path in context_hooks:
|
|
|
|
for hook in context_hooks[path]:
|
|
|
|
self._hooks[path].remove(hook)
|
|
|
|
if not self._hooks[path]:
|
|
|
|
del self._hooks[path]
|
|
|
|
|
|
|
|
def _get_children(self, path):
|
|
|
|
path_prefix = "%s%s" % (self._path_str(path), DEFAULT_EVENT_DELIMITER)
|
|
|
|
matches = []
|
|
|
|
for key in self._hooks.keys():
|
|
|
|
if key.startswith(path_prefix):
|
|
|
|
matches.append(key.replace(path_prefix, "", 1))
|
|
|
|
return matches
|
|
|
|
def _get_hooks(self, path):
|
|
|
|
path_str = self._path_str(path)
|
|
|
|
if path_str in self._hooks:
|
|
|
|
return self._hooks[path_str][:]
|
|
|
|
return []
|