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