Divide into categories the modules in the module selection page
[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._loadModuleData()
32         self._fillModuleTree()
33     
34     def _setupButtonGroup(self):
35         self._buttonGroup = QButtonGroup()
36         self._buttonGroup.setExclusive(False)
37         self.connect(self._buttonGroup, SIGNAL("buttonClicked(int)"), self._moduleSelectionChanged)
38     
39     def _loadModuleData(self):
40         try:
41             bertos_utils.loadModuleData(self._project())
42         except ModuleDefineException, e:
43             self._exceptionOccurred(self.tr("Error parsing line '%2' in file %1").arg(e.path).arg(e.line))
44         except EnumDefineException, e:
45             self._exceptionOccurred(self.tr("Error parsing line '%2' in file %1").arg(e.path).arg(e.line))
46         except ConfigurationDefineException, e:
47             self._exceptionOccurred(self.tr("Error parsing line '%2' in file %1").arg(e.path).arg(e.line))
48     
49     def _fillModuleTree(self):
50         modules = self._projectInfoRetrieve("MODULES")
51         if modules is None:
52             return
53         categories = {}
54         for module, information in modules.items():
55             if information["category"] not in categories.keys():
56                 categories[information["category"]] = []
57             categories[information["category"]].append(module)
58         for category, modules in categories.items():
59             item = QTreeWidgetItem(QStringList([category]))
60             for module in modules:
61                 moduleItem = QTreeWidgetItem(item, QStringList([module]))
62                 moduleItem.setCheckState(0, Qt.Unchecked)
63             self.pageContent.moduleTree.addTopLevelItem(item)
64         
65     
66     def _fillPropertyTable(self):
67         module = self._currentModule()
68         if module is not None:
69             self._controlGroup.clear()
70             configuration = self._projectInfoRetrieve("MODULES")[module]["configuration"]
71             moduleDescription = self._projectInfoRetrieve("MODULES")[module]["description"]
72             self.pageContent.moduleLabel.setText(moduleDescription)
73             self.pageContent.moduleLabel.setVisible(True)
74             self.pageContent.propertyTable.clear()
75             if len(configuration) > 0:
76                 configurations = self._projectInfoRetrieve("CONFIGURATIONS")[configuration]
77                 self.pageContent.propertyTable.setRowCount(len(configurations))
78                 for index, property in enumerate(configurations):
79                     item = QTableWidgetItem(configurations[property]["brief"])
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                         self._insertCheckBox(index, configurations[property]["value"])
84                     elif "type" in configurations[property]["informations"].keys() and configurations[property]["informations"]["type"] == "enum":
85                         self._insertComboBox(index, configurations[property]["value"], configurations[property]["informations"]["value_list"])
86                     elif "type" in configurations[property]["informations"] and configurations[property]["informations"]["type"] == "int":
87                         self._insertSpinBox(index, configurations[property]["value"], configurations[property]["informations"])
88                     else:
89                         # Not defined type, rendered as a text field
90                         self.pageContent.propertyTable.setItem(index, 1, QTableWidgetItem(property))
91             else:
92                 self.pageContent.propertyTable.setRowCount(0)
93     
94     def _insertCheckBox(self, index, value):
95         ## boolean property
96         checkBox = QCheckBox()
97         self.pageContent.propertyTable.setCellWidget(index, 1, checkBox)
98         if value == "1":
99             checkBox.setChecked(True)
100         else:
101             checkBox.setChecked(False)
102         self._controlGroup.addControl(index, checkBox)
103     
104     def _insertComboBox(self, index, value, value_list):
105         ## enum property
106         comboBox = QComboBox()
107         self.pageContent.propertyTable.setCellWidget(index, 1, comboBox)
108         enum = self._projectInfoRetrieve("LISTS")[value_list]
109         for i, element in enumerate(enum):
110             comboBox.addItem(element)
111             if element == value:
112                 comboBox.setCurrentIndex(i)
113         self._controlGroup.addControl(index, comboBox)
114     
115     def _insertSpinBox(self, index, value, informations):
116         ## int, long or undefined type property
117         spinBox = None
118         if bertos_utils.isLong(informations) or bertos_utils.isUnsignedLong(informations):
119             spinBox = QDoubleSpinBox()
120             spinBox.setDecimals(0)
121         else:
122             spinBox = QSpinBox()
123         self.pageContent.propertyTable.setCellWidget(index, 1, spinBox)
124         minimum = -32768
125         maximum = 32767
126         suff = ""
127         if bertos_utils.isLong(informations):
128             minimum = -2147483648
129             maximum = 2147483647
130             suff = "L"
131         elif bertos_utils.isUnsigned(informations):
132             minimum = 0
133             maximum = 65535
134             suff = "U"
135         elif bertos_utils.isUnsignedLong(informations):
136             minimum = 0
137             maximum = 4294967295
138             suff = "UL"
139         if "min" in informations.keys():
140             minimum = int(informations["min"])
141         if "max" in informations.keys():
142             maximum = int(informations["max"])
143         spinBox.setRange(minimum, maximum)
144         spinBox.setSuffix(suff)
145         spinBox.setValue(int(value.replace("L", "").replace("U", "")))
146         self._controlGroup.addControl(index, spinBox)
147         
148     
149     def _currentModule(self):
150         currentModule = self.pageContent.moduleTree.currentItem()
151         # return only the child items
152         if currentModule is not None and currentModule.parent() is not None:
153             return unicode(currentModule.text(0))
154         else:
155             return None
156     
157     def _currentModuleConfigurations(self):
158         return self._configurations(self._currentModule())
159     
160     def _currentProperty(self):
161         return qvariant_converter.getString(self.pageContent.propertyTable.item(self.pageContent.propertyTable.currentRow(), 0).data(Qt.UserRole))
162     
163     def _currentPropertyItem(self):
164         return self.pageContent.propertyTable.item(self.pageContent.propertyTable.currentRow(), 0)
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             # Awful solution! Needed because if the user change the module, the selection changed...
177             if propertyName not in self._currentModuleConfigurations().keys():
178                 break
179             self.pageContent.propertyTable.item(index, 0).setText(self._currentModuleConfigurations()[propertyName]['brief'])
180     
181     def _showPropertyDescription(self):
182         self._resetPropertyDescription()
183         configurations = self._currentModuleConfigurations()
184         if self._currentProperty() in configurations.keys():
185             description = configurations[self._currentProperty()]["brief"]
186             name = self._currentProperty()
187             self._currentPropertyItem().setText(description + "\n" + name)
188     
189     def _setupUi(self):
190         self.pageContent.moduleTree.setHeaderHidden(True)
191         self.pageContent.propertyTable.horizontalHeader().setResizeMode(QHeaderView.Stretch)
192         self.pageContent.propertyTable.horizontalHeader().setVisible(False)
193         self.pageContent.propertyTable.verticalHeader().setResizeMode(QHeaderView.ResizeToContents)
194         self.pageContent.propertyTable.verticalHeader().setVisible(False)
195         self.pageContent.propertyTable.setColumnCount(2)
196         self.pageContent.propertyTable.setRowCount(0)
197         self.pageContent.moduleLabel.setVisible(False)
198     
199     def _connectSignals(self):
200         self.connect(self.pageContent.moduleTree, SIGNAL("itemPressed(QTreeWidgetItem*, int)"), self._fillPropertyTable)
201         self.connect(self.pageContent.moduleTree, SIGNAL("itemChanged(QTreeWidgetItem*, int)"), self._dependencyCheck)
202         self.connect(self.pageContent.propertyTable, SIGNAL("itemSelectionChanged()"), self._showPropertyDescription)
203         self.connect(self._controlGroup, SIGNAL("stateChanged"), self._saveValue)
204     
205     def _saveValue(self, index):
206         property = qvariant_converter.getString(self.pageContent.propertyTable.item(index, 0).data(Qt.UserRole))
207         configuration = self._projectInfoRetrieve("MODULES")[self._currentModule()]["configuration"]
208         configurations = self._projectInfoRetrieve("CONFIGURATIONS")
209         if "type" not in configurations[configuration][property]["informations"].keys() or configurations[configuration][property]["informations"]["type"] == "int":
210             configurations[configuration][property]["value"] = str(int(self.pageContent.propertyTable.cellWidget(index, 1).value()))
211         elif configurations[configuration][property]["informations"]["type"] == "enum":
212             configurations[configuration][property]["value"] = unicode(self.pageContent.propertyTable.cellWidget(index, 1).currentText())
213         elif configurations[configuration][property]["informations"]["type"] == "boolean":
214             if self.pageContent.propertyTable.cellWidget(index, 1).isChecked():
215                 configurations[configuration][property]["value"] = "1"
216             else:
217                 configurations[configuration][property]["value"] = "0"
218         self._projectInfoStore("CONFIGURATIONS", configurations)
219     
220     def _moduleSelectionChanged(self, index):
221         module = unicode(self.pageContent.moduleTable.item(index, 1).text())
222         if self._buttonGroup.button(index).isChecked():
223             self._moduleSelected(module)
224         else:
225             self._moduleUnselected(module)
226     
227     def _dependencyCheck(self, item):
228         checked = False
229         module = unicode(item.text(0))
230         if item.checkState(0) == Qt.Checked:
231             self._moduleSelected(module)
232         else:
233             self._moduleUnselected(module)
234     
235     def _moduleSelected(self, selectedModule):
236         modules = self._projectInfoRetrieve("MODULES")
237         modules[selectedModule]["enabled"] = True
238         self._projectInfoStore("MODULES", modules)
239         depends = self._projectInfoRetrieve("MODULES")[selectedModule]["depends"]
240         unsatisfied = []
241         if self.pageContent.automaticFix.isChecked():
242             unsatisfied = self.selectDependencyCheck(selectedModule)
243         if len(unsatisfied) > 0:
244             for module in unsatisfied:
245                 modules = self._projectInfoRetrieve("MODULES")
246                 modules[module]["enabled"] = True
247             for category in range(self.pageContent.moduleTree.topLevelItemCount()):
248                 item = self.pageContent.moduleTree.topLevelItem(category)
249                 for child in range(item.childCount()):
250                     if unicode(item.child(child).text(0)) in unsatisfied:
251                         item.child(child).setCheckState(0, Qt.Checked)
252     
253     def _moduleUnselected(self, unselectedModule):
254         modules = self._projectInfoRetrieve("MODULES")
255         modules[unselectedModule]["enabled"] = False
256         self._projectInfoStore("MODULES", modules)
257         unsatisfied = []
258         if self.pageContent.automaticFix.isChecked():
259             unsatisfied = self.unselectDependencyCheck(unselectedModule)
260         if len(unsatisfied) > 0:
261             message = self.tr("The module %1 is needed by the following modules:\n%2.\n\nDo you want to remove these modules too?")
262             message = message.arg(unselectedModule).arg(", ".join(unsatisfied))
263             choice = QMessageBox.warning(self, self.tr("Dependency error"), message, QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)
264             if choice == QMessageBox.Yes:
265                 for module in unsatisfied:
266                     modules = self._projectInfoRetrieve("MODULES")
267                     modules[module]["enabled"] = False
268                 for category in range(self.pageContent.moduleTree.topLevelItemCount()):
269                     item = self.pageContent.moduleTree.topLevelItem(category)
270                     for child in range(item.childCount()):
271                         if unicode(item.child(child).text(0)) in unsatisfied:
272                             item.child(child).setCheckState(0, Qt.Unchecked)
273     
274     def selectDependencyCheck(self, module):
275         unsatisfied = set()
276         modules = self._projectInfoRetrieve("MODULES")
277         for dependency in modules[module]["depends"]:
278             if not modules[dependency]["enabled"]:
279                 unsatisfied |= set([dependency])
280                 if dependency not in unsatisfied:
281                     unsatisfied |= self.selectDependencyCheck(dependency)
282         return unsatisfied
283     
284     def unselectDependencyCheck(self, dependency):
285         unsatisfied = set()
286         modules = self._projectInfoRetrieve("MODULES")
287         for module, informations in modules.items():
288             if dependency in informations["depends"] and informations["enabled"]:
289                 unsatisfied |= set([module])
290                 if dependency not in unsatisfied:
291                     unsatisfied |= self.unselectDependencyCheck(module)
292         return unsatisfied
293
294 class QControlGroup(QObject):
295     def __init__(self):
296         QObject.__init__(self)
297         self._controls = {}
298     
299     def addControl(self, id, control):
300         self._controls[id] = control
301         if type(control) == QCheckBox:
302             self.connect(control, SIGNAL("stateChanged(int)"), lambda: self._stateChanged(id))
303         elif type(control) == QSpinBox:
304             self.connect(control, SIGNAL("valueChanged(int)"), lambda: self._stateChanged(id))
305         elif type(control) == QComboBox:
306             self.connect(control, SIGNAL("currentIndexChanged(int)"), lambda: self._stateChanged(id))
307         elif type(control) == QDoubleSpinBox:
308             self.connect(control, SIGNAL("valueChanged(double)"), lambda: self._stateChanged(id))
309     
310     def clear(self):
311         self._controls = {}
312     
313     def _stateChanged(self, id):
314         self.emit(SIGNAL("stateChanged"), id)