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