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.prelude import Prelude
14 # . [ 'SliceList', 'TabbedView' ] : to debug these classes
15 # . True : to debug all plugin
17 DEBUG= [ 'SliceList' ]
21 # using a simple incremental scheme to generate uuids for now
24 # xxx should generate some random id
33 # . title: is used visually for displaying the widget
34 # . name: a simple id suitable for forging css names
36 # . hidable: whether it can be turned on and off from the UI
37 # like e.g. PleKitToggle
38 # . hidden_by_default: if hidable, what's the initial status
39 # . visible: if not set the plugin does not show up at all,
40 # not quite sure what this was for
42 # . uuid: created internally
43 # . rank: this is for plugins sons of a composite plugin
45 # any other setting can also be set when creating the object, like
47 # which will result in 'foo' being accessible to the template engine
49 def __init__ (self, title, name,
50 visible=True, hidable=True, hidden_by_default=False, **settings):
51 # what is in this dictionary will get exposed to template and to javascript
52 self._settings=settings
55 self.add_to_settings ( ['title','name'] )
56 self.uuid=Plugin.newuuid()
57 self.classname=self._classname()
58 self.add_to_settings ( [ 'uuid', 'classname' ] )
61 self.hidden_by_default=hidden_by_default
62 self.add_to_settings( ['visible','hidable','hidden_by_default'] )
63 # we store as a dictionary the arguments passed to constructor
64 # e.g. SimpleList (list=[1,2,3]) => _settings = { 'list':[1,2,3] }
65 # our own settings are not made part of _settings but could be..
67 print "Plugin.__init__ Created plugin with settings %s"%self._settings.keys()
69 # subclasses might handle some fields in their own way,
70 # in which case this call is needed to capture that setting
71 # see e.g. SimpleList or SliceList for an example of that
72 def add_to_settings (self, setting_name_s):
73 if not isinstance (setting_name_s, list):
74 self._settings[setting_name_s]=getattr(self,setting_name_s)
76 for setting_name in setting_name_s:
77 self._settings[setting_name]=getattr(self,setting_name)
79 def _classname (self):
80 try: return self.__class__.__name__
81 except: return 'Plugin'
83 # shorthands to inspect _settings
84 def get_setting (self, setting, default=None):
85 if setting not in self._settings: return default
86 else: return self._settings[setting]
88 def is_visible (self): return self.visible
89 def is_hidable (self): return self.hidable
90 def is_hidden_by_default (self): return self.hidden_by_default
93 def need_debug (self):
94 if not DEBUG: return False
95 if DEBUG is True: return True
96 else: return self.classname in DEBUG
98 # returns the html code for that plugin
99 # in essence, wraps the results of self.render_content ()
100 def render (self, request):
102 # initialize prelude placeholder
103 self._init_request (request)
105 # call render_content
106 plugin_content = self.render_content (request)
107 # expose _settings in json format to js
108 settings_json = json.dumps (self._settings, separators=(',',':'))
110 env= {'plugin_content' : plugin_content,
111 'settings_json' : settings_json,
113 env.update(self._settings)
114 result = render_to_string ('plugin.html',env)
116 # handle requirements() if defined on this class
118 self.handle_requirements (request, self.requirements())
119 except AttributeError:
120 # most likely the object does not have that method defined, which is fine
124 traceback.print_exc()
129 # you may redefine this completely, but if you don't we'll just use methods
130 # . template_file() to find out which template to use, and
131 # . template_env() to compute a dictionary to pass along to the templating system
132 def render_content (self, request):
133 """Should return an HTML fragment"""
134 template = self.template_file()
135 env=self.template_env(request)
136 if not isinstance (env,dict):
137 raise Exception, "%s.template_env returns wrong type"%self.classname
138 # expose this class's settings to the template
139 # xxx we might need to check that this does not overwrite env..
140 env.update(self._settings)
141 result=render_to_string (template, env)
142 if self.need_debug():
143 print "%s.render_content: BEG --------------------"%self.classname
144 print "template=%s"%template
145 print "env.keys=%s"%env.keys()
148 print "%s.render_content: END --------------------"%self.classname
151 #################### requirements/prelude management
152 def _init_request (self, request):
153 if not hasattr (request, 'plugin_prelude'):
154 # include css/plugins.css
155 request.plugin_prelude=Prelude(css_files='css/plugin.css')
157 def inspect_request (self, request, message):
158 has=hasattr(request,'plugin_prelude')
159 get=getattr(request,'plugin_prelude','none-defined')
160 print "INSPECT (%s), hasattr %s, getattr %s"%(message,has,get)
162 # can be used directly in render_content()
163 def add_js_files (self, request, files):
164 self._init_request (request)
165 request.plugin_prelude.add_js_files (files)
166 def add_css_files (self, request, files):
167 self._init_request (request)
168 request.plugin_prelude.add_css_files (files)
169 def add_js_chunks (self, request, chunks):
170 self._init_request (request)
171 request.plugin_prelude.add_js_chunks (chunks)
172 def add_css_chunks (self, request, chunks):
173 self._init_request (request)
174 request.plugin_prelude.add_css_chunks (chunks)
176 # or from the result of self.requirements()
177 def handle_requirements (self, request, d):
178 for (k,v) in d.iteritems():
179 if self.need_debug():
180 print "%s: handling requirement %s"%(self.classname,v)
182 method=Plugin.__dict__[method_name]
183 method(self,request,v)
185 ######################################## abstract interface
186 # your plugin is expected to implement either
187 # (*) def render_content(self, request) -> html fragment
189 # (*) def template_file (self) -> filename
191 # (*) def template_env (self, request) -> dict
192 # this is the variable->value association used to render the template
193 # in which case the html template will be used
195 # if you see this string somewhere your template_file() code is not kicking in
196 def template_file (self): return "undefined_template"
197 def template_env (self, request): return {}
199 # # tell the framework about requirements (for the document <header>)
200 # # the notion of 'Media' in django provides for medium-dependant
201 # # selection of css files
202 # # as a first attempt however we keep a flat model for now
203 # # can use one string instead of a list or tuple if needed,
204 # # see requirements.py for details
205 # def requirements (self):
206 # return { 'js_files' : [], # a list of relative paths for js input files
207 # 'css_files': [], # ditto for css, could have been a dict keyed on
209 # 'js_chunk' : [], # (lines of) verbatim javascript code
210 # 'css_chunk': [], # likewise for css scripts