remove dbg statement
[myslice.git] / unfold / 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 unfold.page import Page
10 from unfold.prelude import Prelude
11
12 #################### 
13 # set DEBUG to
14 # . False : silent
15 # . [ 'SliceList', 'TabbedView' ] : to debug these classes
16 # . True : to debug all plugin
17
18 DEBUG= False
19 #DEBUG= [ 'SimpleList' ]
20 #DEBUG=True
21
22 # decorator to deflect calls on Plugin to its Prelude through self.page.prelude
23 def to_prelude (method):
24     def actual (self, *args, **kwds):
25         prelude_method=Prelude.__dict__[method.__name__]
26         return prelude_method(self.page.prelude,*args, **kwds)
27     return actual
28
29 class Plugin:
30
31     # using a simple incremental scheme to generate domids for now
32     # we just need this to be unique in a page
33     domid=0
34
35     @staticmethod
36     def newdomid():
37         Plugin.domid += 1
38         return "plugin-%d"%Plugin.domid
39
40     ########## 
41     # Constructor
42     #### mandatory
43     # . page: the context of the request being served
44     # . title: is used visually for displaying the widget
45     #### optional
46     # . visible: if not set the plugin does not show up at all
47     #            (not quite sure what this was for)
48     # . togglable: whether it can be turned on and off by clicking on the title (like PleKitToggle)
49     # . toggled:   whether the plugin should startup open/shown or closed/hidden
50     #              possible values are
51     #   .. True         : start up open/hidden
52     #   .. False        : start up closed/shown
53     #   .. 'persistent' : start up as it was the last time that browser showed it (based on 'domid')
54     #                NOTE that it is required for you to set a domid if you want to use persistent mode
55     #                     since domid is the key for storing that data in the browser storage space
56     #   .. None         : if not passed to __init__ at all, then the default_toggled() method is called
57     #   ..              : anything else, defaults to True
58     #
59     #### internal data
60     # . domid: created internally, but can be set at creation time if needed
61     #          useful for hand-made css, or for selecting an active plugin in a composite
62     # . rank: this is for plugins sons of a composite plugin
63     #### custom
64     # any other setting can also be set when creating the object, like
65     # p=Plugin(foo='bar')
66     # which will result in 'foo' being accessible to the template engine
67     # 
68     def __init__ (self, page, title, domid=None,
69                   visible=True, togglable=True, toggled=None, **settings):
70         self.page = page
71         self.title=title
72         # callers can provide their domid for css'ing 
73         if not domid: domid=Plugin.newdomid()
74         self.domid=domid
75         self.classname=self._py_classname()
76         self.plugin_classname=self._js_classname()
77         self.visible=visible
78         self.togglable=togglable
79         if toggled is not None: self.toggled=toggled
80         else:                   self.toggled=self.default_toggled()
81         # what comes from subclasses
82         for (k,v) in settings.iteritems():
83             setattr(self,k,v)
84             if self.need_debug(): print "%s init - subclass setting %s"%(self.classname,k)
85         # minimal debugging
86         if self.need_debug():
87             print "%s init dbg .... BEG"%self.classname
88             for (k,v) in self.__dict__.items(): print "dbg %s:%s"%(k,v)
89             print "%s init dbg .... END"%self.classname
90         # do this only once the structure is fine
91         self.page.record_plugin(self)
92
93     def __repr__ (self):
94         return "[%s]:%s"%(self.classname,self.domid)
95
96     def _py_classname (self): 
97         try:    return self.__class__.__name__
98         except: return 'Plugin'
99
100     def _js_classname (self): 
101         try:    return self.plugin_classname ()
102         except: return self._py_classname()
103
104     ##########
105     def need_debug (self):
106         if not DEBUG:           return False
107         if DEBUG is True:       return True
108         else:                   return self.classname in DEBUG
109
110     def setting_json (self, setting):
111         # TMP: js world expects plugin_uuid
112         if setting=='plugin_uuid':
113             value=self.domid
114         elif setting=='query_uuid':
115             try: value=self.query.query_uuid
116             except: return '%s:"undefined"'%setting
117         else:
118             value=getattr(self,setting,None)
119             if value is None: value = "unknown-setting-%s"%setting
120         # first try to use to_json method (json.dumps not working on class instances)
121         try:    value_json=value.to_json()
122         except: value_json=json.dumps(value,separators=(',',':'))
123         return "%s:%s"%(setting,value_json)
124
125     # expose in json format to js the list of fields as described in json_settings_list()
126     # and add plugin_uuid: domid in the mix
127     # NOTE this plugin_uuid thing might occur in js files from joomla/js, ** do not rename **
128     def settings_json (self):
129         exposed_settings=self.json_settings_list()
130         if 'query' in exposed_settings:
131             print "WARNING, cannot expose 'query' directly in json_settings_list, query_uuid is enough"
132         result = "{"
133         result += ",".join([ self.setting_json(setting) for setting in self.json_settings_list() ])
134         result += "}"
135         return result
136
137     # as a first approximation, only plugins that are associated with a query
138     # need to be prepared for js - meaning their json settings get exposed to js
139     # others just get displayed and that's it
140     def export_json_settings (self):
141         return 'query_uuid' in self.json_settings_list()
142     
143     # by default we create a timer if there's a query attached, redefine to change this behaviour
144     def start_with_spin (self):
145         return self.export_json_settings()
146
147     # returns the html code for that plugin
148     # in essence, wraps the results of self.render_content ()
149     def render (self, request):
150         # call render_content
151         plugin_content = self.render_content (request)
152         # shove this into plugin.html
153         env = {}
154         env ['plugin_content']= plugin_content
155         # need_spin is used in plugin.html
156         self.need_spin=self.start_with_spin()
157         env.update(self.__dict__)
158         # translate high-level 'toggled' into 4 different booleans
159         if self.toggled=='persistent':
160             # start with everything turned off and let the js callback do its job
161             env.update({'persistent_toggle':True,'display_hide_button':False,'display_show_button':False,'display_body':False})
162         elif self.toggled==False:
163             env.update({'persistent_toggle':False,'display_hide_button':False,'display_show_button':True,'display_body':False})
164         else:
165             env.update({'persistent_toggle':False,'display_hide_button':True,'display_show_button':False,'display_body':True})
166         if self.need_debug(): 
167             print "rendering plugin.html with env keys %s"%env.keys()
168             print "rendering plugin.html with env"
169             for (k,v) in env.items(): 
170                 if "display" in k or "persistent" in k: print k,'->',v
171         result = render_to_string ('plugin.html',env)
172
173         # export this only for relevant plugins
174         if self.export_json_settings():
175             env ['settings_json' ] = self.settings_json()
176             # compute plugin-specific initialization
177             js_init = render_to_string ( 'plugin-init.js', env )
178             self.add_js_chunks (js_init)
179         
180         # interpret the result of requirements ()
181         self.handle_requirements (request)
182
183         return result
184         
185     # you may redefine this completely, but if you don't we'll just use methods 
186     # . template_file() to find out which template to use, and 
187     # . template_env() to compute a dictionary to pass along to the templating system
188     def render_content (self, request):
189         """Should return an HTML fragment"""
190         template = self.template_file()
191         # start with a fresh one
192         env={}
193         # add our own settings as defaults
194         env.update(self.__dict__)
195         # then the things explicitly defined in template_env()
196         env.update(self.template_env(request))
197         if not isinstance (env,dict):
198             raise Exception, "%s.template_env returns wrong type"%self.classname
199         result=render_to_string (template, env)
200         if self.need_debug():
201             print "%s.render_content: BEG --------------------"%self.classname
202             print "template=%s"%template
203             print "env.keys=%s"%env.keys()
204             #print "env=%s"%env
205             #print result
206             print "%s.render_content: END --------------------"%self.classname
207         return result
208
209     # or from the result of self.requirements()
210     def handle_requirements (self, request):
211         try:
212             d=self.requirements()
213             for (k,v) in d.iteritems():
214                 if self.need_debug():
215                     print "%s: handling requirement %s"%(self.classname,v)
216                 # e.g. js_files -> add_js_files
217                 method_name='add_'+k
218                 method=Page.__dict__[method_name]
219                 method(self.page,v)
220         except AttributeError: 
221             # most likely the object does not have that method defined, which is fine
222             pass
223         except:
224             import traceback
225             traceback.print_exc()
226             pass
227
228     #################### requirements/prelude management
229     # just forward to our prelude instance - see decorator above
230     @to_prelude
231     def add_js_files (self):pass
232     @to_prelude
233     def add_css_files (self):pass
234     @to_prelude
235     def add_js_chunks (self):pass
236     @to_prelude
237     def add_css_chunks (self):pass
238
239     ######################################## abstract interface
240     # your plugin is expected to implement either 
241     # (*) def render_content(self, request) -> html fragment
242     # -- or --
243     # (*) def template_file (self) -> filename
244     #   relative to STATIC 
245     # (*) def template_env (self, request) -> dict
246     #   this is the variable->value association used to render the template
247     # in which case the html template will be used
248
249     # if you see this string somewhere your template_file() code is not kicking in
250     def template_file (self):           return "undefined_template"
251     def template_env (self, request):   return {}
252
253     def default_toggled (self):         return 'persistent'
254
255 #    # tell the framework about requirements (for the document <header>)
256 #    # the notion of 'Media' in django provides for medium-dependant
257 #    # selection of css files
258 #    # as a first attempt however we keep a flat model for now
259 #    # can use one string instead of a list or tuple if needed, 
260 #    # see requirements.py for details
261 #    def requirements (self): 
262 #        return { 'js_files' : [],       # a list of relative paths for js input files
263 #                 'css_files': [],       # ditto for css, could have been a dict keyed on
264 #                                        # media instead
265 #                 'js_chunk' : [],       # (lines of) verbatim javascript code 
266 #                 'css_chunk': [],       # likewise for css scripts
267 #                 }
268     
269 #    # for better performance
270 #    # you can specify a list of keys that won't be exposed as json attributes
271 #    def exclude_from_json (self): return []
272
273     # mandatory : define the fields that need to be exposed to json as part of 
274     # plugin initialization
275     # mention 'domid' if you need plugin_uuid
276     # also 'query_uuid' gets replaced with query.query_uuid
277     def json_settings_list (self): return ['json_settings_list-must-be-redefined']
278
279     # might also define these ones:
280     #
281     # see e.g. slicelist.py that piggybacks simplelist js code
282     # def plugin_classname (self)
283     #
284     # whether we export the json settings to js
285     # def export_json_settings (self)
286     #
287     # whether we show an initial spinner
288     # def start_with_spin (self)