Files
DemonEditor/app/commons.py

82 lines
1.9 KiB
Python
Raw Normal View History

2017-11-25 15:55:24 +03:00
import logging
2017-10-26 01:23:05 +03:00
from functools import wraps
from threading import Thread, Timer
2017-10-26 01:23:05 +03:00
2017-11-14 19:20:16 +03:00
from gi.repository import GLib
2017-12-21 12:38:45 +03:00
_LOG_FILE = "demon-editor.log"
2017-11-25 15:55:24 +03:00
_DATE_FORMAT = "%d-%m-%y %H:%M:%S"
2020-05-19 11:39:12 +03:00
_LOGGER_NAME = None
2019-05-12 16:26:19 +03:00
def init_logger():
2020-05-19 11:39:12 +03:00
global _LOGGER_NAME
_LOGGER_NAME = "main_logger"
2019-05-12 16:26:19 +03:00
logging.Logger(_LOGGER_NAME)
logging.basicConfig(level=logging.INFO,
format="%(asctime)s %(message)s",
datefmt=_DATE_FORMAT,
2020-05-19 11:39:12 +03:00
handlers=[logging.FileHandler(_LOG_FILE), logging.StreamHandler()])
2019-05-12 16:26:19 +03:00
log("Logging is enabled.", level=logging.INFO)
2017-11-25 15:55:24 +03:00
2020-07-11 12:58:03 +03:00
def log(message, level=logging.ERROR, debug=False, fmt_message="{}"):
""" The main logging function. """
logger = logging.getLogger(_LOGGER_NAME)
if debug:
from traceback import format_exc
logger.log(level, fmt_message.format(format_exc()))
else:
logger.log(level, message)
2017-11-25 15:55:24 +03:00
2017-11-14 19:20:16 +03:00
def run_idle(func):
""" Runs a function with a lower priority """
@wraps(func)
def wrapper(*args, **kwargs):
GLib.idle_add(func, *args, **kwargs)
return wrapper
2017-10-26 01:23:05 +03:00
def run_task(func):
""" Runs function in separate thread """
@wraps(func)
def wrapper(*args, **kwargs):
2017-11-14 19:20:16 +03:00
task = Thread(target=func, args=args, kwargs=kwargs, daemon=True)
2017-10-26 01:23:05 +03:00
task.start()
2017-11-25 15:55:24 +03:00
return wrapper
def run_with_delay(timeout=5):
""" Starts the function with a delay.
If the previous timer still works, it will canceled!
"""
def run_with(func):
timer = None
@wraps(func)
def wrapper(*args, **kwargs):
nonlocal timer
if timer and timer.is_alive():
timer.cancel()
def run():
2021-02-23 11:10:06 +03:00
GLib.idle_add(func, priority=GLib.PRIORITY_LOW, *args, **kwargs)
timer = Timer(interval=timeout, function=run)
timer.start()
return wrapper
return run_with
2017-10-26 01:23:05 +03:00
if __name__ == "__main__":
pass