Add comment for each method and class
[bertos.git] / wizard / BModulePage.py
1 #!/usr/bin/env python
2 # encoding: utf-8
3 #
4 # Copyright 2009 Develer S.r.l. (http://www.develer.com/)
5 # All rights reserved.
6 #
7 # $Id:$
8 #
9 # Author: Lorenzo Berni <duplo@develer.com>
10 #
11
12 import os
13
14 from PyQt4.QtGui import *
15 from BWizardPage import *
16 import bertos_utils
17
18 from DefineException import *
19 from const import *
20
21 class BModulePage(BWizardPage):
22     """
23     Page of the wizard that permits to select and configurate the BeRTOS modules.
24     """
25     
26     def __init__(self):
27         BWizardPage.__init__(self, UI_LOCATION + "/module_select.ui")
28         self.setTitle(self.tr("Configure the BeRTOS modules"))
29         self._control_group = QControlGroup()
30         self._connectSignals()
31     
32     def reloadData(self):
33         """
34         Overload of the BWizardPage reloadData method.
35         """
36         QApplication.instance().setOverrideCursor(Qt.WaitCursor)
37         self._setupUi()
38         self._loadModuleData()
39         self._fillModuleTree()
40         QApplication.instance().restoreOverrideCursor()
41     
42     def _setupButtonGroup(self):
43         """
44         Sets up the button group.
45         """
46         self._button_group = QButtonGroup()
47         self._button_group.setExclusive(False)
48         self.connect(self._button_group, SIGNAL("buttonClicked(int)"), self._moduleSelectionChanged)
49     
50     def _loadModuleData(self):
51         """
52         Loads the module data.
53         """
54         ## Load the module data only if it isn't already loaded
55         if self._projectInfoRetrieve("MODULES") == None \
56                 and self._projectInfoRetrieve("LISTS") == None \
57                 and self._projectInfoRetrieve("CONFIGURATIONS") == None:
58             try:
59                 bertos_utils.loadModuleData(self._project())
60             except ModuleDefineException, e:
61                 self._exceptionOccurred(self.tr("Error parsing line '%2' in file %1").arg(e.path).arg(e.line))
62             except EnumDefineException, e:
63                 self._exceptionOccurred(self.tr("Error parsing line '%2' in file %1").arg(e.path).arg(e.line))
64             except ConfigurationDefineException, e:
65                 self._exceptionOccurred(self.tr("Error parsing line '%2' in file %1").arg(e.path).arg(e.line))
66     
67     def _fillModuleTree(self):
68         """
69         Fills the module tree with the module entries separated in categories.
70         """
71         modules = self._projectInfoRetrieve("MODULES")
72         if modules is None:
73             return
74         categories = {}
75         for module, information in modules.items():
76             if information["category"] not in categories.keys():
77                 categories[information["category"]] = []
78             categories[information["category"]].append(module)
79         for category, module_list in categories.items():
80             item = QTreeWidgetItem(QStringList([category]))
81             for module in module_list:
82                 enabled = modules[module]["enabled"]
83                 module_item = QTreeWidgetItem(item, QStringList([module]))
84                 if enabled:
85                     module_item.setCheckState(0, Qt.Checked)
86                 else:
87                     module_item.setCheckState(0, Qt.Unchecked)
88             self.pageContent.moduleTree.addTopLevelItem(item)
89         self.pageContent.moduleTree.sortItems(0, Qt.AscendingOrder)
90         
91     
92     def _fillPropertyTable(self):
93         """
94         Slot called when the user selects a module from the module tree.
95         Fills the property table using the configuration parameters defined in
96         the source tree.
97         """
98         module = self._currentModule()
99         if module is not None:
100             self._control_group.clear()
101             configuration = self._projectInfoRetrieve("MODULES")[module]["configuration"]
102             module_description = self._projectInfoRetrieve("MODULES")[module]["description"]
103             self.pageContent.moduleLabel.setText(module_description)
104             self.pageContent.moduleLabel.setVisible(True)
105             self.pageContent.propertyTable.clear()
106             self.pageContent.propertyTable.setRowCount(0)
107             if configuration != "":
108                 configurations = self._projectInfoRetrieve("CONFIGURATIONS")[configuration]
109                 param_list = sorted(configurations["paramlist"])
110                 index = 0
111                 for i, property in param_list:
112                     if "type" in configurations[property]["informations"] and configurations[property]["informations"]["type"] == "autoenabled":
113                         ## Doesn't show the hidden fields
114                         pass
115                     else:
116                         ## Set the row count to the current index + 1
117                         self.pageContent.propertyTable.setRowCount(index + 1)
118                         item = QTableWidgetItem(configurations[property]["brief"])
119                         item.setData(Qt.UserRole, qvariant_converter.convertString(property))
120                         self.pageContent.propertyTable.setItem(index, 0, item)
121                         if "type" in configurations[property]["informations"].keys() and configurations[property]["informations"]["type"] == "boolean":
122                             self._insertCheckBox(index, configurations[property]["value"])
123                         elif "type" in configurations[property]["informations"].keys() and configurations[property]["informations"]["type"] == "enum":
124                             self._insertComboBox(index, configurations[property]["value"], configurations[property]["informations"]["value_list"])
125                         elif "type" in configurations[property]["informations"] and configurations[property]["informations"]["type"] == "int":
126                             self._insertSpinBox(index, configurations[property]["value"], configurations[property]["informations"])
127                         else:
128                             # Not defined type, rendered as a text field
129                             self.pageContent.propertyTable.setItem(index, 1, QTableWidgetItem(configurations[property]["value"]))
130                         index += 1
131             if self.pageContent.propertyTable.rowCount() == 0:
132                 module_label = self.pageContent.moduleLabel.text()
133                 module_label += "\n\nNo configuration needed."
134                 self.pageContent.moduleLabel.setText(module_label)
135     
136     def _insertCheckBox(self, index, value):
137         """
138         Inserts in the table at index a checkbox for a boolean property setted
139         to value.
140         """
141         check_box = QCheckBox()
142         self.pageContent.propertyTable.setCellWidget(index, 1, check_box)
143         if value == "1":
144             check_box.setChecked(True)
145         else:
146             check_box.setChecked(False)
147         self._control_group.addControl(index, check_box)
148     
149     def _insertComboBox(self, index, value, value_list):
150         """
151         Inserts in the table at index a combobox for an enum property setted
152         to value.
153         """
154         try:
155             enum = self._projectInfoRetrieve("LISTS")[value_list]
156             combo_box = QComboBox()
157             self.pageContent.propertyTable.setCellWidget(index, 1, combo_box)
158             for i, element in enumerate(enum):
159                 combo_box.addItem(element)
160                 if element == value:
161                     combo_box.setCurrentIndex(i)
162             self._control_group.addControl(index, combo_box)
163         except KeyError:
164             self._exceptionOccurred(self.tr("Define list \"%1\" not found. Check definition files.").arg(value_list))
165             self.pageContent.propertyTable.setItem(index, 1, QTableWidgetItem(value))
166     
167     def _insertSpinBox(self, index, value, informations):
168         """
169         Inserts in the table at index a spinbox for an int, a long or an unsigned
170         long property setted to value.
171         """
172         ## int, long or undefined type property
173         spin_box = None
174         if bertos_utils.isLong(informations) or bertos_utils.isUnsignedLong(informations):
175             spin_box = QDoubleSpinBox()
176             spin_box.setDecimals(0)
177         else:
178             spin_box = QSpinBox()
179         self.pageContent.propertyTable.setCellWidget(index, 1, spin_box)
180         minimum = -32768
181         maximum = 32767
182         suff = ""
183         if bertos_utils.isLong(informations):
184             minimum = -2147483648
185             maximum = 2147483647
186             suff = "L"
187         elif bertos_utils.isUnsigned(informations):
188             minimum = 0
189             maximum = 65535
190             suff = "U"
191         elif bertos_utils.isUnsignedLong(informations):
192             minimum = 0
193             maximum = 4294967295
194             suff = "UL"
195         if "min" in informations.keys():
196             minimum = int(informations["min"])
197         if "max" in informations.keys():
198             maximum = int(informations["max"])
199         spin_box.setRange(minimum, maximum)
200         spin_box.setSuffix(suff)
201         spin_box.setValue(int(value.replace("L", "").replace("U", "")))
202         self._control_group.addControl(index, spin_box)
203         
204     
205     def _currentModule(self):
206         """
207         Retuns the current module name.
208         """
209         current_module = self.pageContent.moduleTree.currentItem()
210         # return only the child items
211         if current_module is not None and current_module.parent() is not None:
212             return unicode(current_module.text(0))
213         else:
214             return None
215     
216     def _currentModuleConfigurations(self):
217         """
218         Returns the current module configuration.
219         """
220         return self._configurations(self._currentModule())
221     
222     def _currentProperty(self):
223         """
224         Rerturns the current property from the property table.
225         """
226         return qvariant_converter.getString(self.pageContent.propertyTable.item(self.pageContent.propertyTable.currentRow(), 0).data(Qt.UserRole))
227     
228     def _currentPropertyItem(self):
229         """
230         Returns the QTableWidgetItem of the current property.
231         """
232         return self.pageContent.propertyTable.item(self.pageContent.propertyTable.currentRow(), 0)
233     
234     def _configurations(self, module):
235         """
236         Returns the configuration for the selected module.
237         """
238         configuration = self._projectInfoRetrieve("MODULES")[module]["configuration"]
239         if len(configuration) > 0:
240             return self._projectInfoRetrieve("CONFIGURATIONS")[configuration]
241         else:
242             return {}
243     
244     def _resetPropertyDescription(self):
245         """
246         Resets the label for each property table entry.
247         """
248         for index in range(self.pageContent.propertyTable.rowCount()):
249             property_name = qvariant_converter.getString(self.pageContent.propertyTable.item(index, 0).data(Qt.UserRole))
250             # Awful solution! Needed because if the user change the module, the selection changed...
251             if property_name not in self._currentModuleConfigurations().keys():
252                 break
253             self.pageContent.propertyTable.item(index, 0).setText(self._currentModuleConfigurations()[property_name]['brief'])
254     
255     def _showPropertyDescription(self):
256         """
257         Slot called when the property selection changes. Shows the description
258         of the selected property.
259         """
260         self._resetPropertyDescription()
261         configurations = self._currentModuleConfigurations()
262         if self._currentProperty() in configurations.keys():
263             description = configurations[self._currentProperty()]["brief"]
264             name = self._currentProperty()
265             self._currentPropertyItem().setText(description + "\n" + name)
266     
267     def _setupUi(self):
268         """
269         Set up the user interface.
270         """
271         self.pageContent.moduleTree.clear()
272         self.pageContent.moduleTree.setHeaderHidden(True)
273         self.pageContent.propertyTable.horizontalHeader().setResizeMode(QHeaderView.Stretch)
274         self.pageContent.propertyTable.horizontalHeader().setVisible(False)
275         self.pageContent.propertyTable.verticalHeader().setResizeMode(QHeaderView.ResizeToContents)
276         self.pageContent.propertyTable.verticalHeader().setVisible(False)
277         self.pageContent.propertyTable.setColumnCount(2)
278         self.pageContent.propertyTable.setRowCount(0)
279         self.pageContent.moduleLabel.setVisible(False)
280     
281     def _connectSignals(self):
282         """
283         Connect the signals with the related slots.
284         """
285         self.connect(self.pageContent.moduleTree, SIGNAL("itemPressed(QTreeWidgetItem*, int)"), self._fillPropertyTable)
286         self.connect(self.pageContent.moduleTree, SIGNAL("itemChanged(QTreeWidgetItem*, int)"), self._dependencyCheck)
287         self.connect(self.pageContent.propertyTable, SIGNAL("itemSelectionChanged()"), self._showPropertyDescription)
288         self.connect(self._control_group, SIGNAL("stateChanged"), self._saveValue)
289     
290     def _saveValue(self, index):
291         """
292         Slot called when the user modifies one of the configuration parameters.
293         It stores the new value."""
294         property = qvariant_converter.getString(self.pageContent.propertyTable.item(index, 0).data(Qt.UserRole))
295         configuration = self._projectInfoRetrieve("MODULES")[self._currentModule()]["configuration"]
296         configurations = self._projectInfoRetrieve("CONFIGURATIONS")
297         if "type" not in configurations[configuration][property]["informations"].keys() or configurations[configuration][property]["informations"]["type"] == "int":
298             configurations[configuration][property]["value"] = str(int(self.pageContent.propertyTable.cellWidget(index, 1).value()))
299         elif configurations[configuration][property]["informations"]["type"] == "enum":
300             configurations[configuration][property]["value"] = unicode(self.pageContent.propertyTable.cellWidget(index, 1).currentText())
301         elif configurations[configuration][property]["informations"]["type"] == "boolean":
302             if self.pageContent.propertyTable.cellWidget(index, 1).isChecked():
303                 configurations[configuration][property]["value"] = "1"
304             else:
305                 configurations[configuration][property]["value"] = "0"
306         self._projectInfoStore("CONFIGURATIONS", configurations)
307     
308     def _moduleSelectionChanged(self, index):
309         """
310         Slot called when the user selects or unselects a module from the module
311         tree.
312         """
313         module = unicode(self.pageContent.moduleTable.item(index, 1).text())
314         if self._button_group.button(index).isChecked():
315             self._moduleSelected(module)
316         else:
317             self._moduleUnselected(module)
318     
319     def _dependencyCheck(self, item):
320         """
321         Checks the dependencies of the module associated with the given item.
322         """
323         checked = False
324         module = unicode(item.text(0))
325         if item.checkState(0) == Qt.Checked:
326             self._moduleSelected(module)
327         else:
328             self._moduleUnselected(module)
329             self.removeFileDependencies(module)
330     
331     def _moduleSelected(self, selectedModule):
332         """
333         Resolves the selection dependencies.
334         """
335         modules = self._projectInfoRetrieve("MODULES")
336         modules[selectedModule]["enabled"] = True
337         self._projectInfoStore("MODULES", modules)
338         depends = self._projectInfoRetrieve("MODULES")[selectedModule]["depends"]
339         unsatisfied = []
340         if self.pageContent.automaticFix.isChecked():
341             unsatisfied = self.selectDependencyCheck(selectedModule)
342         if len(unsatisfied) > 0:
343             for module in unsatisfied:
344                 modules = self._projectInfoRetrieve("MODULES")
345                 modules[module]["enabled"] = True
346             for category in range(self.pageContent.moduleTree.topLevelItemCount()):
347                 item = self.pageContent.moduleTree.topLevelItem(category)
348                 for child in range(item.childCount()):
349                     if unicode(item.child(child).text(0)) in unsatisfied:
350                         item.child(child).setCheckState(0, Qt.Checked)
351     
352     def _moduleUnselected(self, unselectedModule):
353         """
354         Resolves the unselection dependencies.
355         """
356         modules = self._projectInfoRetrieve("MODULES")
357         modules[unselectedModule]["enabled"] = False
358         self._projectInfoStore("MODULES", modules)
359         unsatisfied = []
360         if self.pageContent.automaticFix.isChecked():
361             unsatisfied = self.unselectDependencyCheck(unselectedModule)
362         if len(unsatisfied) > 0:
363             message = self.tr("The module %1 is needed by the following modules:\n%2.\n\nDo you want to remove these modules too?")
364             message = message.arg(unselectedModule).arg(", ".join(unsatisfied))
365             choice = QMessageBox.warning(self, self.tr("Dependency error"), message, QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)
366             if choice == QMessageBox.Yes:
367                 for module in unsatisfied:
368                     modules = self._projectInfoRetrieve("MODULES")
369                     modules[module]["enabled"] = False
370                 for category in range(self.pageContent.moduleTree.topLevelItemCount()):
371                     item = self.pageContent.moduleTree.topLevelItem(category)
372                     for child in range(item.childCount()):
373                         if unicode(item.child(child).text(0)) in unsatisfied:
374                             item.child(child).setCheckState(0, Qt.Unchecked)
375     
376     def selectDependencyCheck(self, module):
377         """
378         Returns the list of unsatisfied dependencies after a selection.
379         """
380         unsatisfied = set()
381         modules = self._projectInfoRetrieve("MODULES")
382         files = self._projectInfoRetrieve("FILES")
383         for dependency in modules[module]["depends"]:
384             if dependency in modules and not modules[dependency]["enabled"]:
385                 unsatisfied |= set([dependency])
386                 if dependency not in unsatisfied:
387                     unsatisfied |= self.selectDependencyCheck(dependency)
388             if dependency not in modules:
389                 if dependency in files:
390                     files[dependency] += 1
391                 else:
392                     files[dependency] = 1
393         self._projectInfoStore("FILES", files)
394         return unsatisfied
395     
396     def unselectDependencyCheck(self, dependency):
397         """
398         Returns the list of unsatisfied dependencies after an unselection.
399         """
400         unsatisfied = set()
401         modules = self._projectInfoRetrieve("MODULES")
402         for module, informations in modules.items():
403             if dependency in informations["depends"] and informations["enabled"]:
404                 unsatisfied |= set([module])
405                 if dependency not in unsatisfied:
406                     unsatisfied |= self.unselectDependencyCheck(module)
407         return unsatisfied
408     
409     def removeFileDependencies(self, module):
410         """
411         Removes the files dependencies of the given module.
412         """
413         modules = self._projectInfoRetrieve("MODULES")
414         files = self._projectInfoRetrieve("FILES")
415         dependencies = modules[module]["depends"]
416         for dependency in dependencies:
417             if dependency in files:
418                 files[dependency] -= 1
419                 if files[dependency] == 0:
420                     del files[dependency]
421         self._projectInfoStore("FILES", files)
422
423 class QControlGroup(QObject):
424     """
425     Simple class that permit to connect different signals of different widgets
426     with a slot that emit a signal. Permits to group widget and to understand which of
427     them has sent the signal.
428     """
429     
430     def __init__(self):
431         QObject.__init__(self)
432         self._controls = {}
433     
434     def addControl(self, id, control):
435         """
436         Add a control.
437         """
438         self._controls[id] = control
439         if type(control) == QCheckBox:
440             self.connect(control, SIGNAL("stateChanged(int)"), lambda: self._stateChanged(id))
441         elif type(control) == QSpinBox:
442             self.connect(control, SIGNAL("valueChanged(int)"), lambda: self._stateChanged(id))
443         elif type(control) == QComboBox:
444             self.connect(control, SIGNAL("currentIndexChanged(int)"), lambda: self._stateChanged(id))
445         elif type(control) == QDoubleSpinBox:
446             self.connect(control, SIGNAL("valueChanged(double)"), lambda: self._stateChanged(id))
447     
448     def clear(self):
449         """
450         Remove all the controls.
451         """
452         self._controls = {}
453     
454     def _stateChanged(self, id):
455         """
456         Slot called when the value of one of the stored widget changes. It emits
457         another signal.
458         """
459         self.emit(SIGNAL("stateChanged"), id)