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