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 # . 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 #### xxx NOTE : pending move towards a more elaborate mode for 'toggled'
51 # . toggled: if togglable, what's the initial status; possible values are
52 # .. True : start up open/hidden
53 # .. False : start up closed/shown
54 # .. 'last' : start up as it was the last time that browser showed it (based on 'domid')
55 # .. None : if not passed to __init__ at all, then the DefaultTaggled() method is called
56 # .. : anything else, defaults to True
57 #### xxx NOTE : pending move towards a more elaborate mode for 'toggled'
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
64 # any other setting can also be set when creating the object, like
66 # which will result in 'foo' being accessible to the template engine
68 def __init__ (self, page, title, domid=None,
69 visible=True, togglable=True, toggled=True, **settings):
72 # callers can provide their domid for css'ing
73 if not domid: domid=Plugin.newdomid()
75 self.classname=self._py_classname()
76 self.plugin_classname=self._js_classname()
78 self.togglable=togglable
80 # what comes from subclasses
81 for (k,v) in settings.iteritems():
83 if self.need_debug(): print "%s init - subclass setting %s"%(self.classname,k)
86 print "%s init dbg .... BEG"%self.classname
87 for (k,v) in self.__dict__.items(): print "dbg %s:%s"%(k,v)
88 print "%s init dbg .... END"%self.classname
89 # do this only once the structure is fine
90 self.page.record_plugin(self)
93 return "[%s]:%s"%(self.classname,self.domid)
95 def _py_classname (self):
96 try: return self.__class__.__name__
97 except: return 'Plugin'
99 def _js_classname (self):
100 try: return self.plugin_classname ()
101 except: return self._py_classname()
104 def need_debug (self):
105 if not DEBUG: return False
106 if DEBUG is True: return True
107 else: return self.classname in DEBUG
109 def setting_json (self, setting):
110 # TMP: js world expects plugin_uuid
111 if setting=='plugin_uuid':
113 elif setting=='query_uuid':
114 try: value=self.query.query_uuid
115 except: return '%s:"undefined"'%setting
117 value=getattr(self,setting,None)
118 if value is None: value = "unknown-setting-%s"%setting
119 # first try to use to_json method (json.dumps not working on class instances)
120 try: value_json=value.to_json()
121 except: value_json=json.dumps(value,separators=(',',':'))
122 return "%s:%s"%(setting,value_json)
124 # expose in json format to js the list of fields as described in json_settings_list()
125 # and add plugin_uuid: domid in the mix
126 # NOTE this plugin_uuid thing might occur in js files from joomla/js, ** do not rename **
127 def settings_json (self):
128 exposed_settings=self.json_settings_list()
129 if 'query' in exposed_settings:
130 print "WARNING, cannot expose 'query' directly in json_settings_list, query_uuid is enough"
132 result += ",".join([ self.setting_json(setting) for setting in self.json_settings_list() ])
136 # as a first approximation, only plugins that are associated with a query
137 # need to be prepared for js - meaning their json settings get exposed to js
138 # others just get displayed and that's it
139 def export_json_settings (self):
140 return 'query_uuid' in self.json_settings_list()
142 # by default we create a timer if there's a query attached, redefine to change this behaviour
143 def start_with_spin (self):
144 return self.export_json_settings()
146 # returns the html code for that plugin
147 # in essence, wraps the results of self.render_content ()
148 def render (self, request):
149 # call render_content
150 plugin_content = self.render_content (request)
151 # shove this into plugin.html
153 env ['plugin_content']= plugin_content
154 # need_spin is used in plugin.html
155 self.need_spin=self.start_with_spin()
156 env.update(self.__dict__)
157 if self.need_debug():
158 print "rendering plugin.html with env keys %s"%env.keys()
159 result = render_to_string ('plugin.html',env)
161 # export this only for relevant plugins
162 if self.export_json_settings():
163 env ['settings_json' ] = self.settings_json()
164 # compute plugin-specific initialization
165 js_init = render_to_string ( 'plugin-init.js', env )
166 self.add_js_chunks (js_init)
168 # interpret the result of requirements ()
169 self.handle_requirements (request)
173 # you may redefine this completely, but if you don't we'll just use methods
174 # . template_file() to find out which template to use, and
175 # . template_env() to compute a dictionary to pass along to the templating system
176 def render_content (self, request):
177 """Should return an HTML fragment"""
178 template = self.template_file()
179 # start with a fresh one
181 # add our own settings as defaults
182 env.update(self.__dict__)
183 # then the things explicitly defined in template_env()
184 env.update(self.template_env(request))
185 if not isinstance (env,dict):
186 raise Exception, "%s.template_env returns wrong type"%self.classname
187 result=render_to_string (template, env)
188 if self.need_debug():
189 print "%s.render_content: BEG --------------------"%self.classname
190 print "template=%s"%template
191 print "env.keys=%s"%env.keys()
194 print "%s.render_content: END --------------------"%self.classname
197 # or from the result of self.requirements()
198 def handle_requirements (self, request):
200 d=self.requirements()
201 for (k,v) in d.iteritems():
202 if self.need_debug():
203 print "%s: handling requirement %s"%(self.classname,v)
204 # e.g. js_files -> add_js_files
206 method=Page.__dict__[method_name]
208 except AttributeError:
209 # most likely the object does not have that method defined, which is fine
213 traceback.print_exc()
216 #################### requirements/prelude management
217 # just forward to our prelude instance - see decorator above
219 def add_js_files (self):pass
221 def add_css_files (self):pass
223 def add_js_chunks (self):pass
225 def add_css_chunks (self):pass
227 ######################################## abstract interface
228 # your plugin is expected to implement either
229 # (*) def render_content(self, request) -> html fragment
231 # (*) def template_file (self) -> filename
233 # (*) def template_env (self, request) -> dict
234 # this is the variable->value association used to render the template
235 # in which case the html template will be used
237 # if you see this string somewhere your template_file() code is not kicking in
238 def template_file (self): return "undefined_template"
239 def template_env (self, request): return {}
241 # # tell the framework about requirements (for the document <header>)
242 # # the notion of 'Media' in django provides for medium-dependant
243 # # selection of css files
244 # # as a first attempt however we keep a flat model for now
245 # # can use one string instead of a list or tuple if needed,
246 # # see requirements.py for details
247 # def requirements (self):
248 # return { 'js_files' : [], # a list of relative paths for js input files
249 # 'css_files': [], # ditto for css, could have been a dict keyed on
251 # 'js_chunk' : [], # (lines of) verbatim javascript code
252 # 'css_chunk': [], # likewise for css scripts
255 # # for better performance
256 # # you can specify a list of keys that won't be exposed as json attributes
257 # def exclude_from_json (self): return []
259 # mandatory : define the fields that need to be exposed to json as part of
260 # plugin initialization
261 # mention 'domid' if you need plugin_uuid
262 # also 'query_uuid' gets replaced with query.query_uuid
263 def json_settings_list (self): return ['json_settings_list-must-be-redefined']
265 # might also define these ones:
267 # see e.g. slicelist.py that piggybacks simplelist js code
268 # def plugin_classname (self)
270 # whether we export the json settings to js
271 # def export_json_settings (self)
273 # whether we show an initial spinner
274 # def start_with_spin (self)