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