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 engine.pluginset import PluginSet
10 from engine.prelude import Prelude
15 # . [ 'SliceList', 'TabbedView' ] : to debug these classes
16 # . True : to debug all plugin
19 #DEBUG= [ 'SliceList' ]
21 # decorator to deflect calls on Plugin to its PluginSet
22 def to_prelude (method):
23 def actual (self, *args, **kwds):
24 prelude_method=Prelude.__dict__[method.__name__]
25 return prelude_method(self.pluginset.prelude,*args, **kwds)
30 # using a simple incremental scheme to generate domids for now
31 # we just need this to be unique in a page
37 return "plugin-%d"%Plugin.domid
42 # . pluginset: the context of the request being served
43 # . title: is used visually for displaying the widget
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)
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
54 # any other setting can also be set when creating the object, like
56 # which will result in 'foo' being accessible to the template engine
58 def __init__ (self, pluginset, title, domid=None,
59 visible=True, togglable=True, toggled=True, **settings):
60 self.pluginset = pluginset
62 if not domid: domid=Plugin.newdomid()
64 self.classname=self._py_classname()
65 self.plugin_classname=self._js_classname()
67 self.togglable=togglable
69 # what comes from subclasses
70 for (k,v) in settings.iteritems():
72 if self.need_debug(): print "%s init - subclass setting %s"%(self.classname,k)
75 print "%s init dbg .... BEG"%self.classname
76 for (k,v) in self.__dict__.items(): print "dbg %s:%s"%(k,v)
77 print "%s init dbg .... END"%self.classname
78 # do this only once the structure is fine
79 self.pluginset.record_plugin(self)
81 def _py_classname (self):
82 try: return self.__class__.__name__
83 except: return 'Plugin'
85 def _js_classname (self):
86 try: return self.plugin_classname ()
87 except: return self._py_classname()
90 def need_debug (self):
91 if not DEBUG: return False
92 if DEBUG is True: return True
93 else: return self.classname in DEBUG
95 def setting_json (self, setting):
96 # TMP: js world expects plugin_uuid
97 if setting=='plugin_uuid':
99 elif setting=='query_uuid':
100 try: value=self.query.uuid
101 except: return '%s:"undefined"'%setting
103 value=getattr(self,setting,None)
104 if not value: value = "unknown-setting-%s"%setting
105 # first try to use to_json method (json.dumps not working on class instances)
106 try: value_json=value.to_json()
107 except: value_json=json.dumps(value,separators=(',',':'))
108 return "%s:%s"%(setting,value_json)
110 # expose in json format to js the list of fields as described in json_settings_list()
111 # and add plugin_uuid: domid in the mix
112 # NOTE this plugin_uuid thing might occur in js files from joomla/js, ** do not rename **
113 def settings_json (self):
115 result += ",".join([ self.setting_json(setting) for setting in self.json_settings_list() ])
119 # as a first approximation, only plugins that are associated with a query
120 # need to be prepared for js - others just get displayed and that's it
121 def is_asynchroneous (self):
122 return 'query' in self.__dict__
124 # returns the html code for that plugin
125 # in essence, wraps the results of self.render_content ()
126 def render (self, request):
127 # call render_content
128 plugin_content = self.render_content (request)
129 # shove this into plugin.html
131 env ['plugin_content']= plugin_content
132 env.update(self.__dict__)
133 result = render_to_string ('plugin.html',env)
135 # export this only for relevant plugins
136 if self.is_asynchroneous():
137 env ['settings_json' ] = self.settings_json()
138 # compute plugin-specific initialization
139 js_init = render_to_string ( 'plugin-setenv.js', env )
140 self.add_js_chunks (js_init)
142 # interpret the result of requirements ()
143 self.handle_requirements (request)
147 # you may redefine this completely, but if you don't we'll just use methods
148 # . template_file() to find out which template to use, and
149 # . template_env() to compute a dictionary to pass along to the templating system
150 def render_content (self, request):
151 """Should return an HTML fragment"""
152 template = self.template_file()
153 env=self.template_env(request)
154 if not isinstance (env,dict):
155 raise Exception, "%s.template_env returns wrong type"%self.classname
156 result=render_to_string (template, env)
157 if self.need_debug():
158 print "%s.render_content: BEG --------------------"%self.classname
159 print "template=%s"%template
160 print "env.keys=%s"%env.keys()
163 print "%s.render_content: END --------------------"%self.classname
166 # or from the result of self.requirements()
167 def handle_requirements (self, request):
169 d=self.requirements()
170 for (k,v) in d.iteritems():
171 if self.need_debug():
172 print "%s: handling requirement %s"%(self.classname,v)
174 method=PluginSet.__dict__[method_name]
175 method(self.pluginset,v)
176 except AttributeError:
177 # most likely the object does not have that method defined, which is fine
181 traceback.print_exc()
184 #################### requirements/prelude management
185 # just forward to self.pluginset - see decorator above
187 def add_js_files (self):pass
189 def add_css_files (self):pass
191 def add_js_chunks (self):pass
193 def add_css_chunks (self):pass
195 ######################################## abstract interface
196 # your plugin is expected to implement either
197 # (*) def render_content(self, request) -> html fragment
199 # (*) def template_file (self) -> filename
201 # (*) def template_env (self, request) -> dict
202 # this is the variable->value association used to render the template
203 # in which case the html template will be used
205 # if you see this string somewhere your template_file() code is not kicking in
206 def template_file (self): return "undefined_template"
207 def template_env (self, request): return {}
209 # # tell the framework about requirements (for the document <header>)
210 # # the notion of 'Media' in django provides for medium-dependant
211 # # selection of css files
212 # # as a first attempt however we keep a flat model for now
213 # # can use one string instead of a list or tuple if needed,
214 # # see requirements.py for details
215 # def requirements (self):
216 # return { 'js_files' : [], # a list of relative paths for js input files
217 # 'css_files': [], # ditto for css, could have been a dict keyed on
219 # 'js_chunk' : [], # (lines of) verbatim javascript code
220 # 'css_chunk': [], # likewise for css scripts
223 # # for better performance
224 # # you can specify a list of keys that won't be exposed as json attributes
225 # def exclude_from_json (self): return []
227 # mandatory : define the fields that need to be exposed to json as part of
228 # plugin initialization
229 # mention 'domid' if you need plugin_uuid
230 # also 'query_uuid' gets replaced with query.uuid
231 def json_settings_list (self): return ['json_settings_list-must-be-redefined']
233 # might also define this one; see e.g. slicelist.py that piggybacks simplelist js code
234 # def plugin_classname (self):