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