Added interactive diff gui
[ugit.git] / py / observer.py
blob7048cbd9ee3111ee11b75331d432017105f86dea
1 #!/usr/bin/env python
2 from pprint import pformat
4 class Observer (object):
5 '''Observers receive notify(*attributes) messages from their
6 subjects whenever new data arrives. This notify() message signifies
7 that an observer should update its internal state/view.'''
9 def __init__ (self):
10 self.__attribute_adapter = {}
11 self.__subjects = {}
12 self.__debug = False
14 def set_debug (self, enabled):
15 self.__debug = enabled
17 def notify (self, *attributes):
18 '''Called by the model to notify Observers about changes.'''
19 # We can be notified about multiple attribute changes at once
20 for attr in attributes:
22 if attr not in self.__subjects: continue
24 # The model corresponding to attribute
25 model = self.__subjects[attr]
27 # The new value for updating
28 value = model.getattr (attr)
30 # Allow mapping from model to observer attributes
31 if attr in self.__attribute_adapter:
32 attr = self.__attribute_adapter[attr]
34 # Call the concrete observer's notification method
35 notify = model.get_notify()
36 model.set_notify (False)
38 self.subject_changed (model, attr, value)
40 model.set_notify (notify)
42 if not self.__debug: continue
44 print ("Objserver::notify ("
45 + pformat (attributes) + "):")
46 print model, "\n"
49 def subject_changed (self, model, attr, value):
50 '''This method handles updating of the observer/UI.
51 This must be implemented in each concrete observer class.'''
53 msg = 'Concrete Observers must override subject_changed().'
54 raise NotImplementedError, msg
56 def add_subject (self, model, model_attr):
57 self.__subjects[model_attr] = model
59 def add_attribute_adapter (self, model_attr, observer_attr):
60 self.__attribute_adapter[model_attr] = observer_attr