f3fae50a43d6c683fabf3410ea1bc7784ddb24c1
[unfold.git] / engine / plugin.py
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
4
5 import json
6
7 from django.template.loader import render_to_string
8
9 from engine.prelude import Prelude
10
11 #################### 
12 # set DEBUG to
13 # . False : silent
14 # . [ 'SliceList', 'TabbedView' ] : to debug these classes
15 # . True : to debug all plugin
16
17 DEBUG= False
18 DEBUG= [ 'SimpleList' ]
19
20 class Plugin:
21
22     # using a simple incremental scheme to generate domids for now
23     # we just need this to be unique in a page
24     domid=0
25
26     @staticmethod
27     def newdomid():
28         Plugin.domid += 1
29         return "plugin-%d"%Plugin.domid
30
31     ########## 
32     # Constructor
33     #### mandatory
34     # . title: is used visually for displaying the widget
35     #### optional
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)
40     #### internal data
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
44     #### custom
45     # any other setting can also be set when creating the object, like
46     # p=Plugin(foo='bar')
47     # which will result in 'foo' being accessible to the template engine
48     # 
49     def __init__ (self, title, domid=None,
50                   visible=True, togglable=True, toggled=True, **settings):
51         self.title=title
52         if not domid: domid=Plugin.newdomid()
53         self.domid=domid
54         self.classname=self._classname()
55         self.visible=visible
56         self.togglable=togglable
57         self.toggled=toggled
58         # what comes from subclasses
59         for (k,v) in settings.iteritems():
60             setattr(self,k,v)
61             if self.need_debug(): print "%s init - subclass setting %s"%(self.classname,k)
62         # minimal debugging
63         if self.need_debug():
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
67
68     def _classname (self): 
69         try:    return self.__class__.__name__
70         except: return 'Plugin'
71
72     ##########
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
77
78     def setting_json (self, setting):
79         # TMP: js world expects plugin_uuid
80         if setting=='plugin_uuid':
81             value=self.domid
82         elif setting=='query_uuid':
83             try: value=self.query.uuid
84             except: return '%s:"undefined"'%setting
85         else:
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)
92
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):
97         result = "{"
98         result += "plugin_uuid:%s,"%self.domid
99         result += ",".join([ self.setting_json(setting) for setting in self.json_settings_list() ])
100         result += "}"
101         return result
102
103     # returns the html code for that plugin
104     # in essence, wraps the results of self.render_content ()
105     def render (self, request):
106         # initialize prelude placeholder if needed
107         self._init_prelude (request)
108         # call render_content
109         plugin_content = self.render_content (request)
110         # shove this into plugin.html
111         env = {}
112         env ['plugin_content']= plugin_content
113         env.update(self.__dict__)
114         result = render_to_string ('plugin.html',env)
115
116         env ['settings_json' ] = self.settings_json()
117         # compute plugin-specific initialization
118         js_init = render_to_string ( 'plugin-setenv.js', env )
119         self.add_js_chunks (request, js_init)
120         
121         # interpret the result of requirements ()
122         self.handle_requirements (request)
123
124         return result
125         
126     # you may redefine this completely, but if you don't we'll just use methods 
127     # . template_file() to find out which template to use, and 
128     # . template_env() to compute a dictionary to pass along to the templating system
129     def render_content (self, request):
130         """Should return an HTML fragment"""
131         template = self.template_file()
132         env=self.template_env(request)
133         if not isinstance (env,dict):
134             raise Exception, "%s.template_env returns wrong type"%self.classname
135         result=render_to_string (template, env)
136         if self.need_debug():
137             print "%s.render_content: BEG --------------------"%self.classname
138             print "template=%s"%template
139             print "env.keys=%s"%env.keys()
140             #print "env=%s"%env
141             #print result
142             print "%s.render_content: END --------------------"%self.classname
143         return result
144
145     #################### requirements/prelude management
146     def _init_prelude (self, request):
147         if not hasattr (request, 'plugin_prelude'): 
148             # include css/plugins.css
149             request.plugin_prelude=Prelude(css_files='css/plugin.css')
150
151     def inspect_request (self, request, message):
152         has=hasattr(request,'plugin_prelude')
153         get=getattr(request,'plugin_prelude','none-defined')
154         print "INSPECT (%s), hasattr %s, getattr %s"%(message,has,get)
155
156     # can be used directly in render_content()
157     def add_js_files (self, request, files):
158         self._init_prelude (request)
159         request.plugin_prelude.add_js_files (files)
160     def add_css_files (self, request, files):
161         self._init_prelude (request)
162         request.plugin_prelude.add_css_files (files)
163     def add_js_chunks (self, request, chunks):
164         self._init_prelude (request)
165         request.plugin_prelude.add_js_chunks (chunks)
166     def add_css_chunks (self, request, chunks):
167         self._init_prelude (request)
168         request.plugin_prelude.add_css_chunks (chunks)
169
170     # or from the result of self.requirements()
171     def handle_requirements (self, request):
172         try:
173             d=self.requirements()
174             for (k,v) in d.iteritems():
175                 if self.need_debug():
176                     print "%s: handling requirement %s"%(self.classname,v)
177                 method_name='add_'+k
178                 method=Plugin.__dict__[method_name]
179                 method(self,request,v)
180         except AttributeError: 
181             # most likely the object does not have that method defined, which is fine
182             pass
183         except:
184             import traceback
185             traceback.print_exc()
186             pass
187
188     ######################################## abstract interface
189     # your plugin is expected to implement either 
190     # (*) def render_content(self, request) -> html fragment
191     # -- or --
192     # (*) def template_file (self) -> filename
193     #   relative to STATIC 
194     # (*) def template_env (self, request) -> dict
195     #   this is the variable->value association used to render the template
196     # in which case the html template will be used
197
198     # if you see this string somewhere your template_file() code is not kicking in
199     def template_file (self):           return "undefined_template"
200     def template_env (self, request):   return {}
201
202 #    # tell the framework about requirements (for the document <header>)
203 #    # the notion of 'Media' in django provides for medium-dependant
204 #    # selection of css files
205 #    # as a first attempt however we keep a flat model for now
206 #    # can use one string instead of a list or tuple if needed, 
207 #    # see requirements.py for details
208 #    def requirements (self): 
209 #        return { 'js_files' : [],       # a list of relative paths for js input files
210 #                 'css_files': [],       # ditto for css, could have been a dict keyed on
211 #                                        # media instead
212 #                 'js_chunk' : [],       # (lines of) verbatim javascript code 
213 #                 'css_chunk': [],       # likewise for css scripts
214 #                 }
215     
216 #    # for better performance
217 #    # you can specify a list of keys that won't be exposed as json attributes
218 #    def exclude_from_json (self): return []
219
220     # mandatory : define the fields that need to be exposed to json as part of 
221     # plugin initialization
222     # mention 'domid' if you need plugin_uuid
223     # also 'query_uuid' gets replaced with query.uuid
224     def json_settings_list (self): return ['json_settings_list-must-be-redefined']
225