Fix problems with older BeRTOS versions.
[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.QtCore import *
39 from PyQt4.QtGui import *
40 from BWizardPage import *
41 import bertos_utils
42
43 from bertos_utils import SupportedException
44 from DefineException import *
45 from const import *
46
47 class BModulePage(BWizardPage):
48     """
49     Page of the wizard that permits to select and configurate the BeRTOS modules.
50     """
51     
52     def __init__(self):
53         BWizardPage.__init__(self, UI_LOCATION + "/module_select.ui")
54         self.setTitle(self.tr("Configure the BeRTOS modules"))
55         self._control_group = QControlGroup()
56         ## special connection needed for the QControlGroup
57         self.connect(self._control_group, SIGNAL("stateChanged"), self.saveValue)
58     
59     ## Overloaded BWizardPage methods ##
60
61     def setupUi(self):
62         """
63         Overload of BWizardPage setupUi method.
64         """
65         self.pageContent.moduleTree.clear()
66         self.pageContent.moduleTree.setHeaderHidden(True)
67         self.pageContent.propertyTable.horizontalHeader().setResizeMode(QHeaderView.Stretch)
68         self.pageContent.propertyTable.horizontalHeader().setVisible(False)
69         self.pageContent.propertyTable.verticalHeader().setResizeMode(QHeaderView.ResizeToContents)
70         self.pageContent.propertyTable.verticalHeader().setVisible(False)
71         self.pageContent.propertyTable.setColumnCount(2)
72         self.pageContent.propertyTable.setRowCount(0)
73         self.pageContent.moduleLabel.setVisible(False)
74         self.pageContent.warningLabel.setVisible(False)
75     
76     def connectSignals(self):
77         """
78         Overload of the BWizardPage connectSignals method.
79         """
80         self.connect(self.pageContent.moduleTree, SIGNAL("itemPressed(QTreeWidgetItem*, int)"), self.fillPropertyTable)
81         self.connect(self.pageContent.moduleTree, SIGNAL("itemPressed(QTreeWidgetItem*, int)"), self.moduleClicked)
82         self.connect(self.pageContent.moduleTree, SIGNAL("itemChanged(QTreeWidgetItem*, int)"), self.dependencyCheck)
83         self.connect(self.pageContent.propertyTable, SIGNAL("itemSelectionChanged()"), self.showPropertyDescription)
84
85     def reloadData(self):
86         """
87         Overload of the BWizardPage reloadData method.
88         """
89         try:
90             QApplication.instance().setOverrideCursor(Qt.WaitCursor)
91             self.setupUi()
92             self.loadModuleData()
93             self.fillModuleTree()
94         finally:
95             QApplication.instance().restoreOverrideCursor()
96     
97     ####
98     
99     ## Slots ##
100
101     def moduleClicked(self, item, column):
102         self.setBold(item, False)
103
104     def fillPropertyTable(self):
105         """
106         Slot called when the user selects a module from the module tree.
107         Fills the property table using the configuration parameters defined in
108         the source tree.
109         """
110         module = self.currentModule()
111         if module:
112             try:
113                 supported = bertos_utils.isSupported(self.project, module=module)
114             except SupportedException, e:
115                 self.exceptionOccurred(self.tr("Error evaluating \"%1\" for module %2").arg(e.support_string).arg(module))
116                 supported = True
117             self._control_group.clear()
118             configuration = self.projectInfo("MODULES")[module]["configuration"]
119             module_description = self.projectInfo("MODULES")[module]["description"]
120             self.pageContent.moduleLabel.setText(module_description)
121             self.pageContent.moduleLabel.setVisible(True)
122             if not supported:
123                 self.pageContent.warningLabel.setVisible(True)
124                 selected_cpu = self.projectInfo("CPU_NAME")
125                 self.pageContent.warningLabel.setText(self.tr("<font color='#FF0000'>Warning: the selected module, \
126                     is not completely supported by the %1.</font>").arg(selected_cpu))
127             else:
128                 self.pageContent.warningLabel.setVisible(False)
129             self.pageContent.propertyTable.clear()
130             self.pageContent.propertyTable.setRowCount(0)
131             if configuration != "":
132                 configurations = self.projectInfo("CONFIGURATIONS")[configuration]
133                 param_list = sorted(configurations["paramlist"])
134                 index = 0
135                 for i, property in param_list:
136                     if "type" in configurations[property]["informations"] and configurations[property]["informations"]["type"] == "autoenabled":
137                         # Doesn't show the hidden fields
138                         continue
139                     try:
140                         param_supported = bertos_utils.isSupported(self.project, property_id=(configuration, property))
141                     except SupportedException, e:
142                         self.exceptionOccurred(self.tr("Error evaluating \"%1\" for parameter %2").arg(e.support_string).arg(property))
143                         param_supported = True
144                     if not param_supported:
145                         # Doesn't show the unsupported parameters
146                         continue
147                     # Set the row count to the current index + 1
148                     self.pageContent.propertyTable.setRowCount(index + 1)
149                     item = QTableWidgetItem(configurations[property]["brief"])
150                     item.setData(Qt.UserRole, qvariant_converter.convertString(property))
151                     self.pageContent.propertyTable.setItem(index, 0, item)
152                     if "type" in configurations[property]["informations"] and configurations[property]["informations"]["type"] == "boolean":
153                         self.insertCheckBox(index, configurations[property]["value"])
154                     elif "type" in configurations[property]["informations"] and configurations[property]["informations"]["type"] == "enum":
155                         self.insertComboBox(index, configurations[property]["value"], configurations[property]["informations"]["value_list"])
156                     elif "type" in configurations[property]["informations"] and configurations[property]["informations"]["type"] == "int":
157                         self.insertSpinBox(index, configurations[property]["value"], configurations[property]["informations"])
158                     else:
159                         # Not defined type, rendered as a text field
160                         self.pageContent.propertyTable.setItem(index, 1, QTableWidgetItem(configurations[property]["value"]))
161                     index += 1
162             if self.pageContent.propertyTable.rowCount() == 0:
163                 module_label = self.pageContent.moduleLabel.text()
164                 module_label += "\n\nNo configuration needed."
165                 self.pageContent.moduleLabel.setText(module_label) 
166         else:
167             self.pageContent.moduleLabel.setText("")
168             self.pageContent.moduleLabel.setVisible(False)
169             self.pageContent.propertyTable.clear()
170             self.pageContent.propertyTable.setRowCount(0)
171
172     def dependencyCheck(self, item):
173         """
174         Checks the dependencies of the module associated with the given item.
175         """
176         checked = False
177         module = unicode(item.text(0))
178         if item.checkState(0) == Qt.Checked:
179             self.moduleSelected(module)
180         else:
181             self.moduleUnselected(module)
182             self.removeFileDependencies(module)
183
184     def showPropertyDescription(self):
185         """
186         Slot called when the property selection changes. Shows the description
187         of the selected property.
188         """
189         self.resetPropertyDescription()
190         configurations = self.currentModuleConfigurations()
191         if self.currentProperty() in configurations:
192             description = configurations[self.currentProperty()]["brief"]
193             name = self.currentProperty()
194             self.currentPropertyItem().setText(description + "\n" + name)
195
196     def saveValue(self, index):
197         """
198         Slot called when the user modifies one of the configuration parameters.
199         It stores the new value."""
200         property = qvariant_converter.getString(self.pageContent.propertyTable.item(index, 0).data(Qt.UserRole))
201         configuration = self.projectInfo("MODULES")[self.currentModule()]["configuration"]
202         configurations = self.projectInfo("CONFIGURATIONS")
203         if "type" not in configurations[configuration][property]["informations"] or configurations[configuration][property]["informations"]["type"] == "int":
204             configurations[configuration][property]["value"] = unicode(int(self.pageContent.propertyTable.cellWidget(index, 1).value()))
205         elif configurations[configuration][property]["informations"]["type"] == "enum":
206             configurations[configuration][property]["value"] = unicode(self.pageContent.propertyTable.cellWidget(index, 1).currentText())
207         elif configurations[configuration][property]["informations"]["type"] == "boolean":
208             if self.pageContent.propertyTable.cellWidget(index, 1).isChecked():
209                 configurations[configuration][property]["value"] = "1"
210             else:
211                 configurations[configuration][property]["value"] = "0"
212         self.setProjectInfo("CONFIGURATIONS", configurations)
213         if self.moduleItem(self.currentModule()).checkState(0) == Qt.Checked:
214             self.dependencyCheck(self.moduleItem(self.currentModule()))
215
216     ####
217     
218     def loadModuleData(self):
219         """
220         Loads the module data.
221         """
222         # Load the module data only if it isn't already loaded
223         if not self.projectInfo("MODULES") \
224                 and not self.projectInfo("LISTS") \
225                 and not self.projectInfo("CONFIGURATIONS"):
226             try:
227                 self.project.loadModuleData()
228             except ModuleDefineException, e:
229                 self.exceptionOccurred(self.tr("Error parsing line '%2' in file %1").arg(e.path).arg(e.line))
230             except EnumDefineException, e:
231                 self.exceptionOccurred(self.tr("Error parsing line '%2' in file %1").arg(e.path).arg(e.line))
232             except ConfigurationDefineException, e:
233                 self.exceptionOccurred(self.tr("Error parsing line '%2' in file %1").arg(e.path).arg(e.line))
234     
235     def fillModuleTree(self):
236         """
237         Fills the module tree with the module entries separated in categories.
238         """
239         self.pageContent.moduleTree.clear()
240         modules = self.projectInfo("MODULES")
241         if not modules:
242             return
243         categories = {}
244         for module, information in modules.items():
245             if information["category"] not in categories:
246                 categories[information["category"]] = []
247             categories[information["category"]].append(module)
248         for category, module_list in categories.items():
249             item = QTreeWidgetItem(QStringList([category]))
250             for module in module_list:
251                 enabled = modules[module]["enabled"]
252                 module_item = QTreeWidgetItem(item, QStringList([module]))
253                 try:
254                     supported = bertos_utils.isSupported(self.project, module=module)
255                 except SupportedException, e:
256                     self.exceptionOccurred(self.tr("Error evaluating \"%1\" for module %2").arg(e.support_string).arg(module))
257                     supported = True
258                 if not supported:
259                     module_item.setForeground(0, QBrush(QColor(Qt.red)))
260                 if enabled:
261                     module_item.setCheckState(0, Qt.Checked)
262                 else:
263                     module_item.setCheckState(0, Qt.Unchecked)
264             self.pageContent.moduleTree.addTopLevelItem(item)
265         self.pageContent.moduleTree.sortItems(0, Qt.AscendingOrder)
266         self.fillPropertyTable()
267             
268     def insertCheckBox(self, index, value):
269         """
270         Inserts in the table at index a checkbox for a boolean property setted
271         to value.
272         """
273         check_box = QCheckBox()
274         self.pageContent.propertyTable.setCellWidget(index, 1, check_box)
275         if value == "1":
276             check_box.setChecked(True)
277         else:
278             check_box.setChecked(False)
279         self._control_group.addControl(index, check_box)
280     
281     def insertComboBox(self, index, value, value_list):
282         """
283         Inserts in the table at index a combobox for an enum property setted
284         to value.
285         """
286         try:
287             enum = self.projectInfo("LISTS")[value_list]
288             combo_box = QComboBox()
289             self.pageContent.propertyTable.setCellWidget(index, 1, combo_box)
290             for i, element in enumerate(enum):
291                 combo_box.addItem(element)
292                 if element == value:
293                     combo_box.setCurrentIndex(i)
294             self._control_group.addControl(index, combo_box)
295         except KeyError:
296             self.exceptionOccurred(self.tr("Define list \"%1\" not found. Check definition files.").arg(value_list))
297             self.pageContent.propertyTable.setItem(index, 1, QTableWidgetItem(value))
298     
299     def insertSpinBox(self, index, value, informations):
300         """
301         Inserts in the table at index a spinbox for an int, a long or an unsigned
302         long property setted to value.
303         """
304         # int, long or undefined type property
305         spin_box = None
306         if bertos_utils.isLong(informations) or bertos_utils.isUnsignedLong(informations):
307             spin_box = QDoubleSpinBox()
308             spin_box.setDecimals(0)
309         else:
310             spin_box = QSpinBox()
311         self.pageContent.propertyTable.setCellWidget(index, 1, spin_box)
312         minimum = -32768
313         maximum = 32767
314         suff = ""
315         if bertos_utils.isLong(informations):
316             minimum = -2147483648
317             maximum = 2147483647
318             suff = "L"
319         elif bertos_utils.isUnsigned(informations):
320             minimum = 0
321             maximum = 65535
322             suff = "U"
323         elif bertos_utils.isUnsignedLong(informations):
324             minimum = 0
325             maximum = 4294967295
326             suff = "UL"
327         if "min" in informations:
328             minimum = int(informations["min"])
329         if "max" in informations:
330             maximum = int(informations["max"])
331         spin_box.setRange(minimum, maximum)
332         spin_box.setSuffix(suff)
333         spin_box.setValue(int(value.replace("L", "").replace("U", "")))
334         self._control_group.addControl(index, spin_box)
335         
336     
337     def currentModule(self):
338         """
339         Retuns the current module name.
340         """
341         current_module = self.pageContent.moduleTree.currentItem()
342         # return only the child items
343         if current_module and current_module.parent():
344             return unicode(current_module.text(0))
345         else:
346             return None
347
348     def moduleItem(self, module):
349         for top_level_index in range(self.pageContent.moduleTree.topLevelItemCount()):
350             top_level_item = self.pageContent.moduleTree.topLevelItem(top_level_index)
351             for child_index in range(top_level_item.childCount()):
352                 child_item = top_level_item.child(child_index)
353                 if unicode(child_item.text(0)) == module:
354                     return child_item
355         return None
356     
357     def currentModuleConfigurations(self):
358         """
359         Returns the current module configuration.
360         """
361         return self.configurations(self.currentModule())
362     
363     def currentProperty(self):
364         """
365         Rerturns the current property from the property table.
366         """
367         return qvariant_converter.getString(self.pageContent.propertyTable.item(self.pageContent.propertyTable.currentRow(), 0).data(Qt.UserRole))
368     
369     def currentPropertyItem(self):
370         """
371         Returns the QTableWidgetItem of the current property.
372         """
373         return self.pageContent.propertyTable.item(self.pageContent.propertyTable.currentRow(), 0)
374     
375     def configurations(self, module):
376         """
377         Returns the configuration for the selected module.
378         """
379         configuration = self.projectInfo("MODULES")[module]["configuration"]
380         if len(configuration) > 0:
381             return self.projectInfo("CONFIGURATIONS")[configuration]
382         else:
383             return {}
384     
385     def resetPropertyDescription(self):
386         """
387         Resets the label for each property table entry.
388         """
389         for index in range(self.pageContent.propertyTable.rowCount()):
390             property_name = qvariant_converter.getString(self.pageContent.propertyTable.item(index, 0).data(Qt.UserRole))
391             # Awful solution! Needed because if the user change the module, the selection changed...
392             if property_name not in self.currentModuleConfigurations():
393                 break
394             self.pageContent.propertyTable.item(index, 0).setText(self.currentModuleConfigurations()[property_name]['brief'])
395     
396     def setBold(self, item, bold):
397         self.pageContent.moduleTree.blockSignals(True)
398         font = item.font(0)
399         font.setBold(bold)
400         item.setFont(0, font)
401         self.pageContent.moduleTree.blockSignals(False)
402
403     def moduleSelected(self, selectedModule):
404         """
405         Resolves the selection dependencies.
406         """
407         try:
408             qApp.setOverrideCursor(Qt.WaitCursor)
409             modules = self.projectInfo("MODULES")
410             modules[selectedModule]["enabled"] = True
411             self.setProjectInfo("MODULES", modules)
412             depends = self.projectInfo("MODULES")[selectedModule]["depends"]
413             unsatisfied = []
414             if self.pageContent.automaticFix.isChecked():
415                 unsatisfied = self.selectDependencyCheck(selectedModule)
416             if len(unsatisfied) > 0:
417                 for module in unsatisfied:
418                     modules = self.projectInfo("MODULES")
419                     modules[module]["enabled"] = True
420                 for category in range(self.pageContent.moduleTree.topLevelItemCount()):
421                     item = self.pageContent.moduleTree.topLevelItem(category)
422                     for child in range(item.childCount()):
423                         if unicode(item.child(child).text(0)) in unsatisfied:
424                             self.setBold(item.child(child), True)
425                             self.setBold(item, True)
426                             item.child(child).setCheckState(0, Qt.Checked)
427         finally:
428             qApp.restoreOverrideCursor()
429     
430     def moduleUnselected(self, unselectedModule):
431         """
432         Resolves the unselection dependencies.
433         """
434         try:
435             qApp.setOverrideCursor(Qt.WaitCursor)
436             modules = self.projectInfo("MODULES")
437             modules[unselectedModule]["enabled"] = False
438             self.setProjectInfo("MODULES", modules)
439             unsatisfied = []
440             unsatisfied_params = []
441             if self.pageContent.automaticFix.isChecked():
442                 unsatisfied, unsatisfied_params = self.unselectDependencyCheck(unselectedModule)
443             if len(unsatisfied) > 0 or len(unsatisfied_params) > 0:
444                 message = []
445                 heading = self.tr("The module %1 is needed by").arg(unselectedModule)
446                 message.append(heading)
447                 module_list = ", ".join(unsatisfied)
448                 param_list = ", ".join(["%s (%s)" %(param_name, module) for module, param_name in unsatisfied_params])
449                 if module_list:
450                     message.append(QString(module_list))
451                 if module_list and param_list:
452                     message.append(self.tr("and by"))
453                 if param_list:
454                     message.append(QString(param_list))
455                 message_str = QStringList(message).join(" ")
456                 message_str.append(self.tr("\n\nDo you want to automatically fix these conflicts?"))
457                 qApp.restoreOverrideCursor()
458                 choice = QMessageBox.warning(self, self.tr("Dependency error"), message_str, QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)
459                 qApp.setOverrideCursor(Qt.WaitCursor)
460                 if choice == QMessageBox.Yes:
461                     for module in unsatisfied:
462                         modules = self.projectInfo("MODULES")
463                         modules[module]["enabled"] = False
464                     for category in range(self.pageContent.moduleTree.topLevelItemCount()):
465                         item = self.pageContent.moduleTree.topLevelItem(category)
466                         for child in range(item.childCount()):
467                             if unicode(item.child(child).text(0)) in unsatisfied:
468                                 item.child(child).setCheckState(0, Qt.Unchecked)
469                     for module, param in unsatisfied_params:
470                         configuration_file = self.projectInfo("MODULES")[module]["configuration"]
471                         configurations = self.projectInfo("CONFIGURATIONS")
472                         configurations[configuration_file][param]["value"] = "0"
473                         self.setProjectInfo("CONFIGURATIONS", configurations)
474         finally:
475             qApp.restoreOverrideCursor()
476     
477     def selectDependencyCheck(self, module):
478         """
479         Returns the list of unsatisfied dependencies after a selection.
480         """
481         unsatisfied = set()
482         modules = self.projectInfo("MODULES")
483         files = self.projectInfo("FILES")
484         configurations = self.projectInfo("CONFIGURATIONS").get(modules[module]["configuration"], {"paramlist": ()})
485         conditional_deps = ()
486         for i, param_name in configurations["paramlist"]:
487             information = configurations[param_name]
488             if information["informations"]["type"] == "boolean" and \
489                 information["value"] != "0" and \
490                 "conditional_deps" in information["informations"]:
491
492                 conditional_deps += information["informations"]["conditional_deps"]
493
494         for dependency in modules[module]["depends"] + conditional_deps:
495             if dependency in modules and not modules[dependency]["enabled"]:
496                 unsatisfied |= set([dependency])
497                 if dependency not in unsatisfied:
498                     unsatisfied |= self.selectDependencyCheck(dependency)
499             if dependency not in modules:
500                 if dependency in files:
501                     files[dependency] += 1
502                 else:
503                     files[dependency] = 1
504         self.setProjectInfo("FILES", files)
505         return unsatisfied
506     
507     def unselectDependencyCheck(self, dependency):
508         """
509         Returns the list of unsatisfied dependencies after an unselection.
510         """
511         unsatisfied = set()
512         unsatisfied_params = set()
513         modules = self.projectInfo("MODULES")
514         for module, informations in modules.items():
515             configurations = self.projectInfo("CONFIGURATIONS").get(informations["configuration"], {"paramlist": ()})
516             conditional_deps = {}
517             for i, param_name in configurations["paramlist"]:
518                 information = configurations[param_name]
519                 if information["informations"]["type"] == "boolean" and information["value"] != "0" and "conditional_deps" in information["informations"]:
520                     for dep in information["informations"]["conditional_deps"]:
521                         if not dep in conditional_deps:
522                             conditional_deps[dep] = []
523                         conditional_deps[dep].append((module, param_name))
524             if dependency in informations["depends"] and informations["enabled"]:
525                 unsatisfied |= set([module])
526                 if dependency not in unsatisfied:
527                     tmp = self.unselectDependencyCheck(module)
528                     unsatisfied |= tmp[0]
529                     unsatisfied_params |= tmp[1]
530             if dependency in conditional_deps:
531                 unsatisfied_params |= set(conditional_deps[dependency])
532         return unsatisfied, unsatisfied_params
533     
534     def removeFileDependencies(self, module):
535         """
536         Removes the files dependencies of the given module.
537         """
538         modules = self.projectInfo("MODULES")
539         files = self.projectInfo("FILES")
540         dependencies = modules[module]["depends"]
541         for dependency in dependencies:
542             if dependency in files:
543                 files[dependency] -= 1
544                 if files[dependency] == 0:
545                     del files[dependency]
546         self.setProjectInfo("FILES", files)
547
548 class QControlGroup(QObject):
549     """
550     Simple class that permit to connect different signals of different widgets
551     with a slot that emit a signal. Permits to group widget and to understand which of
552     them has sent the signal.
553     """
554     
555     def __init__(self):
556         QObject.__init__(self)
557         self._controls = {}
558     
559     def addControl(self, id, control):
560         """
561         Add a control.
562         """
563         self._controls[id] = control
564         if type(control) == QCheckBox:
565             self.connect(control, SIGNAL("stateChanged(int)"), lambda: self.stateChanged(id))
566         elif type(control) == QSpinBox:
567             self.connect(control, SIGNAL("valueChanged(int)"), lambda: self.stateChanged(id))
568         elif type(control) == QComboBox:
569             self.connect(control, SIGNAL("currentIndexChanged(int)"), lambda: self.stateChanged(id))
570         elif type(control) == QDoubleSpinBox:
571             self.connect(control, SIGNAL("valueChanged(double)"), lambda: self.stateChanged(id))
572     
573     def clear(self):
574         """
575         Remove all the controls.
576         """
577         self._controls = {}
578     
579     def stateChanged(self, id):
580         """
581         Slot called when the value of one of the stored widget changes. It emits
582         another signal.
583         """
584         self.emit(SIGNAL("stateChanged"), id)