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)
83 def _py_classname (self):
84 try: return self.__class__.__name__
85 except: return 'Plugin'
87 def _js_classname (self):
88 try: return self.plugin_classname ()
89 except: return self._py_classname()
92 def need_debug (self):
93 if not DEBUG: return False
94 if DEBUG is True: return True
95 else: return self.classname in DEBUG
97 def setting_json (self, setting):
98 # TMP: js world expects plugin_uuid
99 if setting=='plugin_uuid':
101 elif setting=='query_uuid':
102 try: value=self.query.query_uuid
103 except: return '%s:"undefined"'%setting
105 value=getattr(self,setting,None)
106 if not value: value = "unknown-setting-%s"%setting
107 # first try to use to_json method (json.dumps not working on class instances)
108 try: value_json=value.to_json()
109 except: value_json=json.dumps(value,separators=(',',':'))
110 return "%s:%s"%(setting,value_json)
112 # expose in json format to js the list of fields as described in json_settings_list()
113 # and add plugin_uuid: domid in the mix
114 # NOTE this plugin_uuid thing might occur in js files from joomla/js, ** do not rename **
115 def settings_json (self):
116 exposed_settings=self.json_settings_list()
117 if 'query' in exposed_settings:
118 print "WARNING, cannot expose 'query' directly in json_settings_list, query_uuid is enough"
120 result += ",".join([ self.setting_json(setting) for setting in self.json_settings_list() ])
124 # as a first approximation, only plugins that are associated with a query
125 # need to be prepared for js - meaning their json settings get exposed to js
126 # others just get displayed and that's it
127 def export_json_settings (self):
128 return 'query_uuid' in self.json_settings_list()
130 # by default we create a timer if there's a query attached, redefine to change this behaviour
131 def start_with_spin (self):
132 return self.export_json_settings()
134 # returns the html code for that plugin
135 # in essence, wraps the results of self.render_content ()
136 def render (self, request):
137 # call render_content
138 plugin_content = self.render_content (request)
139 # shove this into plugin.html
141 env ['plugin_content']= plugin_content
142 # need_spin is used in plugin.html
143 self.need_spin=self.start_with_spin()
144 env.update(self.__dict__)
145 if self.need_debug():
146 print "rendering plugin.html with env keys %s"%env.keys()
147 result = render_to_string ('plugin.html',env)
149 # export this only for relevant plugins
150 if self.export_json_settings():
151 env ['settings_json' ] = self.settings_json()
152 # compute plugin-specific initialization
153 js_init = render_to_string ( 'plugin-init.js', env )
154 self.add_js_chunks (js_init)
156 # interpret the result of requirements ()
157 self.handle_requirements (request)
161 # you may redefine this completely, but if you don't we'll just use methods
162 # . template_file() to find out which template to use, and
163 # . template_env() to compute a dictionary to pass along to the templating system
164 def render_content (self, request):
165 """Should return an HTML fragment"""
166 template = self.template_file()
167 env=self.template_env(request)
168 if not isinstance (env,dict):
169 raise Exception, "%s.template_env returns wrong type"%self.classname
170 result=render_to_string (template, env)
171 if self.need_debug():
172 print "%s.render_content: BEG --------------------"%self.classname
173 print "template=%s"%template
174 print "env.keys=%s"%env.keys()
177 print "%s.render_content: END --------------------"%self.classname
180 # or from the result of self.requirements()
181 def handle_requirements (self, request):
183 d=self.requirements()
184 for (k,v) in d.iteritems():
185 if self.need_debug():
186 print "%s: handling requirement %s"%(self.classname,v)
187 # e.g. js_files -> add_js_files
189 method=Page.__dict__[method_name]
191 except AttributeError:
192 # most likely the object does not have that method defined, which is fine
196 traceback.print_exc()
199 #################### requirements/prelude management
200 # just forward to our prelude instance - see decorator above
202 def add_js_files (self):pass
204 def add_css_files (self):pass
206 def add_js_chunks (self):pass
208 def add_css_chunks (self):pass
210 ######################################## abstract interface
211 # your plugin is expected to implement either
212 # (*) def render_content(self, request) -> html fragment
214 # (*) def template_file (self) -> filename
216 # (*) def template_env (self, request) -> dict
217 # this is the variable->value association used to render the template
218 # in which case the html template will be used
220 # if you see this string somewhere your template_file() code is not kicking in
221 def template_file (self): return "undefined_template"
222 def template_env (self, request): return {}
224 # # tell the framework about requirements (for the document <header>)
225 # # the notion of 'Media' in django provides for medium-dependant
226 # # selection of css files
227 # # as a first attempt however we keep a flat model for now
228 # # can use one string instead of a list or tuple if needed,
229 # # see requirements.py for details
230 # def requirements (self):
231 # return { 'js_files' : [], # a list of relative paths for js input files
232 # 'css_files': [], # ditto for css, could have been a dict keyed on
234 # 'js_chunk' : [], # (lines of) verbatim javascript code
235 # 'css_chunk': [], # likewise for css scripts
238 # # for better performance
239 # # you can specify a list of keys that won't be exposed as json attributes
240 # def exclude_from_json (self): return []
242 # mandatory : define the fields that need to be exposed to json as part of
243 # plugin initialization
244 # mention 'domid' if you need plugin_uuid
245 # also 'query_uuid' gets replaced with query.query_uuid
246 def json_settings_list (self): return ['json_settings_list-must-be-redefined']
248 # might also define these ones:
250 # see e.g. slicelist.py that piggybacks simplelist js code
251 # def plugin_classname (self)
253 # whether we export the json settings to js
254 # def export_json_settings (self)
256 # whether we show an initial spinner
257 # def start_with_spin (self)