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