new object pluginset
[myslice.git] / engine / plugin.py
1 # this is the abstract interface for Plugin instances
2 # so it should be specialized in real plugin classes
3 # like e.g. plugins.simplelist.SimpleList
4
5 import json
6
7 from django.template.loader import render_to_string
8
9 from engine.pluginset import PluginSet
10 from engine.prelude import Prelude
11
12 #################### 
13 # set DEBUG to
14 # . False : silent
15 # . [ 'SliceList', 'TabbedView' ] : to debug these classes
16 # . True : to debug all plugin
17
18 DEBUG= False
19 #DEBUG= [ 'SimpleList' ]
20
21 # decorator to deflect calls on Plugin to its PluginSet
22 def to_prelude (method):
23     def actual (self, *args, **kwds):
24         prelude_method=Prelude.__dict__[method.__name__]
25         return prelude_method(self.pluginset.prelude,*args, **kwds)
26     return actual
27
28 class Plugin:
29
30     # using a simple incremental scheme to generate domids for now
31     # we just need this to be unique in a page
32     domid=0
33
34     @staticmethod
35     def newdomid():
36         Plugin.domid += 1
37         return "plugin-%d"%Plugin.domid
38
39     ########## 
40     # Constructor
41     #### mandatory
42     # . pluginset: the context of the request being served
43     # . title: is used visually for displaying the widget
44     #### optional
45     # . togglable: whether it can be turned on and off (like PleKitToggle)
46     # . toggled: if togglable, what's the initial status
47     # . visible: if not set the plugin does not show up at all
48     #            (not quite sure what this was for)
49     #### internal data
50     # . domid: created internally, but can be set at creation time if needed
51     #          useful for hand-made css, or for selecting an active plugin in a composite
52     # . rank: this is for plugins sons of a composite plugin
53     #### custom
54     # any other setting can also be set when creating the object, like
55     # p=Plugin(foo='bar')
56     # which will result in 'foo' being accessible to the template engine
57     # 
58     def __init__ (self, pluginset, title, domid=None,
59                   visible=True, togglable=True, toggled=True, **settings):
60         self.pluginset = pluginset
61         self.title=title
62         if not domid: domid=Plugin.newdomid()
63         self.domid=domid
64         self.classname=self._classname()
65         self.visible=visible
66         self.togglable=togglable
67         self.toggled=toggled
68         # what comes from subclasses
69         for (k,v) in settings.iteritems():
70             setattr(self,k,v)
71             if self.need_debug(): print "%s init - subclass setting %s"%(self.classname,k)
72         # minimal debugging
73         if self.need_debug():
74             print "%s init dbg .... BEG"%self.classname
75             for (k,v) in self.__dict__.items(): print "dbg %s:%s"%(k,v)
76             print "%s init dbg .... END"%self.classname
77         # do this only once the structure is fine
78         self.pluginset.record_plugin(self)
79
80     def _classname (self): 
81         try:    return self.__class__.__name__
82         except: return 'Plugin'
83
84     ##########
85     def need_debug (self):
86         if not DEBUG:           return False
87         if DEBUG is True:       return True
88         else:                   return self.classname in DEBUG
89
90     def setting_json (self, setting):
91         # TMP: js world expects plugin_uuid
92         if setting=='plugin_uuid':
93             value=self.domid
94         elif setting=='query_uuid':
95             try: value=self.query.uuid
96             except: return '%s:"undefined"'%setting
97         else:
98             value=getattr(self,setting,None)
99             if not value: value = "unknown-setting-%s"%setting
100         # first try to use to_json method (json.dumps not working on class instances)
101         try:    value_json=value.to_json()
102         except: value_json=json.dumps(value,separators=(',',':'))
103         return "%s:%s"%(setting,value_json)
104
105     # expose in json format to js the list of fields as described in json_settings_list()
106     # and add plugin_uuid: domid in the mix
107     # NOTE this plugin_uuid thing might occur in js files from joomla/js, ** do not rename **
108     def settings_json (self):
109         result = "{"
110         result += ",".join([ self.setting_json(setting) for setting in self.json_settings_list() ])
111         result += "}"
112         return result
113
114     # returns the html code for that plugin
115     # in essence, wraps the results of self.render_content ()
116     def render (self, request):
117         # call render_content
118         plugin_content = self.render_content (request)
119         # shove this into plugin.html
120         env = {}
121         env ['plugin_content']= plugin_content
122         env.update(self.__dict__)
123         result = render_to_string ('plugin.html',env)
124
125         # as a first approximation we're only concerned with plugins that are associated with a query
126         # other simpler plugins that only deal with layout do not need this
127         if 'query' in self.__dict__:
128             env ['settings_json' ] = self.settings_json()
129             # compute plugin-specific initialization
130             js_init = render_to_string ( 'plugin-setenv.js', env )
131             self.add_js_chunks (js_init)
132         
133         # interpret the result of requirements ()
134         self.handle_requirements (request)
135
136         return result
137         
138     # you may redefine this completely, but if you don't we'll just use methods 
139     # . template_file() to find out which template to use, and 
140     # . template_env() to compute a dictionary to pass along to the templating system
141     def render_content (self, request):
142         """Should return an HTML fragment"""
143         template = self.template_file()
144         env=self.template_env(request)
145         if not isinstance (env,dict):
146             raise Exception, "%s.template_env returns wrong type"%self.classname
147         result=render_to_string (template, env)
148         if self.need_debug():
149             print "%s.render_content: BEG --------------------"%self.classname
150             print "template=%s"%template
151             print "env.keys=%s"%env.keys()
152             #print "env=%s"%env
153             #print result
154             print "%s.render_content: END --------------------"%self.classname
155         return result
156
157     # or from the result of self.requirements()
158     def handle_requirements (self, request):
159         try:
160             d=self.requirements()
161             for (k,v) in d.iteritems():
162                 if self.need_debug():
163                     print "%s: handling requirement %s"%(self.classname,v)
164                 method_name='add_'+k
165                 method=PluginSet.__dict__[method_name]
166                 method(self.pluginset,v)
167         except AttributeError: 
168             # most likely the object does not have that method defined, which is fine
169             pass
170         except:
171             import traceback
172             traceback.print_exc()
173             pass
174
175     #################### requirements/prelude management
176     # just forward to self.pluginset - see decorator above
177     @to_prelude
178     def add_js_files (self):pass
179     @to_prelude
180     def add_css_files (self):pass
181     @to_prelude
182     def add_js_chunks (self):pass
183     @to_prelude
184     def add_css_chunks (self):pass
185
186     ######################################## abstract interface
187     # your plugin is expected to implement either 
188     # (*) def render_content(self, request) -> html fragment
189     # -- or --
190     # (*) def template_file (self) -> filename
191     #   relative to STATIC 
192     # (*) def template_env (self, request) -> dict
193     #   this is the variable->value association used to render the template
194     # in which case the html template will be used
195
196     # if you see this string somewhere your template_file() code is not kicking in
197     def template_file (self):           return "undefined_template"
198     def template_env (self, request):   return {}
199
200 #    # tell the framework about requirements (for the document <header>)
201 #    # the notion of 'Media' in django provides for medium-dependant
202 #    # selection of css files
203 #    # as a first attempt however we keep a flat model for now
204 #    # can use one string instead of a list or tuple if needed, 
205 #    # see requirements.py for details
206 #    def requirements (self): 
207 #        return { 'js_files' : [],       # a list of relative paths for js input files
208 #                 'css_files': [],       # ditto for css, could have been a dict keyed on
209 #                                        # media instead
210 #                 'js_chunk' : [],       # (lines of) verbatim javascript code 
211 #                 'css_chunk': [],       # likewise for css scripts
212 #                 }
213     
214 #    # for better performance
215 #    # you can specify a list of keys that won't be exposed as json attributes
216 #    def exclude_from_json (self): return []
217
218     # mandatory : define the fields that need to be exposed to json as part of 
219     # plugin initialization
220     # mention 'domid' if you need plugin_uuid
221     # also 'query_uuid' gets replaced with query.uuid
222     def json_settings_list (self): return ['json_settings_list-must-be-redefined']
223