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