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