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