Update the property table when filling the module tree
[bertos.git] / wizard / BModulePage.py
1 #!/usr/bin/env python
2 # encoding: utf-8
3 #
4 # This file is part of BeRTOS.
5 #
6 # Bertos is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 2 of the License, or
9 # (at your option) any later version.
10 #
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, write to the Free Software
18 # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
19 #
20 # As a special exception, you may use this file as part of a free software
21 # library without restriction.  Specifically, if other files instantiate
22 # templates or use macros or inline functions from this file, or you compile
23 # this file and link it with other files to produce an executable, this
24 # file does not by itself cause the resulting executable to be covered by
25 # the GNU General Public License.  This exception does not however
26 # invalidate any other reasons why the executable file might be covered by
27 # the GNU General Public License.
28 #
29 # Copyright 2008 Develer S.r.l. (http://www.develer.com/)
30 #
31 # $Id$
32 #
33 # Author: Lorenzo Berni <duplo@develer.com>
34 #
35
36 import os
37
38 from PyQt4.QtGui import *
39 from BWizardPage import *
40 import bertos_utils
41
42 from bertos_utils import SupportedException
43 from DefineException import *
44 from const import *
45
46 class BModulePage(BWizardPage):
47     """
48     Page of the wizard that permits to select and configurate the BeRTOS modules.
49     """
50     
51     def __init__(self):
52         BWizardPage.__init__(self, UI_LOCATION + "/module_select.ui")
53         self.setTitle(self.tr("Configure the BeRTOS modules"))
54         self._control_group = QControlGroup()
55         ## special connection needed for the QControlGroup
56         self.connect(self._control_group, SIGNAL("stateChanged"), self.saveValue)
57     
58     ## Overloaded BWizardPage methods ##
59
60     def setupUi(self):
61         """
62         Overload of BWizardPage setupUi method.
63         """
64         self.pageContent.moduleTree.clear()
65         self.pageContent.moduleTree.setHeaderHidden(True)
66         self.pageContent.propertyTable.horizontalHeader().setResizeMode(QHeaderView.Stretch)
67         self.pageContent.propertyTable.horizontalHeader().setVisible(False)
68         self.pageContent.propertyTable.verticalHeader().setResizeMode(QHeaderView.ResizeToContents)
69         self.pageContent.propertyTable.verticalHeader().setVisible(False)
70         self.pageContent.propertyTable.setColumnCount(2)
71         self.pageContent.propertyTable.setRowCount(0)
72         self.pageContent.moduleLabel.setVisible(False)
73         self.pageContent.warningLabel.setVisible(False)
74     
75     def connectSignals(self):
76         """
77         Overload of the BWizardPage connectSignals method.
78         """
79         self.connect(self.pageContent.moduleTree, SIGNAL("itemPressed(QTreeWidgetItem*, int)"), self.fillPropertyTable)
80         self.connect(self.pageContent.moduleTree, SIGNAL("itemChanged(QTreeWidgetItem*, int)"), self.dependencyCheck)
81         self.connect(self.pageContent.propertyTable, SIGNAL("itemSelectionChanged()"), self.showPropertyDescription)
82
83     def reloadData(self):
84         """
85         Overload of the BWizardPage reloadData method.
86         """
87         QApplication.instance().setOverrideCursor(Qt.WaitCursor)
88         self.setupUi()
89         self.loadModuleData()
90         self.fillModuleTree()
91         QApplication.instance().restoreOverrideCursor()
92     
93     ####
94     
95     ## Slots ##
96
97     def fillPropertyTable(self):
98         """
99         Slot called when the user selects a module from the module tree.
100         Fills the property table using the configuration parameters defined in
101         the source tree.
102         """
103         module = self.currentModule()
104         if module:
105             try:
106                 supported = bertos_utils.isSupported(self.project(), module=module)
107             except SupportedException, e:
108                 self.exceptionOccurred(self.tr("Error evaluating \"%1\" for module %2").arg(e.support_string).arg(module))
109                 supported = True
110             self._control_group.clear()
111             configuration = self.projectInfo("MODULES")[module]["configuration"]
112             module_description = self.projectInfo("MODULES")[module]["description"]
113             self.pageContent.moduleLabel.setText(module_description)
114             self.pageContent.moduleLabel.setVisible(True)
115             if not supported:
116                 self.pageContent.warningLabel.setVisible(True)
117                 selected_cpu = self.projectInfo("CPU_NAME")
118                 self.pageContent.warningLabel.setText(self.tr("<font color='#FF0000'>Warning: the selected module, \
119                     is not completely supported by the %1.</font>").arg(selected_cpu))
120             else:
121                 self.pageContent.warningLabel.setVisible(False)
122             self.pageContent.propertyTable.clear()
123             self.pageContent.propertyTable.setRowCount(0)
124             if configuration != "":
125                 configurations = self.projectInfo("CONFIGURATIONS")[configuration]
126                 param_list = sorted(configurations["paramlist"])
127                 index = 0
128                 for i, property in param_list:
129                     if "type" in configurations[property]["informations"] and configurations[property]["informations"]["type"] == "autoenabled":
130                         # Doesn't show the hidden fields
131                         continue
132                     try:
133                         param_supported = bertos_utils.isSupported(self.project(), property_id=(configuration, property))
134                     except SupportedException, e:
135                         self.exceptionOccurred(self.tr("Error evaluating \"%1\" for parameter %2").arg(e.support_string).arg(property))
136                         param_supported = True
137                     if not param_supported:
138                         # Doesn't show the unsupported parameters
139                         continue
140                     # Set the row count to the current index + 1
141                     self.pageContent.propertyTable.setRowCount(index + 1)
142                     item = QTableWidgetItem(configurations[property]["brief"])
143                     item.setData(Qt.UserRole, qvariant_converter.convertString(property))
144                     self.pageContent.propertyTable.setItem(index, 0, item)
145                     if "type" in configurations[property]["informations"] and configurations[property]["informations"]["type"] == "boolean":
146                         self.insertCheckBox(index, configurations[property]["value"])
147                     elif "type" in configurations[property]["informations"] and configurations[property]["informations"]["type"] == "enum":
148                         self.insertComboBox(index, configurations[property]["value"], configurations[property]["informations"]["value_list"])
149                     elif "type" in configurations[property]["informations"] and configurations[property]["informations"]["type"] == "int":
150                         self.insertSpinBox(index, configurations[property]["value"], configurations[property]["informations"])
151                     else:
152                         # Not defined type, rendered as a text field
153                         self.pageContent.propertyTable.setItem(index, 1, QTableWidgetItem(configurations[property]["value"]))
154                     index += 1
155             if self.pageContent.propertyTable.rowCount() == 0:
156                 module_label = self.pageContent.moduleLabel.text()
157                 module_label += "\n\nNo configuration needed."
158                 self.pageContent.moduleLabel.setText(module_label) 
159         else:
160             self.pageContent.moduleLabel.setText("")
161             self.pageContent.moduleLabel.setVisible(False)
162
163     def dependencyCheck(self, item):
164         """
165         Checks the dependencies of the module associated with the given item.
166         """
167         checked = False
168         module = unicode(item.text(0))
169         if item.checkState(0) == Qt.Checked:
170             self.moduleSelected(module)
171         else:
172             self.moduleUnselected(module)
173             self.removeFileDependencies(module)
174
175     def showPropertyDescription(self):
176         """
177         Slot called when the property selection changes. Shows the description
178         of the selected property.
179         """
180         self.resetPropertyDescription()
181         configurations = self.currentModuleConfigurations()
182         if self.currentProperty() in configurations:
183             description = configurations[self.currentProperty()]["brief"]
184             name = self.currentProperty()
185             self.currentPropertyItem().setText(description + "\n" + name)
186
187     def saveValue(self, index):
188         """
189         Slot called when the user modifies one of the configuration parameters.
190         It stores the new value."""
191         property = qvariant_converter.getString(self.pageContent.propertyTable.item(index, 0).data(Qt.UserRole))
192         configuration = self.projectInfo("MODULES")[self.currentModule()]["configuration"]
193         configurations = self.projectInfo("CONFIGURATIONS")
194         if "type" not in configurations[configuration][property]["informations"] or configurations[configuration][property]["informations"]["type"] == "int":
195             configurations[configuration][property]["value"] = unicode(int(self.pageContent.propertyTable.cellWidget(index, 1).value()))
196         elif configurations[configuration][property]["informations"]["type"] == "enum":
197             configurations[configuration][property]["value"] = unicode(self.pageContent.propertyTable.cellWidget(index, 1).currentText())
198         elif configurations[configuration][property]["informations"]["type"] == "boolean":
199             if self.pageContent.propertyTable.cellWidget(index, 1).isChecked():
200                 configurations[configuration][property]["value"] = "1"
201             else:
202                 configurations[configuration][property]["value"] = "0"
203         self.setProjectInfo("CONFIGURATIONS", configurations)
204
205     ####
206     
207     def loadModuleData(self):
208         """
209         Loads the module data.
210         """
211         # Load the module data only if it isn't already loaded
212         if not self.projectInfo("MODULES") \
213                 and not self.projectInfo("LISTS") \
214                 and not self.projectInfo("CONFIGURATIONS"):
215             try:
216                 bertos_utils.loadModuleData(self.project())
217             except ModuleDefineException, e:
218                 self.exceptionOccurred(self.tr("Error parsing line '%2' in file %1").arg(e.path).arg(e.line))
219             except EnumDefineException, e:
220                 self.exceptionOccurred(self.tr("Error parsing line '%2' in file %1").arg(e.path).arg(e.line))
221             except ConfigurationDefineException, e:
222                 self.exceptionOccurred(self.tr("Error parsing line '%2' in file %1").arg(e.path).arg(e.line))
223     
224     def fillModuleTree(self):
225         """
226         Fills the module tree with the module entries separated in categories.
227         """
228         self.pageContent.moduleTree.clear()
229         modules = self.projectInfo("MODULES")
230         if not modules:
231             return
232         categories = {}
233         for module, information in modules.items():
234             if information["category"] not in categories:
235                 categories[information["category"]] = []
236             categories[information["category"]].append(module)
237         for category, module_list in categories.items():
238             item = QTreeWidgetItem(QStringList([category]))
239             for module in module_list:
240                 enabled = modules[module]["enabled"]
241                 module_item = QTreeWidgetItem(item, QStringList([module]))
242                 try:
243                     supported = bertos_utils.isSupported(self.project(), module=module)
244                 except SupportedException, e:
245                     self.exceptionOccurred(self.tr("Error evaluating \"%1\" for module %2").arg(e.support_string).arg(module))
246                     supported = True
247                 if not supported:
248                     module_item.setForeground(0, QBrush(QColor(Qt.red)))
249                 if enabled:
250                     module_item.setCheckState(0, Qt.Checked)
251                 else:
252                     module_item.setCheckState(0, Qt.Unchecked)
253             self.pageContent.moduleTree.addTopLevelItem(item)
254         self.pageContent.moduleTree.sortItems(0, Qt.AscendingOrder)
255         self.fillPropertyTable()
256             
257     def insertCheckBox(self, index, value):
258         """
259         Inserts in the table at index a checkbox for a boolean property setted
260         to value.
261         """
262         check_box = QCheckBox()
263         self.pageContent.propertyTable.setCellWidget(index, 1, check_box)
264         if value == "1":
265             check_box.setChecked(True)
266         else:
267             check_box.setChecked(False)
268         self._control_group.addControl(index, check_box)
269     
270     def insertComboBox(self, index, value, value_list):
271         """
272         Inserts in the table at index a combobox for an enum property setted
273         to value.
274         """
275         try:
276             enum = self.projectInfo("LISTS")[value_list]
277             combo_box = QComboBox()
278             self.pageContent.propertyTable.setCellWidget(index, 1, combo_box)
279             for i, element in enumerate(enum):
280                 combo_box.addItem(element)
281                 if element == value:
282                     combo_box.setCurrentIndex(i)
283             self._control_group.addControl(index, combo_box)
284         except KeyError:
285             self.exceptionOccurred(self.tr("Define list \"%1\" not found. Check definition files.").arg(value_list))
286             self.pageContent.propertyTable.setItem(index, 1, QTableWidgetItem(value))
287     
288     def insertSpinBox(self, index, value, informations):
289         """
290         Inserts in the table at index a spinbox for an int, a long or an unsigned
291         long property setted to value.
292         """
293         # int, long or undefined type property
294         spin_box = None
295         if bertos_utils.isLong(informations) or bertos_utils.isUnsignedLong(informations):
296             spin_box = QDoubleSpinBox()
297             spin_box.setDecimals(0)
298         else:
299             spin_box = QSpinBox()
300         self.pageContent.propertyTable.setCellWidget(index, 1, spin_box)
301         minimum = -32768
302         maximum = 32767
303         suff = ""
304         if bertos_utils.isLong(informations):
305             minimum = -2147483648
306             maximum = 2147483647
307             suff = "L"
308         elif bertos_utils.isUnsigned(informations):
309             minimum = 0
310             maximum = 65535
311             suff = "U"
312         elif bertos_utils.isUnsignedLong(informations):
313             minimum = 0
314             maximum = 4294967295
315             suff = "UL"
316         if "min" in informations:
317             minimum = int(informations["min"])
318         if "max" in informations:
319             maximum = int(informations["max"])
320         spin_box.setRange(minimum, maximum)
321         spin_box.setSuffix(suff)
322         spin_box.setValue(int(value.replace("L", "").replace("U", "")))
323         self._control_group.addControl(index, spin_box)
324         
325     
326     def currentModule(self):
327         """
328         Retuns the current module name.
329         """
330         current_module = self.pageContent.moduleTree.currentItem()
331         # return only the child items
332         if current_module and current_module.parent():
333             return unicode(current_module.text(0))
334         else:
335             return None
336     
337     def currentModuleConfigurations(self):
338         """
339         Returns the current module configuration.
340         """
341         return self.configurations(self.currentModule())
342     
343     def currentProperty(self):
344         """
345         Rerturns the current property from the property table.
346         """
347         return qvariant_converter.getString(self.pageContent.propertyTable.item(self.pageContent.propertyTable.currentRow(), 0).data(Qt.UserRole))
348     
349     def currentPropertyItem(self):
350         """
351         Returns the QTableWidgetItem of the current property.
352         """
353         return self.pageContent.propertyTable.item(self.pageContent.propertyTable.currentRow(), 0)
354     
355     def configurations(self, module):
356         """
357         Returns the configuration for the selected module.
358         """
359         configuration = self.projectInfo("MODULES")[module]["configuration"]
360         if len(configuration) > 0:
361             return self.projectInfo("CONFIGURATIONS")[configuration]
362         else:
363             return {}
364     
365     def resetPropertyDescription(self):
366         """
367         Resets the label for each property table entry.
368         """
369         for index in range(self.pageContent.propertyTable.rowCount()):
370             property_name = qvariant_converter.getString(self.pageContent.propertyTable.item(index, 0).data(Qt.UserRole))
371             # Awful solution! Needed because if the user change the module, the selection changed...
372             if property_name not in self.currentModuleConfigurations():
373                 break
374             self.pageContent.propertyTable.item(index, 0).setText(self.currentModuleConfigurations()[property_name]['brief'])
375     
376     def moduleSelected(self, selectedModule):
377         """
378         Resolves the selection dependencies.
379         """
380         modules = self.projectInfo("MODULES")
381         modules[selectedModule]["enabled"] = True
382         self.setProjectInfo("MODULES", modules)
383         depends = self.projectInfo("MODULES")[selectedModule]["depends"]
384         unsatisfied = []
385         if self.pageContent.automaticFix.isChecked():
386             unsatisfied = self.selectDependencyCheck(selectedModule)
387         if len(unsatisfied) > 0:
388             for module in unsatisfied:
389                 modules = self.projectInfo("MODULES")
390                 modules[module]["enabled"] = True
391             for category in range(self.pageContent.moduleTree.topLevelItemCount()):
392                 item = self.pageContent.moduleTree.topLevelItem(category)
393                 for child in range(item.childCount()):
394                     if unicode(item.child(child).text(0)) in unsatisfied:
395                         item.child(child).setCheckState(0, Qt.Checked)
396     
397     def moduleUnselected(self, unselectedModule):
398         """
399         Resolves the unselection dependencies.
400         """
401         modules = self.projectInfo("MODULES")
402         modules[unselectedModule]["enabled"] = False
403         self.setProjectInfo("MODULES", modules)
404         unsatisfied = []
405         if self.pageContent.automaticFix.isChecked():
406             unsatisfied = self.unselectDependencyCheck(unselectedModule)
407         if len(unsatisfied) > 0:
408             message = self.tr("The module %1 is needed by the following modules:\n%2.\n\nDo you want to remove these modules too?")
409             message = message.arg(unselectedModule).arg(", ".join(unsatisfied))
410             choice = QMessageBox.warning(self, self.tr("Dependency error"), message, QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)
411             if choice == QMessageBox.Yes:
412                 for module in unsatisfied:
413                     modules = self.projectInfo("MODULES")
414                     modules[module]["enabled"] = False
415                 for category in range(self.pageContent.moduleTree.topLevelItemCount()):
416                     item = self.pageContent.moduleTree.topLevelItem(category)
417                     for child in range(item.childCount()):
418                         if unicode(item.child(child).text(0)) in unsatisfied:
419                             item.child(child).setCheckState(0, Qt.Unchecked)
420     
421     def selectDependencyCheck(self, module):
422         """
423         Returns the list of unsatisfied dependencies after a selection.
424         """
425         unsatisfied = set()
426         modules = self.projectInfo("MODULES")
427         files = self.projectInfo("FILES")
428         for dependency in modules[module]["depends"]:
429             if dependency in modules and not modules[dependency]["enabled"]:
430                 unsatisfied |= set([dependency])
431                 if dependency not in unsatisfied:
432                     unsatisfied |= self.selectDependencyCheck(dependency)
433             if dependency not in modules:
434                 if dependency in files:
435                     files[dependency] += 1
436                 else:
437                     files[dependency] = 1
438         self.setProjectInfo("FILES", files)
439         return unsatisfied
440     
441     def unselectDependencyCheck(self, dependency):
442         """
443         Returns the list of unsatisfied dependencies after an unselection.
444         """
445         unsatisfied = set()
446         modules = self.projectInfo("MODULES")
447         for module, informations in modules.items():
448             if dependency in informations["depends"] and informations["enabled"]:
449                 unsatisfied |= set([module])
450                 if dependency not in unsatisfied:
451                     unsatisfied |= self.unselectDependencyCheck(module)
452         return unsatisfied
453     
454     def removeFileDependencies(self, module):
455         """
456         Removes the files dependencies of the given module.
457         """
458         modules = self.projectInfo("MODULES")
459         files = self.projectInfo("FILES")
460         dependencies = modules[module]["depends"]
461         for dependency in dependencies:
462             if dependency in files:
463                 files[dependency] -= 1
464                 if files[dependency] == 0:
465                     del files[dependency]
466         self.setProjectInfo("FILES", files)
467
468 class QControlGroup(QObject):
469     """
470     Simple class that permit to connect different signals of different widgets
471     with a slot that emit a signal. Permits to group widget and to understand which of
472     them has sent the signal.
473     """
474     
475     def __init__(self):
476         QObject.__init__(self)
477         self._controls = {}
478     
479     def addControl(self, id, control):
480         """
481         Add a control.
482         """
483         self._controls[id] = control
484         if type(control) == QCheckBox:
485             self.connect(control, SIGNAL("stateChanged(int)"), lambda: self.stateChanged(id))
486         elif type(control) == QSpinBox:
487             self.connect(control, SIGNAL("valueChanged(int)"), lambda: self.stateChanged(id))
488         elif type(control) == QComboBox:
489             self.connect(control, SIGNAL("currentIndexChanged(int)"), lambda: self.stateChanged(id))
490         elif type(control) == QDoubleSpinBox:
491             self.connect(control, SIGNAL("valueChanged(double)"), lambda: self.stateChanged(id))
492     
493     def clear(self):
494         """
495         Remove all the controls.
496         """
497         self._controls = {}
498     
499     def stateChanged(self, id):
500         """
501         Slot called when the value of one of the stored widget changes. It emits
502         another signal.
503         """
504         self.emit(SIGNAL("stateChanged"), id)