Remove an empty line
[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(configurations[property]["brief"])
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             # Awful solution! Needed because if the user change the module, the selection changed...
175             if propertyName not in self._currentModuleConfigurations().keys():
176                 break
177             self.pageContent.propertyTable.item(index, 0).setText(self._currentModuleConfigurations()[propertyName]['brief'])
178     
179     def _showPropertyDescription(self):
180         self._resetPropertyDescription()
181         configurations = self._currentModuleConfigurations()
182         if self._currentProperty() in configurations.keys():
183             description = configurations[self._currentProperty()]["brief"]
184             name = self._currentProperty()
185             self._currentPropertyItem().setText(description + "\n" + name)
186     
187     def _setupUi(self):
188         self.pageContent.moduleTable.horizontalHeader().setResizeMode(QHeaderView.ResizeToContents)
189         self.pageContent.moduleTable.horizontalHeader().setStretchLastSection(True)
190         self.pageContent.moduleTable.horizontalHeader().setVisible(False)
191         self.pageContent.moduleTable.verticalHeader().setResizeMode(QHeaderView.ResizeToContents)
192         self.pageContent.moduleTable.verticalHeader().setVisible(False)
193         self.pageContent.moduleTable.setColumnCount(2)
194         self.pageContent.moduleTable.setRowCount(0)
195         self.pageContent.propertyTable.horizontalHeader().setResizeMode(QHeaderView.Stretch)
196         self.pageContent.propertyTable.horizontalHeader().setVisible(False)
197         self.pageContent.propertyTable.verticalHeader().setResizeMode(QHeaderView.ResizeToContents)
198         self.pageContent.propertyTable.verticalHeader().setVisible(False)
199         self.pageContent.propertyTable.setColumnCount(2)
200         self.pageContent.propertyTable.setRowCount(0)
201         self.pageContent.moduleLabel.setVisible(False)
202     
203     def _connectSignals(self):
204         self.connect(self.pageContent.moduleTable, SIGNAL("itemSelectionChanged()"), self._fillPropertyTable)
205         self.connect(self.pageContent.propertyTable, SIGNAL("itemSelectionChanged()"), self._showPropertyDescription)
206         self.connect(self._controlGroup, SIGNAL("stateChanged"), self._saveValue)
207     
208     def _saveValue(self, index):
209         property = qvariant_converter.getString(self.pageContent.propertyTable.item(index, 0).data(Qt.UserRole))
210         configuration = self._projectInfoRetrieve("MODULES")[self._currentModule()]["configuration"]
211         configurations = self._projectInfoRetrieve("CONFIGURATIONS")
212         if "type" not in configurations[configuration][property]["informations"].keys() or configurations[configuration][property]["informations"]["type"] == "int":
213             configurations[configuration][property]["value"] = str(int(self.pageContent.propertyTable.cellWidget(index, 1).value()))
214         elif configurations[configuration][property]["informations"]["type"] == "enum":
215             configurations[configuration][property]["value"] = unicode(self.pageContent.propertyTable.cellWidget(index, 1).currentText())
216         elif configurations[configuration][property]["informations"]["type"] == "boolean":
217             if self.pageContent.propertyTable.cellWidget(index, 1).isChecked():
218                 configurations[configuration][property]["value"] = "1"
219             else:
220                 configurations[configuration][property]["value"] = "0"
221         self._projectInfoStore("CONFIGURATIONS", configurations)
222     
223     def _moduleSelectionChanged(self, index):
224         module = unicode(self.pageContent.moduleTable.item(index, 1).text())
225         if self._buttonGroup.button(index).isChecked():
226             self._moduleSelected(module)
227         else:
228             self._moduleUnselected(module)
229     
230     def _moduleSelected(self, selectedModule):
231         modules = self._projectInfoRetrieve("MODULES")
232         modules[selectedModule]["enabled"] = True
233         self._projectInfoStore("MODULES", modules)
234         depends = self._projectInfoRetrieve("MODULES")[selectedModule]["depends"]
235         unsatisfied = []
236         if self.pageContent.automaticFix.isChecked():
237             unsatisfied = self.selectDependencyCheck(selectedModule)
238         if len(unsatisfied) > 0:
239             for module in unsatisfied:
240                 modules = self._projectInfoRetrieve("MODULES")
241                 modules[module]["enabled"] = True
242             for index in range(self.pageContent.moduleTable.rowCount()):
243                 if unicode(self.pageContent.moduleTable.item(index, 1).text()) in unsatisfied:
244                     self._buttonGroup.button(index).setChecked(True)
245     
246     def _moduleUnselected(self, unselectedModule):
247         modules = self._projectInfoRetrieve("MODULES")
248         modules[unselectedModule]["enabled"] = False
249         self._projectInfoStore("MODULES", modules)
250         unsatisfied = []
251         if self.pageContent.automaticFix.isChecked():
252             unsatisfied = self.unselectDependencyCheck(unselectedModule)
253         if len(unsatisfied) > 0:
254             message = self.tr("The module %1 is needed by the following modules:\n%2.\n\nDo you want to resolve automatically the problem?")
255             message = message.arg(unselectedModule).arg(", ".join(unsatisfied))
256             choice = QMessageBox.warning(self, self.tr("Dependency error"), message, QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)
257             if choice == QMessageBox.Yes:
258                 for module in unsatisfied:
259                     modules = self._projectInfoRetrieve("MODULES")
260                     modules[module]["enabled"] = False
261                 for index in range(self.pageContent.moduleTable.rowCount()):
262                     if unicode(self.pageContent.moduleTable.item(index, 1).text()) in unsatisfied:
263                         self._buttonGroup.button(index).setChecked(False)
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)