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