Anna Schumaker
735f2bba6e
And always run tasks marked for the idle queue in the idle queue, even if we're in the main thread. Signed-off-by: Anna Schumaker <Anna@NoWheyCreamery.com>
46 lines
1.1 KiB
Python
46 lines
1.1 KiB
Python
# Copyright 2019 (c) Anna Schumaker.
|
|
import threading
|
|
from gi.repository import GLib
|
|
|
|
events = { }
|
|
idle_queue = [ ]
|
|
event_lock = threading.Lock()
|
|
|
|
def cancel(name, func):
|
|
cb = events.get(name, [])
|
|
for event in cb:
|
|
if event[0] == func:
|
|
cb.remove(event)
|
|
if len(cb) == 0:
|
|
events.pop(name)
|
|
|
|
def clear():
|
|
events.clear()
|
|
idle_queue.clear()
|
|
|
|
def notify(name, *args):
|
|
for (func, idle) in events.get(name, []):
|
|
if idle == True:
|
|
with event_lock:
|
|
if (func, args) not in idle_queue:
|
|
idle_queue.append((func, args))
|
|
if len(idle_queue) == 1:
|
|
GLib.idle_add(notify_idle)
|
|
else:
|
|
func(*args)
|
|
|
|
def notify_idle():
|
|
with event_lock:
|
|
if len(idle_queue) == 0:
|
|
return False
|
|
(func, args) = idle_queue.pop(0)
|
|
more = len(idle_queue) > 0
|
|
func(*args)
|
|
return more
|
|
|
|
def register(name, func, idle=False):
|
|
cb = events.setdefault(name, [])
|
|
if func in [ n[0] for n in cb ]:
|
|
return
|
|
cb.append((func, idle))
|