Correct a problema about the empty configurations
[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._controlGroup = QControlGroup()
27         self._connectSignals()
28     
29     def reloadData(self):
30         self._setupUi()
31         self._setupButtonGroup()
32         self._loadModuleData()
33         self._fillModuleTable()
34     
35     def _setupButtonGroup(self):
36         self._buttonGroup = QButtonGroup()
37         self._buttonGroup.setExclusive(False)
38         self.connect(self._buttonGroup, SIGNAL("buttonClicked(int)"), self._moduleSelectionChanged)
39     
40     def _loadModuleData(self):
41         try:
42             modules = bertos_utils.loadModuleInfosDict(self._projectInfoRetrieve("SOURCES_PATH"))
43             lists = bertos_utils.loadDefineListsDict(self._projectInfoRetrieve("SOURCES_PATH"))
44             configurations = {}
45             for module, informations in modules.items():
46                 if len(informations["configuration"]) > 0:
47                     configurations[informations["configuration"]] = bertos_utils.loadConfigurationInfos(self._projectInfoRetrieve("SOURCES_PATH") +
48                                                                                                         "/" + informations["configuration"])
49         except ModuleDefineException, e:
50             self._exceptionOccurred(self.tr("Error parsing module information in file %1").arg(e.parameter))
51         except EnumDefineException, e:
52             self._exceptionOccurred(self.tr("Error parsing enum informations in file %1").arg(e.parameter))
53         except ConfigurationDefineException, e:
54             self._exceptionOccurred(self.tr("Error parsing configuration informations in file %1").arg(e.parameter))
55         else:
56             self._projectInfoStore("MODULES", modules)
57             self._projectInfoStore("LISTS", lists)
58             self._projectInfoStore("CONFIGURATIONS", configurations)
59     
60     def _fillModuleTable(self):
61         modules = self._projectInfoRetrieve("MODULES")
62         if modules is None:
63             return
64         self.pageContent.moduleTable.setRowCount(len(modules))
65         for index, module in enumerate(modules):
66             self.pageContent.moduleTable.setItem(index, 1, QTableWidgetItem(module))
67             checkBox = QCheckBox()
68             self._buttonGroup.addButton(checkBox, index)
69             self.pageContent.moduleTable.setCellWidget(index, 0, checkBox)
70             checkBox.setChecked(modules[module]["enabled"])
71     
72     def _fillPropertyTable(self):
73         module = self._currentModule()
74         if module is not None:
75             self._controlGroup.clear()
76             configuration = self._projectInfoRetrieve("MODULES")[module]["configuration"]
77             moduleDescription = self._projectInfoRetrieve("MODULES")[module]["description"]
78             self.pageContent.moduleLabel.setText(moduleDescription)
79             self.pageContent.moduleLabel.setVisible(True)
80             self.pageContent.propertyTable.clear()
81             if len(configuration) > 0:
82                 configurations = self._projectInfoRetrieve("CONFIGURATIONS")[configuration]
83                 self.pageContent.propertyTable.setRowCount(len(configurations))
84                 for index, property in enumerate(configurations):
85                     item = QTableWidgetItem(property)
86                     item.setData(Qt.UserRole, qvariant_converter.convertString(property))
87                     self.pageContent.propertyTable.setItem(index, 0, item)
88                     if "type" in configurations[property]["informations"].keys() and configurations[property]["informations"]["type"] == "boolean":
89                         self._insertCheckBox(index, configurations[property]["value"])
90                     elif "type" in configurations[property]["informations"].keys() and configurations[property]["informations"]["type"] == "enum":
91                         self._insertComboBox(index, configurations[property]["value"], configurations[property]["informations"]["value_list"])
92                     elif "type" in configurations[property]["informations"] and configurations[property]["informations"]["type"] == "int":
93                         self._insertSpinBox(index, configurations[property]["value"], configurations[property]["informations"])
94                     else:
95                         # Not defined type, rendered as a text field
96                         self.pageContent.propertyTable.setItem(index, 1, QTableWidgetItem(property))
97             else:
98                 self.pageContent.propertyTable.setRowCount(0)
99     
100     def _insertCheckBox(self, index, value):
101         ## boolean property
102         checkBox = QCheckBox()
103         self.pageContent.propertyTable.setCellWidget(index, 1, checkBox)
104         if value == "1":
105             checkBox.setChecked(True)
106         else:
107             checkBox.setChecked(False)
108         self._controlGroup.addControl(index, checkBox)
109     
110     def _insertComboBox(self, index, value, value_list):
111         ## enum property
112         comboBox = QComboBox()
113         self.pageContent.propertyTable.setCellWidget(index, 1, comboBox)
114         enum = self._projectInfoRetrieve("LISTS")[value_list]
115         for i, element in enumerate(enum):
116             comboBox.addItem(element)
117             if element == value:
118                 comboBox.setCurrentIndex(i)
119         self._controlGroup.addControl(index, comboBox)
120     
121     def _insertSpinBox(self, index, value, informations):
122         ## int, long or undefined type property
123         spinBox = None
124         if bertos_utils.isLong(informations) or bertos_utils.isUnsignedLong(informations):
125             spinBox = QDoubleSpinBox()
126             spinBox.setDecimals(0)
127         else:
128             spinBox = QSpinBox()
129         self.pageContent.propertyTable.setCellWidget(index, 1, spinBox)
130         minimum = -32768
131         maximum = 32767
132         suff = ""
133         if bertos_utils.isLong(informations):
134             minimum = -2147483648
135             maximum = 2147483647
136             suff = "L"
137         elif bertos_utils.isUnsigned(informations):
138             minimum = 0
139             maximum = 65535
140             suff = "U"
141         elif bertos_utils.isUnsignedLong(informations):
142             minimum = 0
143             maximum = 4294967295
144             suff = "UL"
145         if "min" in informations.keys():
146             minimum = int(informations["min"])
147         if "max" in informations.keys():
148             maximum = int(informations["max"])
149         spinBox.setRange(minimum, maximum)
150         spinBox.setSuffix(suff)
151         spinBox.setValue(int(value.replace("L", "").replace("U", "")))
152         self._controlGroup.addControl(index, spinBox)
153         
154     
155     def _currentModule(self):
156         currentModule = self.pageContent.moduleTable.item(self.pageContent.moduleTable.currentRow(), 1)
157         if currentModule is not None:
158             return unicode(currentModule.text())
159         else:
160             return None
161     
162     def _currentModuleConfigurations(self):
163         return self._configurations(self._currentModule())
164     
165     def _currentProperty(self):
166         return qvariant_converter.getString(self.pageContent.propertyTable.item(self.pageContent.propertyTable.currentRow(), 0).data(Qt.UserRole))
167     
168     def _currentPropertyItem(self):
169         return self.pageContent.propertyTable.item(self.pageContent.propertyTable.currentRow(), 0)
170     
171     def _module(self, row):
172         return unicode(self.pageContent.moduleTable.item(row, 1).text())
173     
174     def _configurations(self, module):
175         configuration = self._projectInfoRetrieve("MODULES")[module]["configuration"]
176         if len(configuration) > 0:
177             return self._projectInfoRetrieve("CONFIGURATIONS")[configuration]
178         else:
179             return {}
180     
181     def _resetPropertyDescription(self):
182         for index in range(self.pageContent.propertyTable.rowCount()):
183             propertyName = qvariant_converter.getString(self.pageContent.propertyTable.item(index, 0).data(Qt.UserRole))
184             self.pageContent.propertyTable.item(index, 0).setText(propertyName)
185     
186     def _showPropertyDescription(self):
187         self._resetPropertyDescription()
188         configurations = self._currentModuleConfigurations()
189         if self._currentProperty() in configurations.keys():
190             description = configurations[self._currentProperty()]["description"]
191             name = self._currentProperty()
192             self._currentPropertyItem().setText(name + "\n" + description)
193     
194     def _setupUi(self):
195         self.pageContent.moduleTable.horizontalHeader().setResizeMode(QHeaderView.ResizeToContents)
196         self.pageContent.moduleTable.horizontalHeader().setStretchLastSection(True)
197         self.pageContent.moduleTable.horizontalHeader().setVisible(False)
198         self.pageContent.moduleTable.verticalHeader().setResizeMode(QHeaderView.ResizeToContents)
199         self.pageContent.moduleTable.verticalHeader().setVisible(False)
200         self.pageContent.moduleTable.setColumnCount(2)
201         self.pageContent.moduleTable.setRowCount(0)
202         self.pageContent.propertyTable.horizontalHeader().setResizeMode(QHeaderView.Stretch)
203         self.pageContent.propertyTable.horizontalHeader().setVisible(False)
204         self.pageContent.propertyTable.verticalHeader().setResizeMode(QHeaderView.ResizeToContents)
205         self.pageContent.propertyTable.verticalHeader().setVisible(False)
206         self.pageContent.propertyTable.setColumnCount(2)
207         self.pageContent.propertyTable.setRowCount(0)
208         self.pageContent.moduleLabel.setVisible(False)
209     
210     def _connectSignals(self):
211         self.connect(self.pageContent.moduleTable, SIGNAL("itemSelectionChanged()"), self._fillPropertyTable)
212         self.connect(self.pageContent.propertyTable, SIGNAL("itemSelectionChanged()"), self._showPropertyDescription)
213         self.connect(self._controlGroup, SIGNAL("stateChanged"), self._saveValue)
214     
215     def _saveValue(self, index):
216         property = qvariant_converter.getString(self.pageContent.propertyTable.item(index, 0).data(Qt.UserRole))
217         configuration = self._projectInfoRetrieve("MODULES")[self._currentModule()]["configuration"]
218         configurations = self._projectInfoRetrieve("CONFIGURATIONS")
219         if "type" not in configurations[configuration][property]["informations"].keys() or configurations[configuration][property]["informations"]["type"] == "int":
220             configurations[configuration][property]["value"] = str(int(self.pageContent.propertyTable.cellWidget(index, 1).value()))
221         elif configurations[configuration][property]["informations"]["type"] == "enum":
222             configurations[configuration][property]["value"] = unicode(self.pageContent.propertyTable.cellWidget(index, 1).currentText())
223         elif configurations[configuration][property]["informations"]["type"] == "boolean":
224             if self.pageContent.propertyTable.cellWidget(index, 1).isChecked():
225                 configurations[configuration][property]["value"] = "1"
226             else:
227                 configurations[configuration][property]["value"] = "0"
228         self._projectInfoStore("CONFIGURATIONS", configurations)
229     
230     def _moduleSelectionChanged(self, index):
231         module = unicode(self.pageContent.moduleTable.item(index, 1).text())
232         if self._buttonGroup.button(index).isChecked():
233             self._moduleSelected(module)
234         else:
235             self._moduleUnselected(module)
236     
237     def _moduleSelected(self, selectedModule):
238         modules = self._projectInfoRetrieve("MODULES")
239         modules[selectedModule]["enabled"] = True
240         self._projectInfoStore("MODULES", modules)
241         depends = self._projectInfoRetrieve("MODULES")[selectedModule]["depends"]
242         unsatisfied = self.selectDependencyCheck(selectedModule)
243         if len(unsatisfied) > 0:
244             message = self.tr("The module %1 needs the following modules:\n%2.\n\nDo you want to resolve automatically the problem?")
245             message = message.arg(selectedModule).arg(", ".join(unsatisfied))
246             choice = QMessageBox.warning(self, self.tr("Dependency error"), message, QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)
247             if choice == QMessageBox.Yes:
248                 for module in unsatisfied:
249                     modules = self._projectInfoRetrieve("MODULES")
250                     modules[module]["enabled"] = True
251                 for index in range(self.pageContent.moduleTable.rowCount()):
252                     if unicode(self.pageContent.moduleTable.item(index, 1).text()) in unsatisfied:
253                         self._buttonGroup.button(index).setChecked(True)
254     
255     def _moduleUnselected(self, unselectedModule):
256         modules = self._projectInfoRetrieve("MODULES")
257         modules[unselectedModule]["enabled"] = False
258         self._projectInfoStore("MODULES", modules)
259         unsatisfied = self.unselectDependencyCheck(unselectedModule)
260         if len(unsatisfied) > 0:
261             message = self.tr("The module %1 is needed by the following modules:\n%2.\n\nDo you want to resolve automatically the problem?")
262             message = message.arg(unselectedModule).arg(", ".join(unsatisfied))
263             choice = QMessageBox.warning(self, self.tr("Dependency error"), message, QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)
264             if choice == QMessageBox.Yes:
265                 for module in unsatisfied:
266                     modules = self._projectInfoRetrieve("MODULES")
267                     modules[module]["enabled"] = False
268                 for index in range(self.pageContent.moduleTable.rowCount()):
269                     if unicode(self.pageContent.moduleTable.item(index, 1).text()) in unsatisfied:
270                         self._buttonGroup.button(index).setChecked(False)
271     
272     
273     def selectDependencyCheck(self, module):
274         unsatisfied = set()
275         modules = self._projectInfoRetrieve("MODULES")
276         for dependency in modules[module]["depends"]:
277             if not modules[dependency]["enabled"]:
278                 unsatisfied |= set([dependency])
279                 if dependency not in unsatisfied:
280                     unsatisfied |= self.selectDependencyCheck(dependency)
281         return unsatisfied
282     
283     def unselectDependencyCheck(self, dependency):
284         unsatisfied = set()
285         modules = self._projectInfoRetrieve("MODULES")
286         for module, informations in modules.items():
287             if dependency in informations["depends"] and informations["enabled"]:
288                 unsatisfied |= set([module])
289                 if dependency not in unsatisfied:
290                     unsatisfied |= self.unselectDependencyCheck(module)
291         return unsatisfied
292
293 class QControlGroup(QObject):
294     def __init__(self):
295         QObject.__init__(self)
296         self._controls = {}
297     
298     def addControl(self, id, control):
299         self._controls[id] = control
300         if type(control) == QCheckBox:
301             self.connect(control, SIGNAL("stateChanged(int)"), lambda: self._stateChanged(id))
302         elif type(control) == QSpinBox:
303             self.connect(control, SIGNAL("valueChanged(int)"), lambda: self._stateChanged(id))
304         elif type(control) == QComboBox:
305             self.connect(control, SIGNAL("currentIndexChanged(int)"), lambda: self._stateChanged(id))
306         elif type(control) == QDoubleSpinBox:
307             self.connect(control, SIGNAL("valueChanged(double)"), lambda: self._stateChanged(id))
308     
309     def clear(self):
310         self._controls = {}
311     
312     def _stateChanged(self, id):
313         self.emit(SIGNAL("stateChanged"), id)