Clear the module tree when the reloadData method is called
[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.clear()
191         self.pageContent.moduleTree.setHeaderHidden(True)
192         self.pageContent.propertyTable.horizontalHeader().setResizeMode(QHeaderView.Stretch)
193         self.pageContent.propertyTable.horizontalHeader().setVisible(False)
194         self.pageContent.propertyTable.verticalHeader().setResizeMode(QHeaderView.ResizeToContents)
195         self.pageContent.propertyTable.verticalHeader().setVisible(False)
196         self.pageContent.propertyTable.setColumnCount(2)
197         self.pageContent.propertyTable.setRowCount(0)
198         self.pageContent.moduleLabel.setVisible(False)
199     
200     def _connectSignals(self):
201         self.connect(self.pageContent.moduleTree, SIGNAL("itemPressed(QTreeWidgetItem*, int)"), self._fillPropertyTable)
202         self.connect(self.pageContent.moduleTree, SIGNAL("itemChanged(QTreeWidgetItem*, int)"), self._dependencyCheck)
203         self.connect(self.pageContent.propertyTable, SIGNAL("itemSelectionChanged()"), self._showPropertyDescription)
204         self.connect(self._controlGroup, SIGNAL("stateChanged"), self._saveValue)
205     
206     def _saveValue(self, index):
207         property = qvariant_converter.getString(self.pageContent.propertyTable.item(index, 0).data(Qt.UserRole))
208         configuration = self._projectInfoRetrieve("MODULES")[self._currentModule()]["configuration"]
209         configurations = self._projectInfoRetrieve("CONFIGURATIONS")
210         if "type" not in configurations[configuration][property]["informations"].keys() or configurations[configuration][property]["informations"]["type"] == "int":
211             configurations[configuration][property]["value"] = str(int(self.pageContent.propertyTable.cellWidget(index, 1).value()))
212         elif configurations[configuration][property]["informations"]["type"] == "enum":
213             configurations[configuration][property]["value"] = unicode(self.pageContent.propertyTable.cellWidget(index, 1).currentText())
214         elif configurations[configuration][property]["informations"]["type"] == "boolean":
215             if self.pageContent.propertyTable.cellWidget(index, 1).isChecked():
216                 configurations[configuration][property]["value"] = "1"
217             else:
218                 configurations[configuration][property]["value"] = "0"
219         self._projectInfoStore("CONFIGURATIONS", configurations)
220     
221     def _moduleSelectionChanged(self, index):
222         module = unicode(self.pageContent.moduleTable.item(index, 1).text())
223         if self._buttonGroup.button(index).isChecked():
224             self._moduleSelected(module)
225         else:
226             self._moduleUnselected(module)
227     
228     def _dependencyCheck(self, item):
229         checked = False
230         module = unicode(item.text(0))
231         if item.checkState(0) == Qt.Checked:
232             self._moduleSelected(module)
233         else:
234             self._moduleUnselected(module)
235     
236     def _moduleSelected(self, selectedModule):
237         modules = self._projectInfoRetrieve("MODULES")
238         modules[selectedModule]["enabled"] = True
239         self._projectInfoStore("MODULES", modules)
240         depends = self._projectInfoRetrieve("MODULES")[selectedModule]["depends"]
241         unsatisfied = []
242         if self.pageContent.automaticFix.isChecked():
243             unsatisfied = self.selectDependencyCheck(selectedModule)
244         if len(unsatisfied) > 0:
245             for module in unsatisfied:
246                 modules = self._projectInfoRetrieve("MODULES")
247                 modules[module]["enabled"] = True
248             for category in range(self.pageContent.moduleTree.topLevelItemCount()):
249                 item = self.pageContent.moduleTree.topLevelItem(category)
250                 for child in range(item.childCount()):
251                     if unicode(item.child(child).text(0)) in unsatisfied:
252                         item.child(child).setCheckState(0, Qt.Checked)
253     
254     def _moduleUnselected(self, unselectedModule):
255         modules = self._projectInfoRetrieve("MODULES")
256         modules[unselectedModule]["enabled"] = False
257         self._projectInfoStore("MODULES", modules)
258         unsatisfied = []
259         if self.pageContent.automaticFix.isChecked():
260             unsatisfied = self.unselectDependencyCheck(unselectedModule)
261         if len(unsatisfied) > 0:
262             message = self.tr("The module %1 is needed by the following modules:\n%2.\n\nDo you want to remove these modules too?")
263             message = message.arg(unselectedModule).arg(", ".join(unsatisfied))
264             choice = QMessageBox.warning(self, self.tr("Dependency error"), message, QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)
265             if choice == QMessageBox.Yes:
266                 for module in unsatisfied:
267                     modules = self._projectInfoRetrieve("MODULES")
268                     modules[module]["enabled"] = False
269                 for category in range(self.pageContent.moduleTree.topLevelItemCount()):
270                     item = self.pageContent.moduleTree.topLevelItem(category)
271                     for child in range(item.childCount()):
272                         if unicode(item.child(child).text(0)) in unsatisfied:
273                             item.child(child).setCheckState(0, Qt.Unchecked)
274     
275     def selectDependencyCheck(self, module):
276         unsatisfied = set()
277         modules = self._projectInfoRetrieve("MODULES")
278         for dependency in modules[module]["depends"]:
279             if not modules[dependency]["enabled"]:
280                 unsatisfied |= set([dependency])
281                 if dependency not in unsatisfied:
282                     unsatisfied |= self.selectDependencyCheck(dependency)
283         return unsatisfied
284     
285     def unselectDependencyCheck(self, dependency):
286         unsatisfied = set()
287         modules = self._projectInfoRetrieve("MODULES")
288         for module, informations in modules.items():
289             if dependency in informations["depends"] and informations["enabled"]:
290                 unsatisfied |= set([module])
291                 if dependency not in unsatisfied:
292                     unsatisfied |= self.unselectDependencyCheck(module)
293         return unsatisfied
294
295 class QControlGroup(QObject):
296     def __init__(self):
297         QObject.__init__(self)
298         self._controls = {}
299     
300     def addControl(self, id, control):
301         self._controls[id] = control
302         if type(control) == QCheckBox:
303             self.connect(control, SIGNAL("stateChanged(int)"), lambda: self._stateChanged(id))
304         elif type(control) == QSpinBox:
305             self.connect(control, SIGNAL("valueChanged(int)"), lambda: self._stateChanged(id))
306         elif type(control) == QComboBox:
307             self.connect(control, SIGNAL("currentIndexChanged(int)"), lambda: self._stateChanged(id))
308         elif type(control) == QDoubleSpinBox:
309             self.connect(control, SIGNAL("valueChanged(double)"), lambda: self._stateChanged(id))
310     
311     def clear(self):
312         self._controls = {}
313     
314     def _stateChanged(self, id):
315         self.emit(SIGNAL("stateChanged"), id)