renamings of js stuff
[myslice.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= [ 'SliceList' ]
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 _py_classname (self): 
84         try:    return self.__class__.__name__
85         except: return 'Plugin'
86
87     def _js_classname (self): 
88         try:    return self.plugin_classname ()
89         except: return self._py_classname()
90
91     ##########
92     def need_debug (self):
93         if not DEBUG:           return False
94         if DEBUG is True:       return True
95         else:                   return self.classname in DEBUG
96
97     def setting_json (self, setting):
98         # TMP: js world expects plugin_uuid
99         if setting=='plugin_uuid':
100             value=self.domid
101         elif setting=='query_uuid':
102             try: value=self.query.query_uuid
103             except: return '%s:"undefined"'%setting
104         else:
105             value=getattr(self,setting,None)
106             if not value: value = "unknown-setting-%s"%setting
107         # first try to use to_json method (json.dumps not working on class instances)
108         try:    value_json=value.to_json()
109         except: value_json=json.dumps(value,separators=(',',':'))
110         return "%s:%s"%(setting,value_json)
111
112     # expose in json format to js the list of fields as described in json_settings_list()
113     # and add plugin_uuid: domid in the mix
114     # NOTE this plugin_uuid thing might occur in js files from joomla/js, ** do not rename **
115     def settings_json (self):
116         exposed_settings=self.json_settings_list()
117         if 'query' in exposed_settings:
118             print "WARNING, cannot expose 'query' directly in json_settings_list, query_uuid is enough"
119         result = "{"
120         result += ",".join([ self.setting_json(setting) for setting in self.json_settings_list() ])
121         result += "}"
122         return result
123
124     # as a first approximation, only plugins that are associated with a query
125     # need to be prepared for js - meaning their json settings get exposed to js
126     # others just get displayed and that's it
127     def export_json_settings (self):
128         return 'query_uuid' in self.json_settings_list()
129     
130     # by default we create a timer if there's a query attached, redefine to change this behaviour
131     def start_with_spin (self):
132         return self.export_json_settings()
133
134     # returns the html code for that plugin
135     # in essence, wraps the results of self.render_content ()
136     def render (self, request):
137         # call render_content
138         plugin_content = self.render_content (request)
139         # shove this into plugin.html
140         env = {}
141         env ['plugin_content']= plugin_content
142         # need_spin is used in plugin.html
143         self.need_spin=self.start_with_spin()
144         env.update(self.__dict__)
145         if self.need_debug(): 
146             print "rendering plugin.html with env keys %s"%env.keys()
147         result = render_to_string ('plugin.html',env)
148
149         # export this only for relevant plugins
150         if self.export_json_settings():
151             env ['settings_json' ] = self.settings_json()
152             # compute plugin-specific initialization
153             js_init = render_to_string ( 'plugin-init.js', env )
154             self.add_js_chunks (js_init)
155         
156         # interpret the result of requirements ()
157         self.handle_requirements (request)
158
159         return result
160         
161     # you may redefine this completely, but if you don't we'll just use methods 
162     # . template_file() to find out which template to use, and 
163     # . template_env() to compute a dictionary to pass along to the templating system
164     def render_content (self, request):
165         """Should return an HTML fragment"""
166         template = self.template_file()
167         env=self.template_env(request)
168         if not isinstance (env,dict):
169             raise Exception, "%s.template_env returns wrong type"%self.classname
170         result=render_to_string (template, env)
171         if self.need_debug():
172             print "%s.render_content: BEG --------------------"%self.classname
173             print "template=%s"%template
174             print "env.keys=%s"%env.keys()
175             #print "env=%s"%env
176             #print result
177             print "%s.render_content: END --------------------"%self.classname
178         return result
179
180     # or from the result of self.requirements()
181     def handle_requirements (self, request):
182         try:
183             d=self.requirements()
184             for (k,v) in d.iteritems():
185                 if self.need_debug():
186                     print "%s: handling requirement %s"%(self.classname,v)
187                 # e.g. js_files -> add_js_files
188                 method_name='add_'+k
189                 method=Page.__dict__[method_name]
190                 method(self.page,v)
191         except AttributeError: 
192             # most likely the object does not have that method defined, which is fine
193             pass
194         except:
195             import traceback
196             traceback.print_exc()
197             pass
198
199     #################### requirements/prelude management
200     # just forward to our prelude instance - see decorator above
201     @to_prelude
202     def add_js_files (self):pass
203     @to_prelude
204     def add_css_files (self):pass
205     @to_prelude
206     def add_js_chunks (self):pass
207     @to_prelude
208     def add_css_chunks (self):pass
209
210     ######################################## abstract interface
211     # your plugin is expected to implement either 
212     # (*) def render_content(self, request) -> html fragment
213     # -- or --
214     # (*) def template_file (self) -> filename
215     #   relative to STATIC 
216     # (*) def template_env (self, request) -> dict
217     #   this is the variable->value association used to render the template
218     # in which case the html template will be used
219
220     # if you see this string somewhere your template_file() code is not kicking in
221     def template_file (self):           return "undefined_template"
222     def template_env (self, request):   return {}
223
224 #    # tell the framework about requirements (for the document <header>)
225 #    # the notion of 'Media' in django provides for medium-dependant
226 #    # selection of css files
227 #    # as a first attempt however we keep a flat model for now
228 #    # can use one string instead of a list or tuple if needed, 
229 #    # see requirements.py for details
230 #    def requirements (self): 
231 #        return { 'js_files' : [],       # a list of relative paths for js input files
232 #                 'css_files': [],       # ditto for css, could have been a dict keyed on
233 #                                        # media instead
234 #                 'js_chunk' : [],       # (lines of) verbatim javascript code 
235 #                 'css_chunk': [],       # likewise for css scripts
236 #                 }
237     
238 #    # for better performance
239 #    # you can specify a list of keys that won't be exposed as json attributes
240 #    def exclude_from_json (self): return []
241
242     # mandatory : define the fields that need to be exposed to json as part of 
243     # plugin initialization
244     # mention 'domid' if you need plugin_uuid
245     # also 'query_uuid' gets replaced with query.query_uuid
246     def json_settings_list (self): return ['json_settings_list-must-be-redefined']
247
248     # might also define these ones:
249     #
250     # see e.g. slicelist.py that piggybacks simplelist js code
251     # def plugin_classname (self)
252     #
253     # whether we export the json settings to js
254     # def export_json_settings (self)
255     #
256     # whether we show an initial spinner
257     # def start_with_spin (self)