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
18 DEBUG= [ 'SimpleList' ]
22 # using a simple incremental scheme to generate domids for now
23 # we just need this to be unique in a page
29 return "plugin-%d"%Plugin.domid
34 # . title: is used visually for displaying the widget
36 # . togglable: whether it can be turned on and off (like PleKitToggle)
37 # . toggled: if togglable, what's the initial status
38 # . visible: if not set the plugin does not show up at all
39 # (not quite sure what this was for)
41 # . domid: created internally, but can be set at creation time if needed
42 # useful for hand-made css, or for selecting an active plugin in a composite
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, domid=None,
50 visible=True, togglable=True, toggled=True, **settings):
52 if not domid: domid=Plugin.newdomid()
54 self.classname=self._classname()
56 self.togglable=togglable
58 # what comes from subclasses
59 for (k,v) in settings.iteritems():
61 if self.need_debug(): print "%s init - subclass setting %s"%(self.classname,k)
64 print "%s init dbg .... BEG"%self.classname
65 for (k,v) in self.__dict__.items(): print "dbg %s:%s"%(k,v)
66 print "%s init dbg .... END"%self.classname
68 def _classname (self):
69 try: return self.__class__.__name__
70 except: return 'Plugin'
73 def need_debug (self):
74 if not DEBUG: return False
75 if DEBUG is True: return True
76 else: return self.classname in DEBUG
78 def setting_json (self, setting):
79 # TMP: js world expects plugin_uuid
80 if setting=='plugin_uuid':
82 elif setting=='query_uuid':
83 try: value=self.query.uuid
84 except: return '%s:"undefined"'%setting
86 value=getattr(self,setting,None)
87 if not value: value = "unknown-setting-%s"%setting
88 # first try to use to_json method (json.dumps not working on class instances)
89 try: value_json=value.to_json()
90 except: value_json=json.dumps(value,separators=(',',':'))
91 return "%s:%s"%(setting,value_json)
93 # expose in json format to js the list of fields as described in json_settings_list()
94 # and add plugin_uuid: domid in the mix
95 # NOTE this plugin_uuid thing might occur in js files from joomla/js, ** do not rename **
96 def settings_json (self):
98 result += ",".join([ self.setting_json(setting) for setting in self.json_settings_list() ])
102 # returns the html code for that plugin
103 # in essence, wraps the results of self.render_content ()
104 def render (self, request):
105 # initialize prelude placeholder if needed
106 self._init_prelude (request)
107 # call render_content
108 plugin_content = self.render_content (request)
109 # shove this into plugin.html
111 env ['plugin_content']= plugin_content
112 env.update(self.__dict__)
113 result = render_to_string ('plugin.html',env)
115 # as a first approximation we're only concerned with plugins that are associated with a query
116 # other simpler plugins that only deal with layout do not need this
117 if 'query' in self.__dict__:
118 env ['settings_json' ] = self.settings_json()
119 # compute plugin-specific initialization
120 js_init = render_to_string ( 'plugin-setenv.js', env )
121 self.add_js_chunks (request, js_init)
123 # interpret the result of requirements ()
124 self.handle_requirements (request)
128 # you may redefine this completely, but if you don't we'll just use methods
129 # . template_file() to find out which template to use, and
130 # . template_env() to compute a dictionary to pass along to the templating system
131 def render_content (self, request):
132 """Should return an HTML fragment"""
133 template = self.template_file()
134 env=self.template_env(request)
135 if not isinstance (env,dict):
136 raise Exception, "%s.template_env returns wrong type"%self.classname
137 result=render_to_string (template, env)
138 if self.need_debug():
139 print "%s.render_content: BEG --------------------"%self.classname
140 print "template=%s"%template
141 print "env.keys=%s"%env.keys()
144 print "%s.render_content: END --------------------"%self.classname
147 #################### requirements/prelude management
148 def _init_prelude (self, request):
149 if not hasattr (request, 'plugin_prelude'):
150 # include css/plugins.css
151 request.plugin_prelude=Prelude(css_files='css/plugin.css')
153 def inspect_request (self, request, message):
154 has=hasattr(request,'plugin_prelude')
155 get=getattr(request,'plugin_prelude','none-defined')
156 print "INSPECT (%s), hasattr %s, getattr %s"%(message,has,get)
158 # can be used directly in render_content()
159 def add_js_files (self, request, files):
160 self._init_prelude (request)
161 request.plugin_prelude.add_js_files (files)
162 def add_css_files (self, request, files):
163 self._init_prelude (request)
164 request.plugin_prelude.add_css_files (files)
165 def add_js_chunks (self, request, chunks):
166 self._init_prelude (request)
167 request.plugin_prelude.add_js_chunks (chunks)
168 def add_css_chunks (self, request, chunks):
169 self._init_prelude (request)
170 request.plugin_prelude.add_css_chunks (chunks)
172 # or from the result of self.requirements()
173 def handle_requirements (self, request):
175 d=self.requirements()
176 for (k,v) in d.iteritems():
177 if self.need_debug():
178 print "%s: handling requirement %s"%(self.classname,v)
180 method=Plugin.__dict__[method_name]
181 method(self,request,v)
182 except AttributeError:
183 # most likely the object does not have that method defined, which is fine
187 traceback.print_exc()
190 ######################################## abstract interface
191 # your plugin is expected to implement either
192 # (*) def render_content(self, request) -> html fragment
194 # (*) def template_file (self) -> filename
196 # (*) def template_env (self, request) -> dict
197 # this is the variable->value association used to render the template
198 # in which case the html template will be used
200 # if you see this string somewhere your template_file() code is not kicking in
201 def template_file (self): return "undefined_template"
202 def template_env (self, request): return {}
204 # # tell the framework about requirements (for the document <header>)
205 # # the notion of 'Media' in django provides for medium-dependant
206 # # selection of css files
207 # # as a first attempt however we keep a flat model for now
208 # # can use one string instead of a list or tuple if needed,
209 # # see requirements.py for details
210 # def requirements (self):
211 # return { 'js_files' : [], # a list of relative paths for js input files
212 # 'css_files': [], # ditto for css, could have been a dict keyed on
214 # 'js_chunk' : [], # (lines of) verbatim javascript code
215 # 'css_chunk': [], # likewise for css scripts
218 # # for better performance
219 # # you can specify a list of keys that won't be exposed as json attributes
220 # def exclude_from_json (self): return []
222 # mandatory : define the fields that need to be exposed to json as part of
223 # plugin initialization
224 # mention 'domid' if you need plugin_uuid
225 # also 'query_uuid' gets replaced with query.uuid
226 def json_settings_list (self): return ['json_settings_list-must-be-redefined']