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