split engine/ into manifold/ (backend oriented) and unfold/ (the UI)
[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= [ 'QuickFilter' ]
20
21 # decorator to deflect calls on Plugin to its Prelude through self.page.prelude
22 def to_prelude (method):
23     def actual (self, *args, **kwds):
24         prelude_method=Prelude.__dict__[method.__name__]
25         return prelude_method(self.page.prelude,*args, **kwds)
26     return actual
27
28 class Plugin:
29
30     # using a simple incremental scheme to generate domids for now
31     # we just need this to be unique in a page
32     domid=0
33
34     @staticmethod
35     def newdomid():
36         Plugin.domid += 1
37         return "plugin-%d"%Plugin.domid
38
39     ########## 
40     # Constructor
41     #### mandatory
42     # . page: the context of the request being served
43     # . title: is used visually for displaying the widget
44     #### optional
45     # . togglable: whether it can be turned on and off (like PleKitToggle)
46     # . toggled: if togglable, what's the initial status
47     # . visible: if not set the plugin does not show up at all
48     #            (not quite sure what this was for)
49     #### internal data
50     # . domid: created internally, but can be set at creation time if needed
51     #          useful for hand-made css, or for selecting an active plugin in a composite
52     # . rank: this is for plugins sons of a composite plugin
53     #### custom
54     # any other setting can also be set when creating the object, like
55     # p=Plugin(foo='bar')
56     # which will result in 'foo' being accessible to the template engine
57     # 
58     def __init__ (self, page, title, domid=None,
59                   visible=True, togglable=True, toggled=True, **settings):
60         self.page = page
61         self.title=title
62         # callers can provide their domid for css'ing 
63         if not domid: domid=Plugin.newdomid()
64         self.domid=domid
65         self.classname=self._py_classname()
66         self.plugin_classname=self._js_classname()
67         self.visible=visible
68         self.togglable=togglable
69         self.toggled=toggled
70         # what comes from subclasses
71         for (k,v) in settings.iteritems():
72             setattr(self,k,v)
73             if self.need_debug(): print "%s init - subclass setting %s"%(self.classname,k)
74         # minimal debugging
75         if self.need_debug():
76             print "%s init dbg .... BEG"%self.classname
77             for (k,v) in self.__dict__.items(): print "dbg %s:%s"%(k,v)
78             print "%s init dbg .... END"%self.classname
79         # do this only once the structure is fine
80         self.page.record_plugin(self)
81
82     def _py_classname (self): 
83         try:    return self.__class__.__name__
84         except: return 'Plugin'
85
86     def _js_classname (self): 
87         try:    return self.plugin_classname ()
88         except: return self._py_classname()
89
90     ##########
91     def need_debug (self):
92         if not DEBUG:           return False
93         if DEBUG is True:       return True
94         else:                   return self.classname in DEBUG
95
96     def setting_json (self, setting):
97         # TMP: js world expects plugin_uuid
98         if setting=='plugin_uuid':
99             value=self.domid
100         elif setting=='query_uuid':
101             try: value=self.query.uuid
102             except: return '%s:"undefined"'%setting
103         else:
104             value=getattr(self,setting,None)
105             if not value: value = "unknown-setting-%s"%setting
106         # first try to use to_json method (json.dumps not working on class instances)
107         try:    value_json=value.to_json()
108         except: value_json=json.dumps(value,separators=(',',':'))
109         return "%s:%s"%(setting,value_json)
110
111     # expose in json format to js the list of fields as described in json_settings_list()
112     # and add plugin_uuid: domid in the mix
113     # NOTE this plugin_uuid thing might occur in js files from joomla/js, ** do not rename **
114     def settings_json (self):
115         result = "{"
116         result += ",".join([ self.setting_json(setting) for setting in self.json_settings_list() ])
117         result += "}"
118         return result
119
120     # as a first approximation, only plugins that are associated with a query
121     # need to be prepared for js - meaning their json settings get exposed to js
122     # others just get displayed and that's it
123     def export_json_settings (self):
124         return 'query' in self.__dict__
125     
126     def start_with_spin (self):
127         return self.export_json_settings()
128
129     # returns the html code for that plugin
130     # in essence, wraps the results of self.render_content ()
131     def render (self, request):
132         # call render_content
133         plugin_content = self.render_content (request)
134         # shove this into plugin.html
135         env = {}
136         env ['plugin_content']= plugin_content
137         # need_spin is used in plugin.html
138         self.need_spin=self.start_with_spin()
139         env.update(self.__dict__)
140         result = render_to_string ('plugin.html',env)
141
142         # export this only for relevant plugins
143         if self.export_json_settings():
144             env ['settings_json' ] = self.settings_json()
145             # compute plugin-specific initialization
146             js_init = render_to_string ( 'plugin-setenv.js', env )
147             self.add_js_chunks (js_init)
148         
149         # interpret the result of requirements ()
150         self.handle_requirements (request)
151
152         return result
153         
154     # you may redefine this completely, but if you don't we'll just use methods 
155     # . template_file() to find out which template to use, and 
156     # . template_env() to compute a dictionary to pass along to the templating system
157     def render_content (self, request):
158         """Should return an HTML fragment"""
159         template = self.template_file()
160         env=self.template_env(request)
161         if not isinstance (env,dict):
162             raise Exception, "%s.template_env returns wrong type"%self.classname
163         result=render_to_string (template, env)
164         if self.need_debug():
165             print "%s.render_content: BEG --------------------"%self.classname
166             print "template=%s"%template
167             print "env.keys=%s"%env.keys()
168             #print "env=%s"%env
169             #print result
170             print "%s.render_content: END --------------------"%self.classname
171         return result
172
173     # or from the result of self.requirements()
174     def handle_requirements (self, request):
175         try:
176             d=self.requirements()
177             for (k,v) in d.iteritems():
178                 if self.need_debug():
179                     print "%s: handling requirement %s"%(self.classname,v)
180                 # e.g. js_files -> add_js_files
181                 method_name='add_'+k
182                 method=Page.__dict__[method_name]
183                 method(self.page,v)
184         except AttributeError: 
185             # most likely the object does not have that method defined, which is fine
186             pass
187         except:
188             import traceback
189             traceback.print_exc()
190             pass
191
192     #################### requirements/prelude management
193     # just forward to our prelude instance - see decorator above
194     @to_prelude
195     def add_js_files (self):pass
196     @to_prelude
197     def add_css_files (self):pass
198     @to_prelude
199     def add_js_chunks (self):pass
200     @to_prelude
201     def add_css_chunks (self):pass
202
203     ######################################## abstract interface
204     # your plugin is expected to implement either 
205     # (*) def render_content(self, request) -> html fragment
206     # -- or --
207     # (*) def template_file (self) -> filename
208     #   relative to STATIC 
209     # (*) def template_env (self, request) -> dict
210     #   this is the variable->value association used to render the template
211     # in which case the html template will be used
212
213     # if you see this string somewhere your template_file() code is not kicking in
214     def template_file (self):           return "undefined_template"
215     def template_env (self, request):   return {}
216
217 #    # tell the framework about requirements (for the document <header>)
218 #    # the notion of 'Media' in django provides for medium-dependant
219 #    # selection of css files
220 #    # as a first attempt however we keep a flat model for now
221 #    # can use one string instead of a list or tuple if needed, 
222 #    # see requirements.py for details
223 #    def requirements (self): 
224 #        return { 'js_files' : [],       # a list of relative paths for js input files
225 #                 'css_files': [],       # ditto for css, could have been a dict keyed on
226 #                                        # media instead
227 #                 'js_chunk' : [],       # (lines of) verbatim javascript code 
228 #                 'css_chunk': [],       # likewise for css scripts
229 #                 }
230     
231 #    # for better performance
232 #    # you can specify a list of keys that won't be exposed as json attributes
233 #    def exclude_from_json (self): return []
234
235     # mandatory : define the fields that need to be exposed to json as part of 
236     # plugin initialization
237     # mention 'domid' if you need plugin_uuid
238     # also 'query_uuid' gets replaced with query.uuid
239     def json_settings_list (self): return ['json_settings_list-must-be-redefined']
240
241     # might also define these ones:
242     #
243     # see e.g. slicelist.py that piggybacks simplelist js code
244     # def plugin_classname (self)
245     #
246     # whether we export the json settings to js
247     # def export_json_settings (self)
248     #
249     # whether we show an initial spinner
250     # def start_with_spin (self)