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