ad88024c680e62e1357fa359d1b6ab71f8453525
[unfold.git] / engine / 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 engine.page import Page
10 from engine.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= [ 'SliceList' ]
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 - others just get displayed and that's it
122     def is_asynchroneous (self):
123         return 'query' in self.__dict__
124     
125     # returns the html code for that plugin
126     # in essence, wraps the results of self.render_content ()
127     def render (self, request):
128         # call render_content
129         plugin_content = self.render_content (request)
130         # shove this into plugin.html
131         env = {}
132         env ['plugin_content']= plugin_content
133         self.need_spin=self.is_asynchroneous()
134         env.update(self.__dict__)
135         result = render_to_string ('plugin.html',env)
136
137         # export this only for relevant plugins
138         if self.is_asynchroneous():
139             env ['settings_json' ] = self.settings_json()
140             # compute plugin-specific initialization
141             js_init = render_to_string ( 'plugin-setenv.js', env )
142             self.add_js_chunks (js_init)
143         
144         # interpret the result of requirements ()
145         self.handle_requirements (request)
146
147         return result
148         
149     # you may redefine this completely, but if you don't we'll just use methods 
150     # . template_file() to find out which template to use, and 
151     # . template_env() to compute a dictionary to pass along to the templating system
152     def render_content (self, request):
153         """Should return an HTML fragment"""
154         template = self.template_file()
155         env=self.template_env(request)
156         if not isinstance (env,dict):
157             raise Exception, "%s.template_env returns wrong type"%self.classname
158         result=render_to_string (template, env)
159         if self.need_debug():
160             print "%s.render_content: BEG --------------------"%self.classname
161             print "template=%s"%template
162             print "env.keys=%s"%env.keys()
163             #print "env=%s"%env
164             #print result
165             print "%s.render_content: END --------------------"%self.classname
166         return result
167
168     # or from the result of self.requirements()
169     def handle_requirements (self, request):
170         try:
171             d=self.requirements()
172             for (k,v) in d.iteritems():
173                 if self.need_debug():
174                     print "%s: handling requirement %s"%(self.classname,v)
175                 # e.g. js_files -> add_js_files
176                 method_name='add_'+k
177                 method=Page.__dict__[method_name]
178                 method(self.page,v)
179         except AttributeError: 
180             # most likely the object does not have that method defined, which is fine
181             pass
182         except:
183             import traceback
184             traceback.print_exc()
185             pass
186
187     #################### requirements/prelude management
188     # just forward to our prelude instance - see decorator above
189     @to_prelude
190     def add_js_files (self):pass
191     @to_prelude
192     def add_css_files (self):pass
193     @to_prelude
194     def add_js_chunks (self):pass
195     @to_prelude
196     def add_css_chunks (self):pass
197
198     ######################################## abstract interface
199     # your plugin is expected to implement either 
200     # (*) def render_content(self, request) -> html fragment
201     # -- or --
202     # (*) def template_file (self) -> filename
203     #   relative to STATIC 
204     # (*) def template_env (self, request) -> dict
205     #   this is the variable->value association used to render the template
206     # in which case the html template will be used
207
208     # if you see this string somewhere your template_file() code is not kicking in
209     def template_file (self):           return "undefined_template"
210     def template_env (self, request):   return {}
211
212 #    # tell the framework about requirements (for the document <header>)
213 #    # the notion of 'Media' in django provides for medium-dependant
214 #    # selection of css files
215 #    # as a first attempt however we keep a flat model for now
216 #    # can use one string instead of a list or tuple if needed, 
217 #    # see requirements.py for details
218 #    def requirements (self): 
219 #        return { 'js_files' : [],       # a list of relative paths for js input files
220 #                 'css_files': [],       # ditto for css, could have been a dict keyed on
221 #                                        # media instead
222 #                 'js_chunk' : [],       # (lines of) verbatim javascript code 
223 #                 'css_chunk': [],       # likewise for css scripts
224 #                 }
225     
226 #    # for better performance
227 #    # you can specify a list of keys that won't be exposed as json attributes
228 #    def exclude_from_json (self): return []
229
230     # mandatory : define the fields that need to be exposed to json as part of 
231     # plugin initialization
232     # mention 'domid' if you need plugin_uuid
233     # also 'query_uuid' gets replaced with query.uuid
234     def json_settings_list (self): return ['json_settings_list-must-be-redefined']
235
236     # might also define this one; see e.g. slicelist.py that piggybacks simplelist js code
237     # def plugin_classname (self):