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