changeset 516:7ee15fbe8c08

core: added priority management in triggers
author Goffi <goffi@goffi.org>
date Sat, 20 Oct 2012 18:18:40 +0200
parents 29b5ef129488
children 59b32c04e105
files src/tools/misc.py
diffstat 1 files changed, 10 insertions(+), 8 deletions(-) [+]
line wrap: on
line diff
--- a/src/tools/misc.py	Sat Oct 20 18:02:14 2012 +0200
+++ b/src/tools/misc.py	Sat Oct 20 18:18:40 2012 +0200
@@ -32,24 +32,26 @@
     def __init__(self):
         self.__triggers={}
 
-    def add(self, point_name, callback):
+    def add(self, point_name, callback, priority=0):
         """Add a trigger to a point
         @param point_name: name of the point when the trigger should be run
         @param callback: method to call at the trigger point
+        @param priority: callback will be called in priority order, biggest first
         """
         if not self.__triggers.has_key(point_name):
             self.__triggers[point_name]=[]
-        self.__triggers[point_name].append(callback)
+        self.__triggers[point_name].append((priority, callback))
+        self.__triggers[point_name].sort(key=lambda trigger_tuple: trigger_tuple[0], reverse=True)
 
     def remove(self, point_name, callback):
         """Remove a trigger from a point
         @param point_name: name of the point when the trigger should be run
         @param callback: method to remove, must exists in the trigger point"""
-        try:
-            self.__triggers[point_name].remove(callback)
-        except (KeyError,ValueError):
-            raise TriggerException("Trying to remove an unexisting trigger")
-            
+        for trigger_tuple in self.__triggers[point_name]:
+            if trigger_tuple[1] == callback:
+                self.__triggers[point_name].remove(trigger_tuple)
+                return
+        raise TriggerException("Trying to remove an unexisting trigger")
 
     def point(self, point_name, *args, **kwargs):
         """This put a trigger point
@@ -59,7 +61,7 @@
         if not self.__triggers.has_key(point_name):
             return True
 
-        for trigger in self.__triggers[point_name]:
+        for priority,trigger in self.__triggers[point_name]:
             if not trigger(*args, **kwargs):
                 return False
         return True