add mandatory title and name args to plugin creation, remove title()
[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 # set to
12 # . False : silent
13 # [ 'SliceList', 'TabbedView' ] : to debug these classes
14 # True : to debug all slices
15
16 DEBUG= [ 'SliceList' ]
17
18 class Plugin:
19
20     # using a simple incremental scheme to generate uuids for now
21     uuid=0
22
23     # xxx should generate some random id
24     @staticmethod
25     def newuuid():
26         Plugin.uuid += 1
27         return Plugin.uuid
28
29     ########## 
30     # Constructor
31     #### mandatory
32     # . title: is used visually for displaying the widget
33     # . name:  a simple id suitable for forging css names
34     #### optional
35     # . hidable: whether it can be turned on and off from the UI
36     #   like e.g. PleKitToggle
37     # . hidden_by_default: if hidable, 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     # . uuid: created internally
42     # . rank: this is for plugins sons of a composite plugin
43     #### custom
44     # any other setting can also be set when creating the object, like
45     # p=Plugin(foo='bar')
46     # which will result in 'foo' being accessible to the template engine
47     # 
48     def __init__ (self, title, name,
49                   visible=True, hidable=True, hidden_by_default=False, **settings):
50         # what is in this dictionary will get exposed to template and to javascript
51         self._settings=settings
52         self.title=title
53         self.name=name
54         self.add_to_settings ( ['title','name'] )
55         self.uuid=Plugin.newuuid()
56         self.visible=visible
57         self.hidable=hidable
58         self.hidden_by_default=hidden_by_default
59         self.add_to_settings( ['uuid','visible','hidable','hidden_by_default'] )
60         # we store as a dictionary the arguments passed to constructor
61         # e.g. SimpleList (list=[1,2,3]) => _settings = { 'list':[1,2,3] }
62         # our own settings are not made part of _settings but could be..
63         if self.need_debug():
64             print "Plugin.__init__ Created plugin with settings %s"%self._settings.keys()
65
66     # subclasses might handle some fields in their own way, 
67     # in which case this call is needed to capture that setting
68     # see e.g. SimpleList or SliceList for an example of that
69     def add_to_settings (self, setting_name_s):
70         if not isinstance (setting_name_s, list):
71             self._settings[setting_name_s]=getattr(self,setting_name_s)
72         else:
73             for setting_name in setting_name_s:
74                 self._settings[setting_name]=getattr(self,setting_name)
75
76     def classname (self): 
77         try:    return self.__class__.__name__
78         except: return 'Plugin'
79
80     # shorthands to inspect _settings
81     def get_setting (self, setting, default=None):
82         if setting not in self._settings: return default
83         else:                             return self._settings[setting]
84
85     def is_visible (self): return self.visible
86     def is_hidable (self): return self.hidable
87     def is_hidden_by_default (self): return self.hidden_by_default
88
89     ##########
90     def need_debug (self):
91         if not DEBUG:           return False
92         if DEBUG is True:       return True
93         else:                   return self.classname() in DEBUG
94
95     # returns the html code for that plugin
96     # in essence, wraps the results of self.render_content ()
97     def render (self, request):
98         uuid = self.uuid
99         classname = self.classname()
100         # initialize prelude placeholder 
101         self._init_request (request)
102         
103         # call render_content
104         plugin_content = self.render_content (request)
105         # expose _settings in json format to js
106         settings_json = json.dumps (self._settings, separators=(',',':'))
107
108         result = render_to_string ('plugin.html',
109                                    {'uuid':uuid, 
110                                     'classname':classname,
111                                     'visible':self.is_visible(),
112                                     'hidable':self.is_hidable(),
113                                     'hidden':self.is_hidden_by_default(),
114                                     'plugin_content' : plugin_content,
115                                     'settings_json' : settings_json,
116                                     })
117
118         # handle requirements() if defined on this class
119         try: 
120             self.handle_requirements (request, self.requirements())
121         except AttributeError: 
122             # most likely the object does not have that method defined, which is fine
123             pass
124         except:
125             import traceback
126             traceback.print_exc()
127             pass
128
129         return result
130         
131     # you may redefine this completely, but if you don't we'll just use methods 
132     # . template_file() to find out which template to use, and 
133     # . template_env() to compute a dictionary to pass along to the templating system
134     def render_content (self, request):
135         """Should return an HTML fragment"""
136         template = self.template_file()
137         env=self.template_env(request)
138         if not isinstance (env,dict):
139             raise Exception, "%s.template_env returns wrong type"%self.classname()
140         # expose this class's settings to the template
141         # xxx we might need to check that this does not overwrite env..
142         env.update(self._settings)
143         result=render_to_string (template, env)
144         if self.need_debug():
145             print "%s.render_content: BEG --------------------"%self.classname()
146             print "template=%s"%template
147             print "env=%s"%env.keys()
148             # print result
149             print "%s.render_content: END --------------------"%self.classname()
150         return result
151
152     #################### requirements/prelude management
153     def _init_request (self, request):
154         if not hasattr (request, 'plugin_prelude'): 
155             # include css/plugins.css
156             request.plugin_prelude=Prelude(css_files='css/plugin.css')
157
158     def inspect_request (self, request, message):
159         has=hasattr(request,'plugin_prelude')
160         get=getattr(request,'plugin_prelude','none-defined')
161         print "INSPECT (%s), hasattr %s, getattr %s"%(message,has,get)
162
163     # can be used directly in render_content()
164     def add_js_files (self, request, files):
165         self._init_request (request)
166         request.plugin_prelude.add_js_files (files)
167     def add_css_files (self, request, files):
168         self._init_request (request)
169         request.plugin_prelude.add_css_files (files)
170     def add_js_chunks (self, request, chunks):
171         self._init_request (request)
172         request.plugin_prelude.add_js_chunks (chunks)
173     def add_css_chunks (self, request, chunks):
174         self._init_request (request)
175         request.plugin_prelude.add_css_chunks (chunks)
176
177     # or from the result of self.requirements()
178     def handle_requirements (self, request, d):
179         for (k,v) in d.iteritems():
180             if self.need_debug():
181                 print "%s: handling requirement %s"%(self.classname(),v)
182             method_name='add_'+k
183             method=Plugin.__dict__[method_name]
184             method(self,request,v)
185
186     ######################################## abstract interface
187     # your plugin is expected to implement either 
188     # (*) def render_content(self, request) -> html fragment
189     # -- or --
190     # (*) def template_file(self) -> filename
191     #   relative to STATIC 
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
195
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 {}
199
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
209 #                                        # media instead
210 #                 'js_chunk' : [],       # (lines of) verbatim javascript code 
211 #                 'css_chunk': [],       # likewise for css scripts
212 #                 }
213