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
21 # using a simple incremental scheme to generate domids for now
22 # we just need this to be unique in a page
28 return "plugin-%d"%Plugin.domid
33 # . title: is used visually for displaying the widget
35 # . togglable: whether it can be turned on and off (like PleKitToggle)
36 # . toggled: if togglable, what's the initial status
37 # . visible: if not set the plugin does not show up at all
38 # (not quite sure what this was for)
40 # . domid: created internally, but can be set at creation time if needed
41 # useful for hand-made css, or for selecting an active plugin in a composite
42 # . rank: this is for plugins sons of a composite plugin
44 # any other setting can also be set when creating the object, like
46 # which will result in 'foo' being accessible to the template engine
48 def __init__ (self, title, domid=None,
49 visible=True, togglable=True, toggled=True, **settings):
50 # what is in this dictionary will get exposed to template and to javascript
51 self._settings=settings
53 if not domid: domid=Plugin.newdomid()
55 self.classname=self._classname()
56 self.add_to_settings ( ['title', 'domid', 'classname'] )
58 self.togglable=togglable
60 self.add_to_settings( ['visible','togglable','toggled'] )
61 # we store as a dictionary the arguments passed to constructor
62 # e.g. SimpleList (list=[1,2,3]) => _settings = { 'list':[1,2,3] }
63 # our own settings are not made part of _settings but could be..
65 print "Plugin.__init__ Created plugin with settings %s"%self._settings.keys()
67 # subclasses might handle some fields in their own way,
68 # in which case this call is needed to capture that setting
69 # see e.g. SimpleList or SliceList for an example of that
70 def add_to_settings (self, setting_name_s):
71 if not isinstance (setting_name_s, list):
72 self._settings[setting_name_s]=getattr(self,setting_name_s)
74 for setting_name in setting_name_s:
75 self._settings[setting_name]=getattr(self,setting_name)
77 def _classname (self):
78 try: return self.__class__.__name__
79 except: return 'Plugin'
81 # shorthands to inspect _settings
82 def get_setting (self, setting, default=None):
83 if setting not in self._settings: return default
84 else: return self._settings[setting]
87 def need_debug (self):
88 if not DEBUG: return False
89 if DEBUG is True: return True
90 else: return self.classname in DEBUG
92 # returns the html code for that plugin
93 # in essence, wraps the results of self.render_content ()
94 def render (self, request):
95 # initialize prelude placeholder if needed
96 self._init_prelude (request)
98 plugin_content = self.render_content (request)
99 # shove this into plugin.html
101 env ['plugin_content']= plugin_content
102 env.update(self._settings)
103 result = render_to_string ('plugin.html',env)
105 # expose _settings in json format to js, and add plugin_uuid: domid in the mix
106 # NOTE this plugin_uuid thing might occur in js files, ** do not rename **
107 js_env = { 'plugin_uuid' : self.domid }
108 js_env.update (self._settings)
109 settings_json = json.dumps (js_env, separators=(',',':'))
110 env ['settings_json' ] = settings_json
111 # compute plugin-specific initialization
112 js_init = render_to_string ( 'plugin_setenv.js', env )
113 print 'js_init',js_init
114 self.add_js_chunks (request, js_init)
116 # interpret the result of requirements ()
117 self.handle_requirements (request)
121 # you may redefine this completely, but if you don't we'll just use methods
122 # . template_file() to find out which template to use, and
123 # . template_env() to compute a dictionary to pass along to the templating system
124 def render_content (self, request):
125 """Should return an HTML fragment"""
126 template = self.template_file()
127 env=self.template_env(request)
128 if not isinstance (env,dict):
129 raise Exception, "%s.template_env returns wrong type"%self.classname
130 # expose this class's settings to the template
131 # xxx we might need to check that this does not overwrite env..
132 env.update(self._settings)
133 result=render_to_string (template, env)
134 if self.need_debug():
135 print "%s.render_content: BEG --------------------"%self.classname
136 print "template=%s"%template
137 print "env.keys=%s"%env.keys()
140 print "%s.render_content: END --------------------"%self.classname
143 #################### requirements/prelude management
144 def _init_prelude (self, request):
145 if not hasattr (request, 'plugin_prelude'):
146 # include css/plugins.css
147 request.plugin_prelude=Prelude(css_files='css/plugin.css')
149 def inspect_request (self, request, message):
150 has=hasattr(request,'plugin_prelude')
151 get=getattr(request,'plugin_prelude','none-defined')
152 print "INSPECT (%s), hasattr %s, getattr %s"%(message,has,get)
154 # can be used directly in render_content()
155 def add_js_files (self, request, files):
156 self._init_prelude (request)
157 request.plugin_prelude.add_js_files (files)
158 def add_css_files (self, request, files):
159 self._init_prelude (request)
160 request.plugin_prelude.add_css_files (files)
161 def add_js_chunks (self, request, chunks):
162 self._init_prelude (request)
163 request.plugin_prelude.add_js_chunks (chunks)
164 def add_css_chunks (self, request, chunks):
165 self._init_prelude (request)
166 request.plugin_prelude.add_css_chunks (chunks)
168 # or from the result of self.requirements()
169 def handle_requirements (self, request):
171 d=self.requirements()
172 for (k,v) in d.iteritems():
173 if self.need_debug():
174 print "%s: handling requirement %s"%(self.classname,v)
176 method=Plugin.__dict__[method_name]
177 method(self,request,v)
178 except AttributeError:
179 # most likely the object does not have that method defined, which is fine
183 traceback.print_exc()
186 ######################################## abstract interface
187 # your plugin is expected to implement either
188 # (*) def render_content(self, request) -> html fragment
190 # (*) def template_file (self) -> filename
192 # (*) def template_env (self, request) -> dict
193 # this is the variable->value association used to render the template
194 # in which case the html template will be used
196 # if you see this string somewhere your template_file() code is not kicking in
197 def template_file (self): return "undefined_template"
198 def template_env (self, request): return {}
200 # # tell the framework about requirements (for the document <header>)
201 # # the notion of 'Media' in django provides for medium-dependant
202 # # selection of css files
203 # # as a first attempt however we keep a flat model for now
204 # # can use one string instead of a list or tuple if needed,
205 # # see requirements.py for details
206 # def requirements (self):
207 # return { 'js_files' : [], # a list of relative paths for js input files
208 # 'css_files': [], # ditto for css, could have been a dict keyed on
210 # 'js_chunk' : [], # (lines of) verbatim javascript code
211 # 'css_chunk': [], # likewise for css scripts