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