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