no spinner on querycode
[unfold.git] / engine / plugin.py
index ff5a598..36d60df 100644 (file)
@@ -6,6 +6,7 @@ import json
 
 from django.template.loader import render_to_string
 
+from engine.page import Page
 from engine.prelude import Prelude
 
 #################### 
@@ -14,76 +15,77 @@ from engine.prelude import Prelude
 # . [ 'SliceList', 'TabbedView' ] : to debug these classes
 # . True : to debug all plugin
 
-DEBUG= [ 'Tabs' ]
+DEBUG= False
+#DEBUG= [ 'SliceList' ]
+
+# decorator to deflect calls on Plugin to its Prelude through self.page.prelude
+def to_prelude (method):
+    def actual (self, *args, **kwds):
+        prelude_method=Prelude.__dict__[method.__name__]
+        return prelude_method(self.page.prelude,*args, **kwds)
+    return actual
 
 class Plugin:
 
-    # using a simple incremental scheme to generate uuids for now
-    uuid=0
+    # using a simple incremental scheme to generate domids for now
+    # we just need this to be unique in a page
+    domid=0
 
-    # xxx should generate some random id
     @staticmethod
-    def newuuid():
-        Plugin.uuid += 1
-        return Plugin.uuid
+    def newdomid():
+        Plugin.domid += 1
+        return "plugin-%d"%Plugin.domid
 
     ########## 
     # Constructor
     #### mandatory
+    # . page: the context of the request being served
     # . title: is used visually for displaying the widget
-    # . name:  a simple id suitable for forging css names
     #### optional
-    # . hidable: whether it can be turned on and off from the UI
-    #   like e.g. PleKitToggle
-    # . hidden_by_default: if hidable, what's the initial status
-    # . visible: if not set the plugin does not show up at all,
-    #   not quite sure what this was for
+    # . togglable: whether it can be turned on and off (like PleKitToggle)
+    # . toggled: if togglable, what's the initial status
+    # . visible: if not set the plugin does not show up at all
+    #            (not quite sure what this was for)
     #### internal data
-    # . uuid: created internally
+    # . domid: created internally, but can be set at creation time if needed
+    #          useful for hand-made css, or for selecting an active plugin in a composite
     # . rank: this is for plugins sons of a composite plugin
     #### custom
     # any other setting can also be set when creating the object, like
     # p=Plugin(foo='bar')
     # which will result in 'foo' being accessible to the template engine
     # 
-    def __init__ (self, title, name,
-                  visible=True, hidable=True, hidden_by_default=False, **settings):
-        # what is in this dictionary will get exposed to template and to javascript
-        self._settings=settings
+    def __init__ (self, page, title, domid=None,
+                  visible=True, togglable=True, toggled=True, **settings):
+        self.page = page
         self.title=title
-        self.name=name
-        self.add_to_settings ( ['title','name'] )
-        self.uuid=Plugin.newuuid()
-        self.classname=self._classname()
-        self.add_to_settings ( [ 'uuid', 'classname' ] )
+        # callers can provide their domid for css'ing 
+        if not domid: domid=Plugin.newdomid()
+        self.domid=domid
+        self.classname=self._py_classname()
+        self.plugin_classname=self._js_classname()
         self.visible=visible
-        self.hidable=hidable
-        self.hidden_by_default=hidden_by_default
-        self.add_to_settings( ['visible','hidable','hidden_by_default'] )
-        # we store as a dictionary the arguments passed to constructor
-        # e.g. SimpleList (list=[1,2,3]) => _settings = { 'list':[1,2,3] }
-        # our own settings are not made part of _settings but could be..
+        self.togglable=togglable
+        self.toggled=toggled
+        # what comes from subclasses
+        for (k,v) in settings.iteritems():
+            setattr(self,k,v)
+            if self.need_debug(): print "%s init - subclass setting %s"%(self.classname,k)
+        # minimal debugging
         if self.need_debug():
-            print "Plugin.__init__ Created plugin with settings %s"%self._settings.keys()
-
-    # subclasses might handle some fields in their own way, 
-    # in which case this call is needed to capture that setting
-    # see e.g. SimpleList or SliceList for an example of that
-    def add_to_settings (self, setting_name_s):
-        if not isinstance (setting_name_s, list):
-            self._settings[setting_name_s]=getattr(self,setting_name_s)
-        else:
-            for setting_name in setting_name_s:
-                self._settings[setting_name]=getattr(self,setting_name)
+            print "%s init dbg .... BEG"%self.classname
+            for (k,v) in self.__dict__.items(): print "dbg %s:%s"%(k,v)
+            print "%s init dbg .... END"%self.classname
+        # do this only once the structure is fine
+        self.page.record_plugin(self)
 
-    def _classname (self): 
+    def _py_classname (self): 
         try:    return self.__class__.__name__
         except: return 'Plugin'
 
-    # shorthands to inspect _settings
-    def get_setting (self, setting, default=None):
-        if setting not in self._settings: return default
-        else:                             return self._settings[setting]
+    def _js_classname (self): 
+        try:    return self.plugin_classname ()
+        except: return self._py_classname()
 
     ##########
     def need_debug (self):
@@ -91,29 +93,58 @@ class Plugin:
         if DEBUG is True:       return True
         else:                   return self.classname in DEBUG
 
+    def setting_json (self, setting):
+        # TMP: js world expects plugin_uuid
+        if setting=='plugin_uuid':
+            value=self.domid
+        elif setting=='query_uuid':
+            try: value=self.query.uuid
+            except: return '%s:"undefined"'%setting
+        else:
+            value=getattr(self,setting,None)
+            if not value: value = "unknown-setting-%s"%setting
+        # first try to use to_json method (json.dumps not working on class instances)
+        try:    value_json=value.to_json()
+        except: value_json=json.dumps(value,separators=(',',':'))
+        return "%s:%s"%(setting,value_json)
+
+    # expose in json format to js the list of fields as described in json_settings_list()
+    # and add plugin_uuid: domid in the mix
+    # NOTE this plugin_uuid thing might occur in js files from joomla/js, ** do not rename **
+    def settings_json (self):
+        result = "{"
+        result += ",".join([ self.setting_json(setting) for setting in self.json_settings_list() ])
+        result += "}"
+        return result
+
+    # as a first approximation, only plugins that are associated with a query
+    # need to be prepared for js - meaning their json settings get exposed to js
+    # others just get displayed and that's it
+    def export_json_settings (self):
+        return 'query' in self.__dict__
+    
+    def start_with_spin (self):
+        return self.export_json_settings()
+
     # returns the html code for that plugin
     # in essence, wraps the results of self.render_content ()
     def render (self, request):
-        uuid = self.uuid
-        # initialize prelude placeholder if needed
-        self._init_prelude (request)
         # call render_content
         plugin_content = self.render_content (request)
         # shove this into plugin.html
         env = {}
         env ['plugin_content']= plugin_content
-        env.update(self._settings)
+        # need_spin is used in plugin.html
+        self.need_spin=self.start_with_spin()
+        env.update(self.__dict__)
         result = render_to_string ('plugin.html',env)
 
-        # expose _settings in json format to js, and add plugin_uuid: uuid in the mix
-        js_env = { 'plugin_uuid' : self.uuid }
-        js_env.update (self._settings)
-        settings_json = json.dumps (js_env, separators=(',',':'))
-        env ['settings_json' ] = settings_json
-        # compute plugin-specific initialization
-        js_init = render_to_string ( 'plugin_setenv.js', env )
-        print 'js_init',js_init
-        self.add_js_chunks (request, js_init)
+        # export this only for relevant plugins
+        if self.export_json_settings():
+            env ['settings_json' ] = self.settings_json()
+            # compute plugin-specific initialization
+            js_init = render_to_string ( 'plugin-setenv.js', env )
+            self.add_js_chunks (js_init)
         
         # interpret the result of requirements ()
         self.handle_requirements (request)
@@ -129,9 +160,6 @@ class Plugin:
         env=self.template_env(request)
         if not isinstance (env,dict):
             raise Exception, "%s.template_env returns wrong type"%self.classname
-        # expose this class's settings to the template
-        # xxx we might need to check that this does not overwrite env..
-        env.update(self._settings)
         result=render_to_string (template, env)
         if self.need_debug():
             print "%s.render_content: BEG --------------------"%self.classname
@@ -142,31 +170,6 @@ class Plugin:
             print "%s.render_content: END --------------------"%self.classname
         return result
 
-    #################### requirements/prelude management
-    def _init_prelude (self, request):
-        if not hasattr (request, 'plugin_prelude'): 
-            # include css/plugins.css
-            request.plugin_prelude=Prelude(css_files='css/plugin.css')
-
-    def inspect_request (self, request, message):
-        has=hasattr(request,'plugin_prelude')
-        get=getattr(request,'plugin_prelude','none-defined')
-        print "INSPECT (%s), hasattr %s, getattr %s"%(message,has,get)
-
-    # can be used directly in render_content()
-    def add_js_files (self, request, files):
-        self._init_prelude (request)
-        request.plugin_prelude.add_js_files (files)
-    def add_css_files (self, request, files):
-        self._init_prelude (request)
-        request.plugin_prelude.add_css_files (files)
-    def add_js_chunks (self, request, chunks):
-        self._init_prelude (request)
-        request.plugin_prelude.add_js_chunks (chunks)
-    def add_css_chunks (self, request, chunks):
-        self._init_prelude (request)
-        request.plugin_prelude.add_css_chunks (chunks)
-
     # or from the result of self.requirements()
     def handle_requirements (self, request):
         try:
@@ -174,9 +177,10 @@ class Plugin:
             for (k,v) in d.iteritems():
                 if self.need_debug():
                     print "%s: handling requirement %s"%(self.classname,v)
+                # e.g. js_files -> add_js_files
                 method_name='add_'+k
-                method=Plugin.__dict__[method_name]
-                method(self,request,v)
+                method=Page.__dict__[method_name]
+                method(self.page,v)
         except AttributeError: 
             # most likely the object does not have that method defined, which is fine
             pass
@@ -185,6 +189,17 @@ class Plugin:
             traceback.print_exc()
             pass
 
+    #################### requirements/prelude management
+    # just forward to our prelude instance - see decorator above
+    @to_prelude
+    def add_js_files (self):pass
+    @to_prelude
+    def add_css_files (self):pass
+    @to_prelude
+    def add_js_chunks (self):pass
+    @to_prelude
+    def add_css_chunks (self):pass
+
     ######################################## abstract interface
     # your plugin is expected to implement either 
     # (*) def render_content(self, request) -> html fragment
@@ -213,3 +228,23 @@ class Plugin:
 #                 'css_chunk': [],       # likewise for css scripts
 #                 }
     
+#    # for better performance
+#    # you can specify a list of keys that won't be exposed as json attributes
+#    def exclude_from_json (self): return []
+
+    # mandatory : define the fields that need to be exposed to json as part of 
+    # plugin initialization
+    # mention 'domid' if you need plugin_uuid
+    # also 'query_uuid' gets replaced with query.uuid
+    def json_settings_list (self): return ['json_settings_list-must-be-redefined']
+
+    # might also define these ones:
+    #
+    # see e.g. slicelist.py that piggybacks simplelist js code
+    # def plugin_classname (self)
+    #
+    # whether we export the json settings to js
+    # def export_json_settings (self)
+    #
+    # whether we show an initial spinner
+    # def start_with_spin (self)