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