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