Correct a bug with autoenabled configuration parameters
[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._control_group = 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._button_group = QButtonGroup()
36         self._button_group.setExclusive(False)
37         self.connect(self._button_group, 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                 module_item = QTreeWidgetItem(item, QStringList([module]))
62                 module_item.setCheckState(0, Qt.Unchecked)
63             self.pageContent.moduleTree.addTopLevelItem(item)
64         self.pageContent.moduleTree.sortItems(0, Qt.AscendingOrder)
65         
66     
67     def _fillPropertyTable(self):
68         module = self._currentModule()
69         if module is not None:
70             self._control_group.clear()
71             configuration = self._projectInfoRetrieve("MODULES")[module]["configuration"]
72             module_description = self._projectInfoRetrieve("MODULES")[module]["description"]
73             self.pageContent.moduleLabel.setText(module_description)
74             self.pageContent.moduleLabel.setVisible(True)
75             self.pageContent.propertyTable.clear()
76             if len(configuration) > 0:
77                 configurations = self._projectInfoRetrieve("CONFIGURATIONS")[configuration]
78                 self.pageContent.propertyTable.setRowCount(0)
79                 index = 0
80                 for property in configurations:
81                     if "type" in configurations[property]["informations"] and configurations[property]["informations"]["type"] == "autoenabled":
82                         ## Doesn't show the hidden fields
83                         pass
84                     else:
85                         ## Set the row count to the current index + 1
86                         self.pageContent.propertyTable.setRowCount(index + 1)
87                         item = QTableWidgetItem(configurations[property]["brief"])
88                         item.setData(Qt.UserRole, qvariant_converter.convertString(property))
89                         self.pageContent.propertyTable.setItem(index, 0, item)
90                         if "type" in configurations[property]["informations"].keys() and configurations[property]["informations"]["type"] == "boolean":
91                             self._insertCheckBox(index, configurations[property]["value"])
92                         elif "type" in configurations[property]["informations"].keys() and configurations[property]["informations"]["type"] == "enum":
93                             self._insertComboBox(index, configurations[property]["value"], configurations[property]["informations"]["value_list"])
94                         elif "type" in configurations[property]["informations"] and configurations[property]["informations"]["type"] == "int":
95                             self._insertSpinBox(index, configurations[property]["value"], configurations[property]["informations"])
96                         else:
97                             # Not defined type, rendered as a text field
98                             self.pageContent.propertyTable.setItem(index, 1, QTableWidgetItem(configurations[property]["value"]))
99                         index += 1
100             else:
101                 self.pageContent.propertyTable.setRowCount(0)
102     
103     def _insertCheckBox(self, index, value):
104         ## boolean property
105         check_box = QCheckBox()
106         self.pageContent.propertyTable.setCellWidget(index, 1, check_box)
107         if value == "1":
108             check_box.setChecked(True)
109         else:
110             check_box.setChecked(False)
111         self._control_group.addControl(index, check_box)
112     
113     def _insertComboBox(self, index, value, value_list):
114         ## enum property
115         combo_box = QComboBox()
116         self.pageContent.propertyTable.setCellWidget(index, 1, combo_box)
117         enum = self._projectInfoRetrieve("LISTS")[value_list]
118         for i, element in enumerate(enum):
119             combo_box.addItem(element)
120             if element == value:
121                 combo_box.setCurrentIndex(i)
122         self._control_group.addControl(index, combo_box)
123     
124     def _insertSpinBox(self, index, value, informations):
125         ## int, long or undefined type property
126         spin_box = None
127         if bertos_utils.isLong(informations) or bertos_utils.isUnsignedLong(informations):
128             spin_box = QDoubleSpinBox()
129             spin_box.setDecimals(0)
130         else:
131             spin_box = QSpinBox()
132         self.pageContent.propertyTable.setCellWidget(index, 1, spin_box)
133         minimum = -32768
134         maximum = 32767
135         suff = ""
136         if bertos_utils.isLong(informations):
137             minimum = -2147483648
138             maximum = 2147483647
139             suff = "L"
140         elif bertos_utils.isUnsigned(informations):
141             minimum = 0
142             maximum = 65535
143             suff = "U"
144         elif bertos_utils.isUnsignedLong(informations):
145             minimum = 0
146             maximum = 4294967295
147             suff = "UL"
148         if "min" in informations.keys():
149             minimum = int(informations["min"])
150         if "max" in informations.keys():
151             maximum = int(informations["max"])
152         spin_box.setRange(minimum, maximum)
153         spin_box.setSuffix(suff)
154         spin_box.setValue(int(value.replace("L", "").replace("U", "")))
155         self._control_group.addControl(index, spin_box)
156         
157     
158     def _currentModule(self):
159         current_module = self.pageContent.moduleTree.currentItem()
160         # return only the child items
161         if current_module is not None and current_module.parent() is not None:
162             return unicode(current_module.text(0))
163         else:
164             return None
165     
166     def _currentModuleConfigurations(self):
167         return self._configurations(self._currentModule())
168     
169     def _currentProperty(self):
170         return qvariant_converter.getString(self.pageContent.propertyTable.item(self.pageContent.propertyTable.currentRow(), 0).data(Qt.UserRole))
171     
172     def _currentPropertyItem(self):
173         return self.pageContent.propertyTable.item(self.pageContent.propertyTable.currentRow(), 0)
174     
175     def _configurations(self, module):
176         configuration = self._projectInfoRetrieve("MODULES")[module]["configuration"]
177         if len(configuration) > 0:
178             return self._projectInfoRetrieve("CONFIGURATIONS")[configuration]
179         else:
180             return {}
181     
182     def _resetPropertyDescription(self):
183         for index in range(self.pageContent.propertyTable.rowCount()):
184             property_name = qvariant_converter.getString(self.pageContent.propertyTable.item(index, 0).data(Qt.UserRole))
185             # Awful solution! Needed because if the user change the module, the selection changed...
186             if property_name not in self._currentModuleConfigurations().keys():
187                 break
188             self.pageContent.propertyTable.item(index, 0).setText(self._currentModuleConfigurations()[property_name]['brief'])
189     
190     def _showPropertyDescription(self):
191         self._resetPropertyDescription()
192         configurations = self._currentModuleConfigurations()
193         if self._currentProperty() in configurations.keys():
194             description = configurations[self._currentProperty()]["brief"]
195             name = self._currentProperty()
196             self._currentPropertyItem().setText(description + "\n" + name)
197     
198     def _setupUi(self):
199         self.pageContent.moduleTree.clear()
200         self.pageContent.moduleTree.setHeaderHidden(True)
201         self.pageContent.propertyTable.horizontalHeader().setResizeMode(QHeaderView.Stretch)
202         self.pageContent.propertyTable.horizontalHeader().setVisible(False)
203         self.pageContent.propertyTable.verticalHeader().setResizeMode(QHeaderView.ResizeToContents)
204         self.pageContent.propertyTable.verticalHeader().setVisible(False)
205         self.pageContent.propertyTable.setColumnCount(2)
206         self.pageContent.propertyTable.setRowCount(0)
207         self.pageContent.moduleLabel.setVisible(False)
208     
209     def _connectSignals(self):
210         self.connect(self.pageContent.moduleTree, SIGNAL("itemPressed(QTreeWidgetItem*, int)"), self._fillPropertyTable)
211         self.connect(self.pageContent.moduleTree, SIGNAL("itemChanged(QTreeWidgetItem*, int)"), self._dependencyCheck)
212         self.connect(self.pageContent.propertyTable, SIGNAL("itemSelectionChanged()"), self._showPropertyDescription)
213         self.connect(self._control_group, SIGNAL("stateChanged"), self._saveValue)
214     
215     def _saveValue(self, index):
216         property = qvariant_converter.getString(self.pageContent.propertyTable.item(index, 0).data(Qt.UserRole))
217         configuration = self._projectInfoRetrieve("MODULES")[self._currentModule()]["configuration"]
218         configurations = self._projectInfoRetrieve("CONFIGURATIONS")
219         if "type" not in configurations[configuration][property]["informations"].keys() or configurations[configuration][property]["informations"]["type"] == "int":
220             configurations[configuration][property]["value"] = str(int(self.pageContent.propertyTable.cellWidget(index, 1).value()))
221         elif configurations[configuration][property]["informations"]["type"] == "enum":
222             configurations[configuration][property]["value"] = unicode(self.pageContent.propertyTable.cellWidget(index, 1).currentText())
223         elif configurations[configuration][property]["informations"]["type"] == "boolean":
224             if self.pageContent.propertyTable.cellWidget(index, 1).isChecked():
225                 configurations[configuration][property]["value"] = "1"
226             else:
227                 configurations[configuration][property]["value"] = "0"
228         self._projectInfoStore("CONFIGURATIONS", configurations)
229     
230     def _moduleSelectionChanged(self, index):
231         module = unicode(self.pageContent.moduleTable.item(index, 1).text())
232         if self._button_group.button(index).isChecked():
233             self._moduleSelected(module)
234         else:
235             self._moduleUnselected(module)
236     
237     def _dependencyCheck(self, item):
238         checked = False
239         module = unicode(item.text(0))
240         if item.checkState(0) == Qt.Checked:
241             self._moduleSelected(module)
242         else:
243             self._moduleUnselected(module)
244             self.removeFileDependencies(module)
245     
246     def _moduleSelected(self, selectedModule):
247         modules = self._projectInfoRetrieve("MODULES")
248         modules[selectedModule]["enabled"] = True
249         self._projectInfoStore("MODULES", modules)
250         depends = self._projectInfoRetrieve("MODULES")[selectedModule]["depends"]
251         unsatisfied = []
252         if self.pageContent.automaticFix.isChecked():
253             unsatisfied = self.selectDependencyCheck(selectedModule)
254         if len(unsatisfied) > 0:
255             for module in unsatisfied:
256                 modules = self._projectInfoRetrieve("MODULES")
257                 modules[module]["enabled"] = True
258             for category in range(self.pageContent.moduleTree.topLevelItemCount()):
259                 item = self.pageContent.moduleTree.topLevelItem(category)
260                 for child in range(item.childCount()):
261                     if unicode(item.child(child).text(0)) in unsatisfied:
262                         item.child(child).setCheckState(0, Qt.Checked)
263     
264     def _moduleUnselected(self, unselectedModule):
265         modules = self._projectInfoRetrieve("MODULES")
266         modules[unselectedModule]["enabled"] = False
267         self._projectInfoStore("MODULES", modules)
268         unsatisfied = []
269         if self.pageContent.automaticFix.isChecked():
270             unsatisfied = self.unselectDependencyCheck(unselectedModule)
271         if len(unsatisfied) > 0:
272             message = self.tr("The module %1 is needed by the following modules:\n%2.\n\nDo you want to remove these modules too?")
273             message = message.arg(unselectedModule).arg(", ".join(unsatisfied))
274             choice = QMessageBox.warning(self, self.tr("Dependency error"), message, QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)
275             if choice == QMessageBox.Yes:
276                 for module in unsatisfied:
277                     modules = self._projectInfoRetrieve("MODULES")
278                     modules[module]["enabled"] = False
279                 for category in range(self.pageContent.moduleTree.topLevelItemCount()):
280                     item = self.pageContent.moduleTree.topLevelItem(category)
281                     for child in range(item.childCount()):
282                         if unicode(item.child(child).text(0)) in unsatisfied:
283                             item.child(child).setCheckState(0, Qt.Unchecked)
284     
285     def selectDependencyCheck(self, module):
286         unsatisfied = set()
287         modules = self._projectInfoRetrieve("MODULES")
288         files = self._projectInfoRetrieve("FILES")
289         for dependency in modules[module]["depends"]:
290             if dependency in modules and not modules[dependency]["enabled"]:
291                 unsatisfied |= set([dependency])
292                 if dependency not in unsatisfied:
293                     unsatisfied |= self.selectDependencyCheck(dependency)
294             if dependency not in modules:
295                 if dependency in files:
296                     files[dependency] += 1
297                 else:
298                     files[dependency] = 1
299         self._projectInfoStore("FILES", files)
300         return unsatisfied
301     
302     def unselectDependencyCheck(self, dependency):
303         unsatisfied = set()
304         modules = self._projectInfoRetrieve("MODULES")
305         for module, informations in modules.items():
306             if dependency in informations["depends"] and informations["enabled"]:
307                 unsatisfied |= set([module])
308                 if dependency not in unsatisfied:
309                     unsatisfied |= self.unselectDependencyCheck(module)
310         return unsatisfied
311     
312     def removeFileDependencies(self, module):
313         modules = self._projectInfoRetrieve("MODULES")
314         files = self._projectInfoRetrieve("FILES")
315         dependencies = modules[module]["depends"]
316         for dependency in dependencies:
317             if dependency in files:
318                 files[dependency] -= 1
319                 if files[dependency] == 0:
320                     del files[dependency]
321         self._projectInfoStore("FILES", files)
322
323 class QControlGroup(QObject):
324     def __init__(self):
325         QObject.__init__(self)
326         self._controls = {}
327     
328     def addControl(self, id, control):
329         self._controls[id] = control
330         if type(control) == QCheckBox:
331             self.connect(control, SIGNAL("stateChanged(int)"), lambda: self._stateChanged(id))
332         elif type(control) == QSpinBox:
333             self.connect(control, SIGNAL("valueChanged(int)"), lambda: self._stateChanged(id))
334         elif type(control) == QComboBox:
335             self.connect(control, SIGNAL("currentIndexChanged(int)"), lambda: self._stateChanged(id))
336         elif type(control) == QDoubleSpinBox:
337             self.connect(control, SIGNAL("valueChanged(double)"), lambda: self._stateChanged(id))
338     
339     def clear(self):
340         self._controls = {}
341     
342     def _stateChanged(self, id):
343         self.emit(SIGNAL("stateChanged"), id)