Source code for Karana.KUtils.MultibodyTUI.notify
"""Notifier class to create TUI notifications."""
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):
"""Create an instance of Notifier.
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):
"""Return the current notification message."""
return self._message
[docs]
def __str__(self):
"""Return 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 a warn 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 clearPriority(self):
"""Reset the notification message priority.
This will keep the current message but allow lower priority
messages to replace it.
"""
self._priority = logging.NOTSET