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