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