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
7 from django.template.loader import render_to_string
9 from unfold.page import Page
10 from unfold.prelude import Prelude
15 # . [ 'SliceList', 'TabbedView' ] : to debug these classes
16 # . True : to debug all plugin
19 #DEBUG= [ 'SimpleList' ]
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)
31 # using a simple incremental scheme to generate domids for now
32 # we just need this to be unique in a page
38 return "plugin-%d"%Plugin.domid
43 # . page: the context of the request being served
44 # . title: is used visually for displaying the widget
46 # . togglable: whether it can be turned on and off (like PleKitToggle)
47 # . toggled: if togglable, what's the initial status
48 # . visible: if not set the plugin does not show up at all
49 # (not quite sure what this was for)
51 # . domid: created internally, but can be set at creation time if needed
52 # useful for hand-made css, or for selecting an active plugin in a composite
53 # . rank: this is for plugins sons of a composite plugin
55 # any other setting can also be set when creating the object, like
57 # which will result in 'foo' being accessible to the template engine
59 def __init__ (self, page, title, domid=None,
60 visible=True, togglable=True, toggled=True, **settings):
63 # callers can provide their domid for css'ing
64 if not domid: domid=Plugin.newdomid()
66 self.classname=self._py_classname()
67 self.plugin_classname=self._js_classname()
69 self.togglable=togglable
71 # what comes from subclasses
72 for (k,v) in settings.iteritems():
74 if self.need_debug(): print "%s init - subclass setting %s"%(self.classname,k)
77 print "%s init dbg .... BEG"%self.classname
78 for (k,v) in self.__dict__.items(): print "dbg %s:%s"%(k,v)
79 print "%s init dbg .... END"%self.classname
80 # do this only once the structure is fine
81 self.page.record_plugin(self)
84 return "[%s]:%s"%(self.classname,self.domid)
86 def _py_classname (self):
87 try: return self.__class__.__name__
88 except: return 'Plugin'
90 def _js_classname (self):
91 try: return self.plugin_classname ()
92 except: return self._py_classname()
95 def need_debug (self):
96 if not DEBUG: return False
97 if DEBUG is True: return True
98 else: return self.classname in DEBUG
100 def setting_json (self, setting):
101 # TMP: js world expects plugin_uuid
102 if setting=='plugin_uuid':
104 elif setting=='query_uuid':
105 try: value=self.query.query_uuid
106 except: return '%s:"undefined"'%setting
108 value=getattr(self,setting,None)
109 if not value: value = "unknown-setting-%s"%setting
110 # first try to use to_json method (json.dumps not working on class instances)
111 try: value_json=value.to_json()
112 except: value_json=json.dumps(value,separators=(',',':'))
113 return "%s:%s"%(setting,value_json)
115 # expose in json format to js the list of fields as described in json_settings_list()
116 # and add plugin_uuid: domid in the mix
117 # NOTE this plugin_uuid thing might occur in js files from joomla/js, ** do not rename **
118 def settings_json (self):
119 exposed_settings=self.json_settings_list()
120 if 'query' in exposed_settings:
121 print "WARNING, cannot expose 'query' directly in json_settings_list, query_uuid is enough"
123 result += ",".join([ self.setting_json(setting) for setting in self.json_settings_list() ])
127 # as a first approximation, only plugins that are associated with a query
128 # need to be prepared for js - meaning their json settings get exposed to js
129 # others just get displayed and that's it
130 def export_json_settings (self):
131 return 'query_uuid' in self.json_settings_list()
133 # by default we create a timer if there's a query attached, redefine to change this behaviour
134 def start_with_spin (self):
135 return self.export_json_settings()
137 # returns the html code for that plugin
138 # in essence, wraps the results of self.render_content ()
139 def render (self, request):
140 # call render_content
141 plugin_content = self.render_content (request)
142 # shove this into plugin.html
144 env ['plugin_content']= plugin_content
145 # need_spin is used in plugin.html
146 self.need_spin=self.start_with_spin()
147 env.update(self.__dict__)
148 if self.need_debug():
149 print "rendering plugin.html with env keys %s"%env.keys()
150 result = render_to_string ('plugin.html',env)
152 # export this only for relevant plugins
153 if self.export_json_settings():
154 env ['settings_json' ] = self.settings_json()
155 # compute plugin-specific initialization
156 js_init = render_to_string ( 'plugin-init.js', env )
157 self.add_js_chunks (js_init)
159 # interpret the result of requirements ()
160 self.handle_requirements (request)
164 # you may redefine this completely, but if you don't we'll just use methods
165 # . template_file() to find out which template to use, and
166 # . template_env() to compute a dictionary to pass along to the templating system
167 def render_content (self, request):
168 """Should return an HTML fragment"""
169 template = self.template_file()
170 # start with a fresh one
172 # add our own settings as defaults
173 env.update(self.__dict__)
174 # then the things explicitly defined in template_env()
175 env.update(self.template_env(request))
176 if not isinstance (env,dict):
177 raise Exception, "%s.template_env returns wrong type"%self.classname
178 result=render_to_string (template, env)
179 if self.need_debug():
180 print "%s.render_content: BEG --------------------"%self.classname
181 print "template=%s"%template
182 print "env.keys=%s"%env.keys()
185 print "%s.render_content: END --------------------"%self.classname
188 # or from the result of self.requirements()
189 def handle_requirements (self, request):
191 d=self.requirements()
192 for (k,v) in d.iteritems():
193 if self.need_debug():
194 print "%s: handling requirement %s"%(self.classname,v)
195 # e.g. js_files -> add_js_files
197 method=Page.__dict__[method_name]
199 except AttributeError:
200 # most likely the object does not have that method defined, which is fine
204 traceback.print_exc()
207 #################### requirements/prelude management
208 # just forward to our prelude instance - see decorator above
210 def add_js_files (self):pass
212 def add_css_files (self):pass
214 def add_js_chunks (self):pass
216 def add_css_chunks (self):pass
218 ######################################## abstract interface
219 # your plugin is expected to implement either
220 # (*) def render_content(self, request) -> html fragment
222 # (*) def template_file (self) -> filename
224 # (*) def template_env (self, request) -> dict
225 # this is the variable->value association used to render the template
226 # in which case the html template will be used
228 # if you see this string somewhere your template_file() code is not kicking in
229 def template_file (self): return "undefined_template"
230 def template_env (self, request): return {}
232 # # tell the framework about requirements (for the document <header>)
233 # # the notion of 'Media' in django provides for medium-dependant
234 # # selection of css files
235 # # as a first attempt however we keep a flat model for now
236 # # can use one string instead of a list or tuple if needed,
237 # # see requirements.py for details
238 # def requirements (self):
239 # return { 'js_files' : [], # a list of relative paths for js input files
240 # 'css_files': [], # ditto for css, could have been a dict keyed on
242 # 'js_chunk' : [], # (lines of) verbatim javascript code
243 # 'css_chunk': [], # likewise for css scripts
246 # # for better performance
247 # # you can specify a list of keys that won't be exposed as json attributes
248 # def exclude_from_json (self): return []
250 # mandatory : define the fields that need to be exposed to json as part of
251 # plugin initialization
252 # mention 'domid' if you need plugin_uuid
253 # also 'query_uuid' gets replaced with query.query_uuid
254 def json_settings_list (self): return ['json_settings_list-must-be-redefined']
256 # might also define these ones:
258 # see e.g. slicelist.py that piggybacks simplelist js code
259 # def plugin_classname (self)
261 # whether we export the json settings to js
262 # def export_json_settings (self)
264 # whether we show an initial spinner
265 # def start_with_spin (self)