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