Source code for Karana.KUtils.MultibodyTUI.notify
import logging
from typing import Callable
from .terminal import critical, error, warn, info
[docs]
class Notifier:
"""Helper to maintain a single, current notification message
The notification is replaced whenever a new notification is
triggered with the same or higher priority.
"""
def __init__(self, on_notify: Callable | None = None):
"""Notifier constructor
Parameters
----------
on_notify: Callable | None
Optional callable invoked whenever the notification changes
"""
self._message = ""
self._priority = logging.NOTSET
self._on_notify = on_notify
@property
def message(self):
"""The current notification message"""
return self._message
[docs]
def __str__(self):
"""The current notification message"""
return self.message
[docs]
def __call__(self, message: str):
"""Notify an info message"""
self.info(message)
def _replace(self, message: str, priority: int):
"""Replace the notification if it has equal or higher priority
Parameters
----------
message: str
The notification message
priority: int
The notification priority from the range in the standard logging
library's constants
"""
if priority >= self._priority:
self._message = message
self._priority = priority
if self._on_notify:
self._on_notify()
[docs]
def critical(self, message: str):
"""Notify a critical error message"""
self._replace(critical(message), logging.CRITICAL)
[docs]
def error(self, message: str):
"""Notify an error message"""
self._replace(error(message), logging.ERROR)
[docs]
def warn(self, message: str):
"""Notify an error message"""
self._replace(warn(message), logging.WARNING)
[docs]
def info(self, message: str):
"""Notify an info message"""
self._replace(info(message), logging.INFO)
[docs]
def clear(self):
"""Reset the notification message"""
self._message = ""
self._priority = logging.NOTSET
if self._on_notify:
self._on_notify()
[docs]
def clear_priority(self):
"""Reset the notification message priority
This will keep the current message but allow lower priority
messages to replace it.
"""
self._priority = logging.NOTSET