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