Correct typo
[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(self.project(), module=module)
83             except SupportedException, e:
84                 self.exceptionOccurred(self.tr("Error evaluating \"%1\" for module %2").arg(e.support_string).arg(module))
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                         continue
108                     try:
109                         param_supported = bertos_utils.isSupported(self.project(), property_id=(configuration, property))
110                     except SupportedException, e:
111                         self.exceptionOccurred(self.tr("Error evaluating \"%1\" for module %2").arg(e.support_string).arg(selectedModule))
112                         param_supported = True
113                     if not param_supported:
114                         # Doesn't show the unsupported parameters
115                         continue
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"] and configurations[property]["informations"]["type"] == "boolean":
122                         self.insertCheckBox(index, configurations[property]["value"])
123                     elif "type" in configurations[property]["informations"] 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 dependencyCheck(self, item):
137         """
138         Checks the dependencies of the module associated with the given item.
139         """
140         checked = False
141         module = unicode(item.text(0))
142         if item.checkState(0) == Qt.Checked:
143             self.moduleSelected(module)
144         else:
145             self.moduleUnselected(module)
146             self.removeFileDependencies(module)
147
148     def showPropertyDescription(self):
149         """
150         Slot called when the property selection changes. Shows the description
151         of the selected property.
152         """
153         self.resetPropertyDescription()
154         configurations = self.currentModuleConfigurations()
155         if self.currentProperty() in configurations:
156             description = configurations[self.currentProperty()]["brief"]
157             name = self.currentProperty()
158             self.currentPropertyItem().setText(description + "\n" + name)
159
160     def saveValue(self, index):
161         """
162         Slot called when the user modifies one of the configuration parameters.
163         It stores the new value."""
164         property = qvariant_converter.getString(self.pageContent.propertyTable.item(index, 0).data(Qt.UserRole))
165         configuration = self.projectInfo("MODULES")[self.currentModule()]["configuration"]
166         configurations = self.projectInfo("CONFIGURATIONS")
167         if "type" not in configurations[configuration][property]["informations"] or configurations[configuration][property]["informations"]["type"] == "int":
168             configurations[configuration][property]["value"] = str(int(self.pageContent.propertyTable.cellWidget(index, 1).value()))
169         elif configurations[configuration][property]["informations"]["type"] == "enum":
170             configurations[configuration][property]["value"] = unicode(self.pageContent.propertyTable.cellWidget(index, 1).currentText())
171         elif configurations[configuration][property]["informations"]["type"] == "boolean":
172             if self.pageContent.propertyTable.cellWidget(index, 1).isChecked():
173                 configurations[configuration][property]["value"] = "1"
174             else:
175                 configurations[configuration][property]["value"] = "0"
176         self.setProjectInfo("CONFIGURATIONS", configurations)
177
178     ####
179     
180     def loadModuleData(self):
181         """
182         Loads the module data.
183         """
184         # Load the module data only if it isn't already loaded
185         if self.projectInfo("MODULES") == None \
186                 and self.projectInfo("LISTS") == None \
187                 and self.projectInfo("CONFIGURATIONS") == None:
188             try:
189                 bertos_utils.loadModuleData(self.project())
190             except ModuleDefineException, e:
191                 self.exceptionOccurred(self.tr("Error parsing line '%2' in file %1").arg(e.path).arg(e.line))
192             except EnumDefineException, e:
193                 self.exceptionOccurred(self.tr("Error parsing line '%2' in file %1").arg(e.path).arg(e.line))
194             except ConfigurationDefineException, e:
195                 self.exceptionOccurred(self.tr("Error parsing line '%2' in file %1").arg(e.path).arg(e.line))
196     
197     def fillModuleTree(self):
198         """
199         Fills the module tree with the module entries separated in categories.
200         """
201         modules = self.projectInfo("MODULES")
202         if modules is None:
203             return
204         categories = {}
205         for module, information in modules.items():
206             if information["category"] not in categories:
207                 categories[information["category"]] = []
208             categories[information["category"]].append(module)
209         for category, module_list in categories.items():
210             item = QTreeWidgetItem(QStringList([category]))
211             for module in module_list:
212                 enabled = modules[module]["enabled"]
213                 module_item = QTreeWidgetItem(item, QStringList([module]))
214                 try:
215                     supported = bertos_utils.isSupported(self.project(), module=module)
216                 except SupportedException, e:
217                     self.exceptionOccurred(self.tr("Error evaluating \"%1\" for module %2").arg(e.support_string).arg(selectedModule))
218                     supported = True
219                 if not supported:
220                     module_item.setForeground(0, QBrush(QColor(Qt.red)))
221                 if enabled:
222                     module_item.setCheckState(0, Qt.Checked)
223                 else:
224                     module_item.setCheckState(0, Qt.Unchecked)
225             self.pageContent.moduleTree.addTopLevelItem(item)
226         self.pageContent.moduleTree.sortItems(0, Qt.AscendingOrder)
227             
228     def insertCheckBox(self, index, value):
229         """
230         Inserts in the table at index a checkbox for a boolean property setted
231         to value.
232         """
233         check_box = QCheckBox()
234         self.pageContent.propertyTable.setCellWidget(index, 1, check_box)
235         if value == "1":
236             check_box.setChecked(True)
237         else:
238             check_box.setChecked(False)
239         self._control_group.addControl(index, check_box)
240     
241     def insertComboBox(self, index, value, value_list):
242         """
243         Inserts in the table at index a combobox for an enum property setted
244         to value.
245         """
246         try:
247             enum = self.projectInfo("LISTS")[value_list]
248             combo_box = QComboBox()
249             self.pageContent.propertyTable.setCellWidget(index, 1, combo_box)
250             for i, element in enumerate(enum):
251                 combo_box.addItem(element)
252                 if element == value:
253                     combo_box.setCurrentIndex(i)
254             self._control_group.addControl(index, combo_box)
255         except KeyError:
256             self.exceptionOccurred(self.tr("Define list \"%1\" not found. Check definition files.").arg(value_list))
257             self.pageContent.propertyTable.setItem(index, 1, QTableWidgetItem(value))
258     
259     def insertSpinBox(self, index, value, informations):
260         """
261         Inserts in the table at index a spinbox for an int, a long or an unsigned
262         long property setted to value.
263         """
264         # int, long or undefined type property
265         spin_box = None
266         if bertos_utils.isLong(informations) or bertos_utils.isUnsignedLong(informations):
267             spin_box = QDoubleSpinBox()
268             spin_box.setDecimals(0)
269         else:
270             spin_box = QSpinBox()
271         self.pageContent.propertyTable.setCellWidget(index, 1, spin_box)
272         minimum = -32768
273         maximum = 32767
274         suff = ""
275         if bertos_utils.isLong(informations):
276             minimum = -2147483648
277             maximum = 2147483647
278             suff = "L"
279         elif bertos_utils.isUnsigned(informations):
280             minimum = 0
281             maximum = 65535
282             suff = "U"
283         elif bertos_utils.isUnsignedLong(informations):
284             minimum = 0
285             maximum = 4294967295
286             suff = "UL"
287         if "min" in informations:
288             minimum = int(informations["min"])
289         if "max" in informations:
290             maximum = int(informations["max"])
291         spin_box.setRange(minimum, maximum)
292         spin_box.setSuffix(suff)
293         spin_box.setValue(int(value.replace("L", "").replace("U", "")))
294         self._control_group.addControl(index, spin_box)
295         
296     
297     def currentModule(self):
298         """
299         Retuns the current module name.
300         """
301         current_module = self.pageContent.moduleTree.currentItem()
302         # return only the child items
303         if current_module is not None and current_module.parent() is not None:
304             return unicode(current_module.text(0))
305         else:
306             return None
307     
308     def currentModuleConfigurations(self):
309         """
310         Returns the current module configuration.
311         """
312         return self.configurations(self.currentModule())
313     
314     def currentProperty(self):
315         """
316         Rerturns the current property from the property table.
317         """
318         return qvariant_converter.getString(self.pageContent.propertyTable.item(self.pageContent.propertyTable.currentRow(), 0).data(Qt.UserRole))
319     
320     def currentPropertyItem(self):
321         """
322         Returns the QTableWidgetItem of the current property.
323         """
324         return self.pageContent.propertyTable.item(self.pageContent.propertyTable.currentRow(), 0)
325     
326     def configurations(self, module):
327         """
328         Returns the configuration for the selected module.
329         """
330         configuration = self.projectInfo("MODULES")[module]["configuration"]
331         if len(configuration) > 0:
332             return self.projectInfo("CONFIGURATIONS")[configuration]
333         else:
334             return {}
335     
336     def resetPropertyDescription(self):
337         """
338         Resets the label for each property table entry.
339         """
340         for index in range(self.pageContent.propertyTable.rowCount()):
341             property_name = qvariant_converter.getString(self.pageContent.propertyTable.item(index, 0).data(Qt.UserRole))
342             # Awful solution! Needed because if the user change the module, the selection changed...
343             if property_name not in self.currentModuleConfigurations():
344                 break
345             self.pageContent.propertyTable.item(index, 0).setText(self.currentModuleConfigurations()[property_name]['brief'])
346     
347     def moduleSelected(self, selectedModule):
348         """
349         Resolves the selection dependencies.
350         """
351         modules = self.projectInfo("MODULES")
352         modules[selectedModule]["enabled"] = True
353         self.setProjectInfo("MODULES", modules)
354         depends = self.projectInfo("MODULES")[selectedModule]["depends"]
355         unsatisfied = []
356         if self.pageContent.automaticFix.isChecked():
357             unsatisfied = self.selectDependencyCheck(selectedModule)
358         if len(unsatisfied) > 0:
359             for module in unsatisfied:
360                 modules = self.projectInfo("MODULES")
361                 modules[module]["enabled"] = True
362             for category in range(self.pageContent.moduleTree.topLevelItemCount()):
363                 item = self.pageContent.moduleTree.topLevelItem(category)
364                 for child in range(item.childCount()):
365                     if unicode(item.child(child).text(0)) in unsatisfied:
366                         item.child(child).setCheckState(0, Qt.Checked)
367     
368     def moduleUnselected(self, unselectedModule):
369         """
370         Resolves the unselection dependencies.
371         """
372         modules = self.projectInfo("MODULES")
373         modules[unselectedModule]["enabled"] = False
374         self.setProjectInfo("MODULES", modules)
375         unsatisfied = []
376         if self.pageContent.automaticFix.isChecked():
377             unsatisfied = self.unselectDependencyCheck(unselectedModule)
378         if len(unsatisfied) > 0:
379             message = self.tr("The module %1 is needed by the following modules:\n%2.\n\nDo you want to remove these modules too?")
380             message = message.arg(unselectedModule).arg(", ".join(unsatisfied))
381             choice = QMessageBox.warning(self, self.tr("Dependency error"), message, QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)
382             if choice == QMessageBox.Yes:
383                 for module in unsatisfied:
384                     modules = self.projectInfo("MODULES")
385                     modules[module]["enabled"] = False
386                 for category in range(self.pageContent.moduleTree.topLevelItemCount()):
387                     item = self.pageContent.moduleTree.topLevelItem(category)
388                     for child in range(item.childCount()):
389                         if unicode(item.child(child).text(0)) in unsatisfied:
390                             item.child(child).setCheckState(0, Qt.Unchecked)
391     
392     def selectDependencyCheck(self, module):
393         """
394         Returns the list of unsatisfied dependencies after a selection.
395         """
396         unsatisfied = set()
397         modules = self.projectInfo("MODULES")
398         files = self.projectInfo("FILES")
399         for dependency in modules[module]["depends"]:
400             if dependency in modules and not modules[dependency]["enabled"]:
401                 unsatisfied |= set([dependency])
402                 if dependency not in unsatisfied:
403                     unsatisfied |= self.selectDependencyCheck(dependency)
404             if dependency not in modules:
405                 if dependency in files:
406                     files[dependency] += 1
407                 else:
408                     files[dependency] = 1
409         self.setProjectInfo("FILES", files)
410         return unsatisfied
411     
412     def unselectDependencyCheck(self, dependency):
413         """
414         Returns the list of unsatisfied dependencies after an unselection.
415         """
416         unsatisfied = set()
417         modules = self.projectInfo("MODULES")
418         for module, informations in modules.items():
419             if dependency in informations["depends"] and informations["enabled"]:
420                 unsatisfied |= set([module])
421                 if dependency not in unsatisfied:
422                     unsatisfied |= self.unselectDependencyCheck(module)
423         return unsatisfied
424     
425     def removeFileDependencies(self, module):
426         """
427         Removes the files dependencies of the given module.
428         """
429         modules = self.projectInfo("MODULES")
430         files = self.projectInfo("FILES")
431         dependencies = modules[module]["depends"]
432         for dependency in dependencies:
433             if dependency in files:
434                 files[dependency] -= 1
435                 if files[dependency] == 0:
436                     del files[dependency]
437         self.setProjectInfo("FILES", files)
438
439 class QControlGroup(QObject):
440     """
441     Simple class that permit to connect different signals of different widgets
442     with a slot that emit a signal. Permits to group widget and to understand which of
443     them has sent the signal.
444     """
445     
446     def __init__(self):
447         QObject.__init__(self)
448         self._controls = {}
449     
450     def addControl(self, id, control):
451         """
452         Add a control.
453         """
454         self._controls[id] = control
455         if type(control) == QCheckBox:
456             self.connect(control, SIGNAL("stateChanged(int)"), lambda: self.stateChanged(id))
457         elif type(control) == QSpinBox:
458             self.connect(control, SIGNAL("valueChanged(int)"), lambda: self.stateChanged(id))
459         elif type(control) == QComboBox:
460             self.connect(control, SIGNAL("currentIndexChanged(int)"), lambda: self.stateChanged(id))
461         elif type(control) == QDoubleSpinBox:
462             self.connect(control, SIGNAL("valueChanged(double)"), lambda: self.stateChanged(id))
463     
464     def clear(self):
465         """
466         Remove all the controls.
467         """
468         self._controls = {}
469     
470     def stateChanged(self, id):
471         """
472         Slot called when the value of one of the stored widget changes. It emits
473         another signal.
474         """
475         self.emit(SIGNAL("stateChanged"), id)