rename js template
[myslice.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= [ 'Tabs' ]
18
19 class Plugin:
20
21     # using a simple incremental scheme to generate uuids for now
22     uuid=0
23
24     # xxx should generate some random id
25     @staticmethod
26     def newuuid():
27         Plugin.uuid += 1
28         return Plugin.uuid
29
30     ########## 
31     # Constructor
32     #### mandatory
33     # . title: is used visually for displaying the widget
34     # . name:  a simple id suitable for forging css names
35     #### optional
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
41     #### internal data
42     # . uuid: created internally
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, 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
53         self.title=title
54         self.name=name
55         self.add_to_settings ( ['title','name'] )
56         self.uuid=Plugin.newuuid()
57         self.classname=self._classname()
58         self.add_to_settings ( [ 'uuid', 'classname' ] )
59         self.visible=visible
60         self.hidable=hidable
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..
66         if self.need_debug():
67             print "Plugin.__init__ Created plugin with settings %s"%self._settings.keys()
68
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)
75         else:
76             for setting_name in setting_name_s:
77                 self._settings[setting_name]=getattr(self,setting_name)
78
79     def _classname (self): 
80         try:    return self.__class__.__name__
81         except: return 'Plugin'
82
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]
87
88     ##########
89     def need_debug (self):
90         if not DEBUG:           return False
91         if DEBUG is True:       return True
92         else:                   return self.classname in DEBUG
93
94     # returns the html code for that plugin
95     # in essence, wraps the results of self.render_content ()
96     def render (self, request):
97         uuid = self.uuid
98         # initialize prelude placeholder if needed
99         self._init_prelude (request)
100         # call render_content
101         plugin_content = self.render_content (request)
102         # shove this into plugin.html
103         env = {}
104         env ['plugin_content']= plugin_content
105         env.update(self._settings)
106         result = render_to_string ('plugin.html',env)
107
108         # expose _settings in json format to js, and add plugin_uuid: uuid in the mix
109         js_env = { 'plugin_uuid' : self.uuid }
110         js_env.update (self._settings)
111         settings_json = json.dumps (js_env, separators=(',',':'))
112         env ['settings_json' ] = settings_json
113         # compute plugin-specific initialization
114         js_init = render_to_string ( 'plugin_setenv.js', env )
115         print 'js_init',js_init
116         self.add_js_chunks (request, js_init)
117         
118         # interpret the result of requirements ()
119         self.handle_requirements (request)
120
121         return result
122         
123     # you may redefine this completely, but if you don't we'll just use methods 
124     # . template_file() to find out which template to use, and 
125     # . template_env() to compute a dictionary to pass along to the templating system
126     def render_content (self, request):
127         """Should return an HTML fragment"""
128         template = self.template_file()
129         env=self.template_env(request)
130         if not isinstance (env,dict):
131             raise Exception, "%s.template_env returns wrong type"%self.classname
132         # expose this class's settings to the template
133         # xxx we might need to check that this does not overwrite env..
134         env.update(self._settings)
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