Check the existance of the value_list, if it doesn't exist show an error message...
[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     def __init__(self):
24         BWizardPage.__init__(self, UI_LOCATION + "/module_select.ui")
25         self.setTitle(self.tr("Configure the BeRTOS modules"))
26         self._control_group = QControlGroup()
27         self._connectSignals()
28     
29     def reloadData(self):
30         self._setupUi()
31         self._loadModuleData()
32         self._fillModuleTree()
33     
34     def _setupButtonGroup(self):
35         self._button_group = QButtonGroup()
36         self._button_group.setExclusive(False)
37         self.connect(self._button_group, SIGNAL("buttonClicked(int)"), self._moduleSelectionChanged)
38     
39     def _loadModuleData(self):
40         ## Load the module data only if it isn't already loaded
41         if self._projectInfoRetrieve("MODULES") == None \
42                 and self._projectInfoRetrieve("LISTS") == None \
43                 and self._projectInfoRetrieve("CONFIGURATIONS") == None:
44             try:
45                 bertos_utils.loadModuleData(self._project())
46             except ModuleDefineException, e:
47                 self._exceptionOccurred(self.tr("Error parsing line '%2' in file %1").arg(e.path).arg(e.line))
48             except EnumDefineException, e:
49                 self._exceptionOccurred(self.tr("Error parsing line '%2' in file %1").arg(e.path).arg(e.line))
50             except ConfigurationDefineException, e:
51                 self._exceptionOccurred(self.tr("Error parsing line '%2' in file %1").arg(e.path).arg(e.line))
52     
53     def _fillModuleTree(self):
54         modules = self._projectInfoRetrieve("MODULES")
55         if modules is None:
56             return
57         categories = {}
58         for module, information in modules.items():
59             if information["category"] not in categories.keys():
60                 categories[information["category"]] = []
61             categories[information["category"]].append(module)
62         for category, module_list in categories.items():
63             item = QTreeWidgetItem(QStringList([category]))
64             for module in module_list:
65                 enabled = modules[module]["enabled"]
66                 module_item = QTreeWidgetItem(item, QStringList([module]))
67                 if enabled:
68                     module_item.setCheckState(0, Qt.Checked)
69                 else:
70                     module_item.setCheckState(0, Qt.Unchecked)
71             self.pageContent.moduleTree.addTopLevelItem(item)
72         self.pageContent.moduleTree.sortItems(0, Qt.AscendingOrder)
73         
74     
75     def _fillPropertyTable(self):
76         module = self._currentModule()
77         if module is not None:
78             self._control_group.clear()
79             configuration = self._projectInfoRetrieve("MODULES")[module]["configuration"]
80             module_description = self._projectInfoRetrieve("MODULES")[module]["description"]
81             self.pageContent.moduleLabel.setText(module_description)
82             self.pageContent.moduleLabel.setVisible(True)
83             self.pageContent.propertyTable.clear()
84             self.pageContent.propertyTable.setRowCount(0)
85             if configuration != "":
86                 configurations = self._projectInfoRetrieve("CONFIGURATIONS")[configuration]
87                 param_list = sorted(configurations["paramlist"])
88                 index = 0
89                 for i, property in param_list:
90                     if "type" in configurations[property]["informations"] and configurations[property]["informations"]["type"] == "autoenabled":
91                         ## Doesn't show the hidden fields
92                         pass
93                     else:
94                         ## Set the row count to the current index + 1
95                         self.pageContent.propertyTable.setRowCount(index + 1)
96                         item = QTableWidgetItem(configurations[property]["brief"])
97                         item.setData(Qt.UserRole, qvariant_converter.convertString(property))
98                         self.pageContent.propertyTable.setItem(index, 0, item)
99                         if "type" in configurations[property]["informations"].keys() and configurations[property]["informations"]["type"] == "boolean":
100                             self._insertCheckBox(index, configurations[property]["value"])
101                         elif "type" in configurations[property]["informations"].keys() and configurations[property]["informations"]["type"] == "enum":
102                             self._insertComboBox(index, configurations[property]["value"], configurations[property]["informations"]["value_list"])
103                         elif "type" in configurations[property]["informations"] and configurations[property]["informations"]["type"] == "int":
104                             self._insertSpinBox(index, configurations[property]["value"], configurations[property]["informations"])
105                         else:
106                             # Not defined type, rendered as a text field
107                             self.pageContent.propertyTable.setItem(index, 1, QTableWidgetItem(configurations[property]["value"]))
108                         index += 1
109             if self.pageContent.propertyTable.rowCount() == 0:
110                 module_label = self.pageContent.moduleLabel.text()
111                 module_label += "\n\nNo configuration needed."
112                 self.pageContent.moduleLabel.setText(module_label)
113     
114     def _insertCheckBox(self, index, value):
115         ## boolean property
116         check_box = QCheckBox()
117         self.pageContent.propertyTable.setCellWidget(index, 1, check_box)
118         if value == "1":
119             check_box.setChecked(True)
120         else:
121             check_box.setChecked(False)
122         self._control_group.addControl(index, check_box)
123     
124     def _insertComboBox(self, index, value, value_list):
125         ## enum property
126         try:
127             enum = self._projectInfoRetrieve("LISTS")[value_list]
128             combo_box = QComboBox()
129             self.pageContent.propertyTable.setCellWidget(index, 1, combo_box)
130             for i, element in enumerate(enum):
131                 combo_box.addItem(element)
132                 if element == value:
133                     combo_box.setCurrentIndex(i)
134             self._control_group.addControl(index, combo_box)
135         except KeyError:
136             self._exceptionOccurred(self.tr("Define list \"%1\" not found. Check definition files.").arg(value_list))
137             self.pageContent.propertyTable.setItem(index, 1, QTableWidgetItem(value))
138     
139     def _insertSpinBox(self, index, value, informations):
140         ## int, long or undefined type property
141         spin_box = None
142         if bertos_utils.isLong(informations) or bertos_utils.isUnsignedLong(informations):
143             spin_box = QDoubleSpinBox()
144             spin_box.setDecimals(0)
145         else:
146             spin_box = QSpinBox()
147         self.pageContent.propertyTable.setCellWidget(index, 1, spin_box)
148         minimum = -32768
149         maximum = 32767
150         suff = ""
151         if bertos_utils.isLong(informations):
152             minimum = -2147483648
153             maximum = 2147483647
154             suff = "L"
155         elif bertos_utils.isUnsigned(informations):
156             minimum = 0
157             maximum = 65535
158             suff = "U"
159         elif bertos_utils.isUnsignedLong(informations):
160             minimum = 0
161             maximum = 4294967295
162             suff = "UL"
163         if "min" in informations.keys():
164             minimum = int(informations["min"])
165         if "max" in informations.keys():
166             maximum = int(informations["max"])
167         spin_box.setRange(minimum, maximum)
168         spin_box.setSuffix(suff)
169         spin_box.setValue(int(value.replace("L", "").replace("U", "")))
170         self._control_group.addControl(index, spin_box)
171         
172     
173     def _currentModule(self):
174         current_module = self.pageContent.moduleTree.currentItem()
175         # return only the child items
176         if current_module is not None and current_module.parent() is not None:
177             return unicode(current_module.text(0))
178         else:
179             return None
180     
181     def _currentModuleConfigurations(self):
182         return self._configurations(self._currentModule())
183     
184     def _currentProperty(self):
185         return qvariant_converter.getString(self.pageContent.propertyTable.item(self.pageContent.propertyTable.currentRow(), 0).data(Qt.UserRole))
186     
187     def _currentPropertyItem(self):
188         return self.pageContent.propertyTable.item(self.pageContent.propertyTable.currentRow(), 0)
189     
190     def _configurations(self, module):
191         configuration = self._projectInfoRetrieve("MODULES")[module]["configuration"]
192         if len(configuration) > 0:
193             return self._projectInfoRetrieve("CONFIGURATIONS")[configuration]
194         else:
195             return {}
196     
197     def _resetPropertyDescription(self):
198         for index in range(self.pageContent.propertyTable.rowCount()):
199             property_name = qvariant_converter.getString(self.pageContent.propertyTable.item(index, 0).data(Qt.UserRole))
200             # Awful solution! Needed because if the user change the module, the selection changed...
201             if property_name not in self._currentModuleConfigurations().keys():
202                 break
203             self.pageContent.propertyTable.item(index, 0).setText(self._currentModuleConfigurations()[property_name]['brief'])
204     
205     def _showPropertyDescription(self):
206         self._resetPropertyDescription()
207         configurations = self._currentModuleConfigurations()
208         if self._currentProperty() in configurations.keys():
209             description = configurations[self._currentProperty()]["brief"]
210             name = self._currentProperty()
211             self._currentPropertyItem().setText(description + "\n" + name)
212     
213     def _setupUi(self):
214         self.pageContent.moduleTree.clear()
215         self.pageContent.moduleTree.setHeaderHidden(True)
216         self.pageContent.propertyTable.horizontalHeader().setResizeMode(QHeaderView.Stretch)
217         self.pageContent.propertyTable.horizontalHeader().setVisible(False)
218         self.pageContent.propertyTable.verticalHeader().setResizeMode(QHeaderView.ResizeToContents)
219         self.pageContent.propertyTable.verticalHeader().setVisible(False)
220         self.pageContent.propertyTable.setColumnCount(2)
221         self.pageContent.propertyTable.setRowCount(0)
222         self.pageContent.moduleLabel.setVisible(False)
223     
224     def _connectSignals(self):
225         self.connect(self.pageContent.moduleTree, SIGNAL("itemPressed(QTreeWidgetItem*, int)"), self._fillPropertyTable)
226         self.connect(self.pageContent.moduleTree, SIGNAL("itemChanged(QTreeWidgetItem*, int)"), self._dependencyCheck)
227         self.connect(self.pageContent.propertyTable, SIGNAL("itemSelectionChanged()"), self._showPropertyDescription)
228         self.connect(self._control_group, SIGNAL("stateChanged"), self._saveValue)
229     
230     def _saveValue(self, index):
231         property = qvariant_converter.getString(self.pageContent.propertyTable.item(index, 0).data(Qt.UserRole))
232         configuration = self._projectInfoRetrieve("MODULES")[self._currentModule()]["configuration"]
233         configurations = self._projectInfoRetrieve("CONFIGURATIONS")
234         if "type" not in configurations[configuration][property]["informations"].keys() or configurations[configuration][property]["informations"]["type"] == "int":
235             configurations[configuration][property]["value"] = str(int(self.pageContent.propertyTable.cellWidget(index, 1).value()))
236         elif configurations[configuration][property]["informations"]["type"] == "enum":
237             configurations[configuration][property]["value"] = unicode(self.pageContent.propertyTable.cellWidget(index, 1).currentText())
238         elif configurations[configuration][property]["informations"]["type"] == "boolean":
239             if self.pageContent.propertyTable.cellWidget(index, 1).isChecked():
240                 configurations[configuration][property]["value"] = "1"
241             else:
242                 configurations[configuration][property]["value"] = "0"
243         self._projectInfoStore("CONFIGURATIONS", configurations)
244     
245     def _moduleSelectionChanged(self, index):
246         module = unicode(self.pageContent.moduleTable.item(index, 1).text())
247         if self._button_group.button(index).isChecked():
248             self._moduleSelected(module)
249         else:
250             self._moduleUnselected(module)
251     
252     def _dependencyCheck(self, item):
253         checked = False
254         module = unicode(item.text(0))
255         if item.checkState(0) == Qt.Checked:
256             self._moduleSelected(module)
257         else:
258             self._moduleUnselected(module)
259             self.removeFileDependencies(module)
260     
261     def _moduleSelected(self, selectedModule):
262         modules = self._projectInfoRetrieve("MODULES")
263         modules[selectedModule]["enabled"] = True
264         self._projectInfoStore("MODULES", modules)
265         depends = self._projectInfoRetrieve("MODULES")[selectedModule]["depends"]
266         unsatisfied = []
267         if self.pageContent.automaticFix.isChecked():
268             unsatisfied = self.selectDependencyCheck(selectedModule)
269         if len(unsatisfied) > 0:
270             for module in unsatisfied:
271                 modules = self._projectInfoRetrieve("MODULES")
272                 modules[module]["enabled"] = True
273             for category in range(self.pageContent.moduleTree.topLevelItemCount()):
274                 item = self.pageContent.moduleTree.topLevelItem(category)
275                 for child in range(item.childCount()):
276                     if unicode(item.child(child).text(0)) in unsatisfied:
277                         item.child(child).setCheckState(0, Qt.Checked)
278     
279     def _moduleUnselected(self, unselectedModule):
280         modules = self._projectInfoRetrieve("MODULES")
281         modules[unselectedModule]["enabled"] = False
282         self._projectInfoStore("MODULES", modules)
283         unsatisfied = []
284         if self.pageContent.automaticFix.isChecked():
285             unsatisfied = self.unselectDependencyCheck(unselectedModule)
286         if len(unsatisfied) > 0:
287             message = self.tr("The module %1 is needed by the following modules:\n%2.\n\nDo you want to remove these modules too?")
288             message = message.arg(unselectedModule).arg(", ".join(unsatisfied))
289             choice = QMessageBox.warning(self, self.tr("Dependency error"), message, QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)
290             if choice == QMessageBox.Yes:
291                 for module in unsatisfied:
292                     modules = self._projectInfoRetrieve("MODULES")
293                     modules[module]["enabled"] = False
294                 for category in range(self.pageContent.moduleTree.topLevelItemCount()):
295                     item = self.pageContent.moduleTree.topLevelItem(category)
296                     for child in range(item.childCount()):
297                         if unicode(item.child(child).text(0)) in unsatisfied:
298                             item.child(child).setCheckState(0, Qt.Unchecked)
299     
300     def selectDependencyCheck(self, module):
301         unsatisfied = set()
302         modules = self._projectInfoRetrieve("MODULES")
303         files = self._projectInfoRetrieve("FILES")
304         for dependency in modules[module]["depends"]:
305             if dependency in modules and not modules[dependency]["enabled"]:
306                 unsatisfied |= set([dependency])
307                 if dependency not in unsatisfied:
308                     unsatisfied |= self.selectDependencyCheck(dependency)
309             if dependency not in modules:
310                 if dependency in files:
311                     files[dependency] += 1
312                 else:
313                     files[dependency] = 1
314         self._projectInfoStore("FILES", files)
315         return unsatisfied
316     
317     def unselectDependencyCheck(self, dependency):
318         unsatisfied = set()
319         modules = self._projectInfoRetrieve("MODULES")
320         for module, informations in modules.items():
321             if dependency in informations["depends"] and informations["enabled"]:
322                 unsatisfied |= set([module])
323                 if dependency not in unsatisfied:
324                     unsatisfied |= self.unselectDependencyCheck(module)
325         return unsatisfied
326     
327     def removeFileDependencies(self, module):
328         modules = self._projectInfoRetrieve("MODULES")
329         files = self._projectInfoRetrieve("FILES")
330         dependencies = modules[module]["depends"]
331         for dependency in dependencies:
332             if dependency in files:
333                 files[dependency] -= 1
334                 if files[dependency] == 0:
335                     del files[dependency]
336         self._projectInfoStore("FILES", files)
337
338 class QControlGroup(QObject):
339     def __init__(self):
340         QObject.__init__(self)
341         self._controls = {}
342     
343     def addControl(self, id, control):
344         self._controls[id] = control
345         if type(control) == QCheckBox:
346             self.connect(control, SIGNAL("stateChanged(int)"), lambda: self._stateChanged(id))
347         elif type(control) == QSpinBox:
348             self.connect(control, SIGNAL("valueChanged(int)"), lambda: self._stateChanged(id))
349         elif type(control) == QComboBox:
350             self.connect(control, SIGNAL("currentIndexChanged(int)"), lambda: self._stateChanged(id))
351         elif type(control) == QDoubleSpinBox:
352             self.connect(control, SIGNAL("valueChanged(double)"), lambda: self._stateChanged(id))
353     
354     def clear(self):
355         self._controls = {}
356     
357     def _stateChanged(self, id):
358         self.emit(SIGNAL("stateChanged"), id)