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