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