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

# Source Code for Module pyforms.gui.BaseWidget

      1  #!/usr/bin/python
      2  # -*- coding: utf-8 -*-
      3  '''
      4  @author: Ricardo Ribeiro
      5  @credits: Ricardo Ribeiro
      6  @license: MIT
      7  @version: 0.0
      8  @maintainer: Ricardo Ribeiro
      9  @email: ricardojvr@gmail.com
     10  @status: Development
     11  @lastEditedBy: Carlos Mão de Ferro (carlos.maodeferro@neuro.fchampalimaud.org)
     12  '''
     13
     14  from pyforms.gui.Controls.ControlBase       import ControlBase
     15  from pyforms.gui.Controls.ControlProgress   import ControlProgress
     16  import os, json, subprocess, time
     17  from datetime import datetime, timedelta
     18  from PyQt4 import QtGui, QtCore
     19  from pyforms import conf
     20
     21
     22 -class BaseWidget(QtGui.QWidget):
     23      """
     24      The class implements the most basic widget or window.
     25      """
     26
     27 -    def __init__(self, title='Untitled'):
     28          QtGui.QWidget.__init__(self)
     29          layout = QtGui.QVBoxLayout()
     30          self.setLayout(layout)
     31          self.layout().setMargin(0)
     32
     33          self.title = title
     34
     35          self._mainmenu = []
     36          self._splitters = []
     37          self._tabs = []
     38          self._formset = None
     39          self._formLoaded = False
     40
     41
     42
     43      ##########################################################################
     44      ############ Module functions  ###########################################
     45      ##########################################################################
     46
     47
     48
     49 -    def initForm(self):
     50          """
     51          Generate the module Form
     52          """
     53          if not self._formLoaded:
     54
     55              if conf.PYFORMS_MODE in ['GUI-OPENCSP']:
     56                  self._progress = ControlProgress("Progress", 0, 100)
     57                  if self._formset != None: self._formset += ['_progress']
     58
     59              if self._formset is not None:
     60                  control = self.generatePanel(self._formset)
     61                  self.layout().addWidget(control)
     62              else:
     63                  allparams = self.formControls
     64                  for key, param in allparams.items():
     65                      param.parent = self
     66                      param.name = key
     67                      self.layout().addWidget(param.form)
     68              self._formLoaded = True
     69
     70 -    def generateTabs(self, formsetDict):
     71          """
     72          Generate QTabWidget for the module form
     73          @param formset: Tab form configuration
     74          @type formset: dict
     75          """
     76          tabs = QtGui.QTabWidget(self)
     77          for key, item in sorted(formsetDict.items()):
     78              ctrl = self.generatePanel(item)
     79              tabs.addTab(ctrl, key[key.find(':') + 1:])
     80          return tabs
     81
     82 -    def generatePanel(self, formset):
     83          """
     84          Generate a panel for the module form with all the controls
     85          formset format example: [('_video', '_arenas', '_run'), {"Player":['_threshold', "_player", "=", "_results", "_query"], "Background image":[(' ', '_selectBackground', '_paintBackground'), '_image']}, "_progress"]
     86          tuple: will display the controls in the same horizontal line
     87          list: will display the controls in the same vertical line
     88          dict: will display the controls in a tab widget
     89          '||': will plit the controls in a horizontal line
     90          '=': will plit the controls in a vertical line
     91          @param formset: Form configuration
     92          @type formset: list
     93          """
     94          control = None
     95          if '=' in formset:
     96              control = QtGui.QSplitter(QtCore.Qt.Vertical)
     97              tmp = list(formset)
     98              index = tmp.index('=')
     99              firstPanel = self.generatePanel(formset[0:index])
    100              secondPanel = self.generatePanel(formset[index + 1:])
    101              control.addWidget(firstPanel)
    102              control.addWidget(secondPanel)
    103              self._splitters.append(control)
    104              return control
    105          elif '||' in formset:
    106              control = QtGui.QSplitter(QtCore.Qt.Horizontal)
    107              tmp = list(formset)
    108              rindex = lindex = index = tmp.index('||')
    109              rindex -= 1
    110              rindex += 2
    111              if isinstance(formset[lindex - 1], int):
    112                  lindex = lindex - 1
    113              if len(formset) > rindex and isinstance(formset[index + 1], int):
    114                  rindex += 1
    115              firstPanel = self.generatePanel(formset[0:lindex])
    116              secondPanel = self.generatePanel(formset[rindex:])
    117              if isinstance(formset[index - 1], int):
    118                  firstPanel.setMaximumWidth(formset[index - 1])
    119              if isinstance(formset[index + 1], int):
    120                  secondPanel.setMaximumWidth(formset[index + 1])
    121              control.addWidget(firstPanel)
    122              control.addWidget(secondPanel)
    123              self._splitters.append(control)
    124              return control
    125          control = QtGui.QWidget()
    126          layout = None
    127          if type(formset) is tuple:
    128              layout = QtGui.QHBoxLayout()
    129              for row in formset:
    130                  if isinstance(row, (list, tuple)):
    131                      panel = self.generatePanel(row)
    132                      layout.addWidget(panel)
    133                  elif row == " ":
    134                      spacer = QtGui.QSpacerItem(
    135                          40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
    136                      layout.addItem(spacer)
    137                  elif type(row) is dict:
    138                      c = self.generateTabs(row)
    139                      layout.addWidget(c)
    140                      self._tabs.append(c)
    141                  else:
    142                      param = self.formControls.get(row, None)
    143                      if param is None:
    144                          label = QtGui.QLabel()
    145                          label.setSizePolicy(
    146                              QtGui.QSizePolicy.Maximum, QtGui.QSizePolicy.Maximum)
    147                          #layout.addWidget( label )
    148
    149                          if row.startswith('info:'):
    150                              label.setText(row[5:])
    151                              font = QtGui.QFont()
    152                              font.setPointSize(10)
    153                              label.setFont(font)
    154                          elif row.startswith('h1:'):
    155                              label.setText(row[3:])
    156                              font = QtGui.QFont()
    157                              font.setPointSize(17)
    158                              font.setBold(True)
    159                              label.setFont(font)
    160                          elif row.startswith('h2:'):
    161                              label.setText(row[3:])
    162                              font = QtGui.QFont()
    163                              font.setPointSize(16)
    164                              font.setBold(True)
    165                              label.setFont(font)
    166                          elif row.startswith('h3:'):
    167                              label.setText(row[3:])
    168                              font = QtGui.QFont()
    169                              font.setPointSize(15)
    170                              font.setBold(True)
    171                              label.setFont(font)
    172                          elif row.startswith('h4:'):
    173                              label.setText(row[3:])
    174                              font = QtGui.QFont()
    175                              font.setPointSize(14)
    176                              font.setBold(True)
    177                              label.setFont(font)
    178                          elif row.startswith('h5:'):
    179                              label.setText(row[3:])
    180                              font = QtGui.QFont()
    181                              font.setPointSize(12)
    182                              font.setBold(True)
    183                              label.setFont(font)
    184                          else:
    185                              label.setText(row)
    186                              font = QtGui.QFont()
    187                              font.setPointSize(10)
    188                              label.setFont(font)
    189
    190                          layout.addWidget(label)
    191                      else:
    192                          param.parent = self
    193                          param.name = row
    194                          layout.addWidget(param.form)
    195          elif type(formset) is list:
    196              layout = QtGui.QVBoxLayout()
    197              for row in formset:
    198                  if isinstance(row, (list, tuple)):
    199                      panel = self.generatePanel(row)
    200                      layout.addWidget(panel)
    201                  elif row == " ":
    202                      spacer = QtGui.QSpacerItem(
    203                          20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)
    204                      layout.addItem(spacer)
    205                  elif type(row) is dict:
    206                      c = self.generateTabs(row)
    207                      layout.addWidget(c)
    208                      self._tabs.append(c)
    209                  else:
    210                      param = self.formControls.get(row, None)
    211                      if param is None:
    212                          label = QtGui.QLabel()
    213                          label.setSizePolicy(
    214                              QtGui.QSizePolicy.Maximum, QtGui.QSizePolicy.Maximum)
    215                          label.resize(30, 30)
    216                          #layout.addWidget( label )
    217
    218                          if row.startswith('info:'):
    219                              label.setText(row[5:])
    220                              font = QtGui.QFont()
    221                              font.setPointSize(10)
    222                              label.setFont(font)
    223                          elif row.startswith('h1:'):
    224                              label.setText(row[3:])
    225                              font = QtGui.QFont()
    226                              font.setPointSize(17)
    227                              font.setBold(True)
    228                              label.setFont(font)
    229                          elif row.startswith('h2:'):
    230                              label.setText(row[3:])
    231                              font = QtGui.QFont()
    232                              font.setPointSize(16)
    233                              font.setBold(True)
    234                              label.setFont(font)
    235                          elif row.startswith('h3:'):
    236                              label.setText(row[3:])
    237                              font = QtGui.QFont()
    238                              font.setPointSize(15)
    239                              font.setBold(True)
    240                              label.setFont(font)
    241                          elif row.startswith('h4:'):
    242                              label.setText(row[3:])
    243                              font = QtGui.QFont()
    244                              font.setPointSize(14)
    245                              font.setBold(True)
    246                              label.setFont(font)
    247                          elif row.startswith('h5:'):
    248                              label.setText(row[3:])
    249                              font = QtGui.QFont()
    250                              font.setPointSize(12)
    251                              font.setBold(True)
    252                              label.setFont(font)
    253                          else:
    254                              label.setText(row)
    255                              font = QtGui.QFont()
    256                              font.setPointSize(10)
    257                              label.setFont(font)
    258
    259                          layout.addWidget(label)
    260                      else:
    261                          param.parent = self
    262                          param.name = row
    263                          layout.addWidget(param.form)
    264          layout.setMargin(0)
    265          control.setLayout(layout)
    266          return control
    267
    268      ##########################################################################
    269      ############ Parent class functions reemplementation #####################
    270      ##########################################################################
    271
    272 -    def show(self):
    273          """
    274          It shows the
    275          """
    276          self.initForm()
    277          super(BaseWidget, self).show()
    278
    279      ##########################################################################
    280      ############ Properties ##################################################
    281      ##########################################################################
    282
    283      @property
    284 -    def formControls(self):
    285          """
    286          Return all the form controls from the the module
    287          """
    288          result = {}
    289          for name, var in vars(self).items():
    290              if isinstance(var, ControlBase):
    291                  result[name] = var
    292          return result
    293
    294 -    def start_progress(self, total=100):
    295          self._progress.max = total
    296          self._progress.min = 0
    297          self._progress.value = 0
    298          self._processing_count = 0
    299          self._processing_initial_time = time.time()
    300
    301 -    def update_progress(self, progress=1):
    302          self._progress.value = self._processing_count
    303          self._processing_count += progress
    304
    305          div = int(self._progress.max / 400)
    306          if div == 0:
    307              div = 1
    308          if (self._processing_count % div) == 0:
    309              self._processing_last_time = time.time()
    310              total_passed_time = self._processing_last_time - \
    311                  self._processing_initial_time
    312              remaining_time = (
    313                  (self._progress.max * total_passed_time) / self._processing_count) - total_passed_time
    314              time_remaining = datetime(
    315                  1, 1, 1) + timedelta(seconds=remaining_time)
    316              time_elapsed = datetime(
    317                  1, 1, 1) + timedelta(seconds=(total_passed_time))
    318
    319              values = (time_elapsed.day - 1, time_elapsed.hour, time_elapsed.minute, time_elapsed.second,
    320                        time_remaining.day -
    321                        1, time_remaining.hour, time_remaining.minute, time_remaining.second,
    322                        (float(self._processing_count) / float(self._progress.max)
    323                         ) * 100.0, self._processing_count, self._progress.max,
    324                        self._processing_count / total_passed_time)
    325              self._progress.label = "Elapsed: %d:%d:%d:%d; Remaining: %d:%d:%d:%d; Processed %0.2f %%  (%d/%d); Cicles per second: %0.3f" % values
    326
    327          QtGui.QApplication.processEvents()
    328
    329 -    def end_progress(self):
    330          # self.update_progress()
    331          self._progress.value = self._progress.max
    332
    333 -    def executeCommand(self, cmd, cwd=None):
    334          if cwd is not None:
    335              currentdirectory = os.getcwd()
    336              os.chdir(cwd)
    337          proc = subprocess.Popen(
    338              cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    339          (output, error) = proc.communicate()
    340          if cwd is not None:
    341              os.chdir(currentdirectory)
    342          if error:
    343              print('Error: ' + error)
    344          return output
    345
    346      @property
    347 -    def form(self): return self
    348
    349      @property
    350 -    def title(self): return self.windowTitle()
    351
    352      @title.setter
    353 -    def title(self, value): self.setWindowTitle(value)
    354
    355      @property
    356 -    def mainmenu(self): return self._mainmenu
    357
    358      @mainmenu.setter
    359 -    def mainmenu(self, value): self._mainmenu = value
    360
    361
    362 -    def save(self, data):
    363          allparams = self.formControls
    364          for name, param in allparams.items():
    365              data[name] = {}
    366              param.save(data[name])
    367
    368 -    def saveWindow(self):
    369          allparams = self.formControls
    370          data = {}
    371          self.save(data)
    372
    373          filename = QtGui.QFileDialog.getSaveFileName(self, 'Select file')
    374
    375          with open(filename, 'w') as output_file:
    376              json.dump(data, output_file)
    377
    378 -    def loadWindowData(self, filename):
    379          with open(filename, 'r') as pkl_file:
    380              project_data = json.load(pkl_file)
    381          data = dict(project_data)
    382          self.load(data)
    383
    384 -    def load(self, data):
    385          allparams = self.formControls
    386          for name, param in allparams.items():
    387              if name in data:
    388                  param.load(data[name])
    389          self.initForm()
    390
    391 -    def loadWindow(self):
    392          filename = QtGui.QFileDialog.getOpenFileNames(self, 'Select file')
    393          self.loadWindowData(str(filename[0]))
    394