Package pyforms :: Package web :: Module BaseWidget |
[hide private]
[frames] | no frames]

# Source Code for Module pyforms.web.BaseWidget

      1
      2  from pyforms.web.Controls.ControlBase import ControlBase
      3  from pyforms.web.Controls.ControlFile import ControlFile
      4  from pyforms.web.Controls.ControlSlider import ControlSlider
      5  from pyforms.web.Controls.ControlText import ControlText
      6  from pyforms.web.Controls.ControlCheckBox import ControlCheckBox
      7  from pyforms.web.Controls.ControlPlayer import ControlPlayer
      8  from pyforms.web.Controls.ControlButton import ControlButton
      9  import uuid, os, shutil
     10
     11 -class BaseWidget(object):
     12
     13      _formset   = None
     14      _splitters = None
     15
     16 -    def __init__(self, title):
     17          self._splitters     = []
     18          self._title         = title
     19          self._formLoaded    = False
     20          self._controls      = []
     21          self._controlsPrefix = ''
     22          self._html          = ''
     23          self._js            = ''
     24
     25      ############################################################################
     26      ############ Module functions  #############################################
     27      ############################################################################
     28
     29 -    def initForm(self):
     30          """
     31          Generate the module Form
     32          """
     33          self._html = ''
     34          self._js = ''
     35          if self._formset != None:
     36              self._html += self.generatePanel(self._formset)
     37              self._js = "\n".join( self._controls )
     38          self._formLoaded = True
     39          return { 'code': self._html, 'controls_js': self._js, 'title': self._title }
     40
     41
     42
     43 -    def generateTabs(self, formsetDict):
     44          """
     45          Generate QTabWidget for the module form
     46          @param formset: Tab form configuration
     47          @type formset: dict
     48          """
     49          tabs_head = ""
     50          tabs_body = ""
     51          tab_id = uuid.uuid4()
     52
     53          for index, (key, item) in enumerate( sorted(formsetDict.items()) ):
     54              tabs_body += "<div id='%s-tab%d' >%s</div>\n" % (tab_id, index, self.generatePanel(item))
     55              tabs_head += "<li><a href='#%s-tab%d' >%s</a></li>\n" % (tab_id, index, key[key.find(':')+1:])
     56          return """<div id='%s' class='application-tabs' ><ul>%s</ul> %s</div>""" % (tab_id, tabs_head, tabs_body)
     57
     58
     59
     60 -    def generatePanel(self, formset):
     61          """
     62          Generate a panel for the module form with all the controls
     63          formset format example: [('_video', '_arenas', '_run'), {"Player":['_threshold', "_player", "=", "_results", "_query"], "Background image":[(' ', '_selectBackground', '_paintBackground'), '_image']}, "_progress"]
     64          tuple: will display the controls in the same horizontal line
     65          list: will display the controls in the same vertical line
     66          dict: will display the controls in a tab widget
     67          '||': will plit the controls in a horizontal line
     68          '=': will plit the controls in a vertical line
     69          @param formset: Form configuration
     70          @type formset: list
     71          """
     72          control = ""
     73          if '=' in formset:
     74              tmp = list( formset )
     75              index = tmp.index('=')
     76              firstPanel = self.generatePanel(formset[0:index])
     77              secondPanel = self.generatePanel(formset[index+1:])
     78              splitter_id =uuid.uuid4()
     79              self._splitters.append( splitter_id )
     80              control = ("<div id='%s' class='horizontalSplitter' ><div>" + firstPanel + "</div><div>" + secondPanel + "</div></div>") % ( splitter_id, )
     81              return control
     82          elif '||' in formset:
     83              tmp = list( formset )
     84              index = tmp.index('||')
     85              firstPanel = self.generatePanel(formset[0:index])
     86              secondPanel = self.generatePanel(formset[index+1:])
     87              splitter_id = uuid.uuid4()
     88              self._splitters.append( splitter_id )
     89              control = ("<div id='%s' class='verticalSplitter' ><div>" + firstPanel + "</div><div>" + secondPanel + "</div></div>") % ( splitter_id, )
     90              return control
     91
     92          layout = ""
     93          if type(formset) is tuple:
     94              for row in formset:
     95                  if isinstance(row, (list, tuple)):
     96                      panel = self.generatePanel( row )
     97                      layout += "<div class='rows' >%s</div>" % panel
     98                  elif row == " ":
     99                      layout += "<div class='space' ></div>"
    100                  elif type(row) is dict:
    101                      tabs = self.generateTabs(row)
    102                      layout += tabs
    103                  else:
    104                      control = self.formControls.get(row, None)
    105                      if control==None:
    106                          if row.startswith('info:'): layout += "<pre class='info' >%s</pre>" % row[5:]
    107                          elif row.startswith('h1:'): layout += "<h1>%s</h1>" % row[3:]
    108                          elif row.startswith('h2:'): layout += "<h2>%s</h2>" % row[3:]
    109                          elif row.startswith('h3:'): layout += "<h3>%s</h3>" % row[3:]
    110                          elif row.startswith('h4:'): layout += "<h4>%s</h4>" % row[3:]
    111                          elif row.startswith('h5:'): layout += "<h5>%s</h5>" % row[3:]
    112                          else: layout += "<span class='info' >%s</span>" % row
    113                      else:
    114                          self._controls.append( control.initControl() )
    115                          layout += "<div class='control' >%s</div>" % control
    116          elif type(formset) is list:
    117              for row in formset:
    118                  if isinstance(row, (list, tuple)):
    119                      panel = self.generatePanel( row )
    120                      layout += "<div class='columns' >%s</div>" % panel
    121                  elif row == " ":
    122                      layout += "<div class='space' ></div>"
    123                  elif type(row) is dict:
    124                      tabs = self.generateTabs(row)
    125                      layout += tabs
    126                  else:
    127                      control = self.formControls.get(row, None)
    128                      if control==None:
    129                          if row.startswith('info:'): layout += "<pre class='info' >%s</pre>" % row[5:]
    130                          elif row.startswith('h1:'): layout += "<h1>%s</h1>" % row[3:]
    131                          elif row.startswith('h2:'): layout += "<h2>%s</h2>" % row[3:]
    132                          elif row.startswith('h3:'): layout += "<h3>%s</h3>" % row[3:]
    133                          elif row.startswith('h4:'): layout += "<h4>%s</h4>" % row[3:]
    134                          elif row.startswith('h5:'): layout += "<h5>%s</h5>" % row[3:]
    135                          else: layout += "<span class='info' >%s</span>" % row
    136                      else:
    137                          self._controls.append( control.initControl() )
    138                          layout += "<div class='control' >%s</div>" % control
    139
    140          return layout
    141
    142 -    def findParameterByLabel(self, label):
    143          for a in self.formControls.values():
    144              if a._label == label: return a._name
    145          return None
    146
    147
    148 -    def loadSerializedForm(self, params):
    149          for key, value in params.items():
    150              control = self.formControls.get(key, None)
    151              if control!=None:control.value = value
    152
    153          if 'event' in params.keys():
    154              for key, item in self.formControls.items():
    155                  if key==params['event']['control']:
    156                      func = getattr(item, params['event']['event'])
    157                      func()
    158
    159
    160 -    def serializeForm(self):
    161          res = {}
    162          for key, item in self.formControls.items():
    163              if isinstance(item, ControlPlayer ):
    164                  res[item._name] = item.value
    165                  if item._value!=None and item._value!='': item._value.release() #release any open video
    166              elif isinstance(item, ControlButton ):
    167                  pass
    168              else:
    169                  res[item._name] = item.value
    170
    171          return res
    172
    173      ############################################################################
    174      ############ Parent class functions reemplementation #######################
    175      ############################################################################
    176
    177 -    def show(self): pass
    178
    179      ############################################################################
    180      ############ Properties ####################################################
    181      ############################################################################
    182
    183      @property
    184 -    def formControls(self):
    185          """
    186          Return all the form controls from the the module
    187          """
    188          result = {}
    189          for name, var in vars(self).items():
    190              if isinstance(var, ControlBase):
    191                  var._name = self._controlsPrefix+"-"+name if len(self._controlsPrefix)>0 else name
    192                  result[name] = var
    193
    194          return result
    195
    196 -    def start_progress(self, total = 100): pass
    197
    198 -    def update_progress(self): pass
    199
    200 -    def end_progress(self): pass
    201
    202
    203      #### Variable connected to the Storage manager of the corrent user
    204      @property
    205 -    def storage(self): return self._storage
    206
    207      @storage.setter
    208 -    def storage(self, value):
    209          self._storage = value
    210          for control in self.formControls.values(): control.storage = value
    211      #######################################################
    212
    213      #### This variable has the current http request #######
    214      @property
    215 -    def httpRequest(self): return self._httpRequest
    216
    217      @httpRequest.setter
    218 -    def httpRequest(self, value):
    219          from opencsp import AVAILABLE_STORAGES
    220          self.storage = AVAILABLE_STORAGES.get(value.user)
    221          self._httpRequest = value
    222          for control in self.formControls.values(): control.httpRequest = value
    223      #######################################################
    224
    225
    226      @property
    227 -    def form(self): return self._html
    228
    229      @property
    230 -    def js(self): return self._js
    231
    232
    233      @property
    234 -    def title(self): return self._title
    235
    236      @title.setter
    237 -    def title(self, value): self._title = value
    238