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