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