Change the settings merge function
[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
160     def dependencyCheck(self, item):
161         """
162         Checks the dependencies of the module associated with the given item.
163         """
164         checked = False
165         module = unicode(item.text(0))
166         if item.checkState(0) == Qt.Checked:
167             self.moduleSelected(module)
168         else:
169             self.moduleUnselected(module)
170             self.removeFileDependencies(module)
171
172     def showPropertyDescription(self):
173         """
174         Slot called when the property selection changes. Shows the description
175         of the selected property.
176         """
177         self.resetPropertyDescription()
178         configurations = self.currentModuleConfigurations()
179         if self.currentProperty() in configurations:
180             description = configurations[self.currentProperty()]["brief"]
181             name = self.currentProperty()
182             self.currentPropertyItem().setText(description + "\n" + name)
183
184     def saveValue(self, index):
185         """
186         Slot called when the user modifies one of the configuration parameters.
187         It stores the new value."""
188         property = qvariant_converter.getString(self.pageContent.propertyTable.item(index, 0).data(Qt.UserRole))
189         configuration = self.projectInfo("MODULES")[self.currentModule()]["configuration"]
190         configurations = self.projectInfo("CONFIGURATIONS")
191         if "type" not in configurations[configuration][property]["informations"] or configurations[configuration][property]["informations"]["type"] == "int":
192             configurations[configuration][property]["value"] = unicode(int(self.pageContent.propertyTable.cellWidget(index, 1).value()))
193         elif configurations[configuration][property]["informations"]["type"] == "enum":
194             configurations[configuration][property]["value"] = unicode(self.pageContent.propertyTable.cellWidget(index, 1).currentText())
195         elif configurations[configuration][property]["informations"]["type"] == "boolean":
196             if self.pageContent.propertyTable.cellWidget(index, 1).isChecked():
197                 configurations[configuration][property]["value"] = "1"
198             else:
199                 configurations[configuration][property]["value"] = "0"
200         self.setProjectInfo("CONFIGURATIONS", configurations)
201
202     ####
203     
204     def loadModuleData(self):
205         """
206         Loads the module data.
207         """
208         # Load the module data only if it isn't already loaded
209         if not self.projectInfo("MODULES") \
210                 and not self.projectInfo("LISTS") \
211                 and not self.projectInfo("CONFIGURATIONS"):
212             try:
213                 bertos_utils.loadModuleData(self.project())
214             except ModuleDefineException, e:
215                 self.exceptionOccurred(self.tr("Error parsing line '%2' in file %1").arg(e.path).arg(e.line))
216             except EnumDefineException, e:
217                 self.exceptionOccurred(self.tr("Error parsing line '%2' in file %1").arg(e.path).arg(e.line))
218             except ConfigurationDefineException, e:
219                 self.exceptionOccurred(self.tr("Error parsing line '%2' in file %1").arg(e.path).arg(e.line))
220     
221     def fillModuleTree(self):
222         """
223         Fills the module tree with the module entries separated in categories.
224         """
225         self.pageContent.moduleTree.clear()
226         modules = self.projectInfo("MODULES")
227         if not modules:
228             return
229         categories = {}
230         for module, information in modules.items():
231             if information["category"] not in categories:
232                 categories[information["category"]] = []
233             categories[information["category"]].append(module)
234         for category, module_list in categories.items():
235             item = QTreeWidgetItem(QStringList([category]))
236             for module in module_list:
237                 enabled = modules[module]["enabled"]
238                 module_item = QTreeWidgetItem(item, QStringList([module]))
239                 try:
240                     supported = bertos_utils.isSupported(self.project(), module=module)
241                 except SupportedException, e:
242                     self.exceptionOccurred(self.tr("Error evaluating \"%1\" for module %2").arg(e.support_string).arg(module))
243                     supported = True
244                 if not supported:
245                     module_item.setForeground(0, QBrush(QColor(Qt.red)))
246                 if enabled:
247                     module_item.setCheckState(0, Qt.Checked)
248                 else:
249                     module_item.setCheckState(0, Qt.Unchecked)
250             self.pageContent.moduleTree.addTopLevelItem(item)
251         self.pageContent.moduleTree.sortItems(0, Qt.AscendingOrder)
252             
253     def insertCheckBox(self, index, value):
254         """
255         Inserts in the table at index a checkbox for a boolean property setted
256         to value.
257         """
258         check_box = QCheckBox()
259         self.pageContent.propertyTable.setCellWidget(index, 1, check_box)
260         if value == "1":
261             check_box.setChecked(True)
262         else:
263             check_box.setChecked(False)
264         self._control_group.addControl(index, check_box)
265     
266     def insertComboBox(self, index, value, value_list):
267         """
268         Inserts in the table at index a combobox for an enum property setted
269         to value.
270         """
271         try:
272             enum = self.projectInfo("LISTS")[value_list]
273             combo_box = QComboBox()
274             self.pageContent.propertyTable.setCellWidget(index, 1, combo_box)
275             for i, element in enumerate(enum):
276                 combo_box.addItem(element)
277                 if element == value:
278                     combo_box.setCurrentIndex(i)
279             self._control_group.addControl(index, combo_box)
280         except KeyError:
281             self.exceptionOccurred(self.tr("Define list \"%1\" not found. Check definition files.").arg(value_list))
282             self.pageContent.propertyTable.setItem(index, 1, QTableWidgetItem(value))
283     
284     def insertSpinBox(self, index, value, informations):
285         """
286         Inserts in the table at index a spinbox for an int, a long or an unsigned
287         long property setted to value.
288         """
289         # int, long or undefined type property
290         spin_box = None
291         if bertos_utils.isLong(informations) or bertos_utils.isUnsignedLong(informations):
292             spin_box = QDoubleSpinBox()
293             spin_box.setDecimals(0)
294         else:
295             spin_box = QSpinBox()
296         self.pageContent.propertyTable.setCellWidget(index, 1, spin_box)
297         minimum = -32768
298         maximum = 32767
299         suff = ""
300         if bertos_utils.isLong(informations):
301             minimum = -2147483648
302             maximum = 2147483647
303             suff = "L"
304         elif bertos_utils.isUnsigned(informations):
305             minimum = 0
306             maximum = 65535
307             suff = "U"
308         elif bertos_utils.isUnsignedLong(informations):
309             minimum = 0
310             maximum = 4294967295
311             suff = "UL"
312         if "min" in informations:
313             minimum = int(informations["min"])
314         if "max" in informations:
315             maximum = int(informations["max"])
316         spin_box.setRange(minimum, maximum)
317         spin_box.setSuffix(suff)
318         spin_box.setValue(int(value.replace("L", "").replace("U", "")))
319         self._control_group.addControl(index, spin_box)
320         
321     
322     def currentModule(self):
323         """
324         Retuns the current module name.
325         """
326         current_module = self.pageContent.moduleTree.currentItem()
327         # return only the child items
328         if current_module and current_module.parent():
329             return unicode(current_module.text(0))
330         else:
331             return None
332     
333     def currentModuleConfigurations(self):
334         """
335         Returns the current module configuration.
336         """
337         return self.configurations(self.currentModule())
338     
339     def currentProperty(self):
340         """
341         Rerturns the current property from the property table.
342         """
343         return qvariant_converter.getString(self.pageContent.propertyTable.item(self.pageContent.propertyTable.currentRow(), 0).data(Qt.UserRole))
344     
345     def currentPropertyItem(self):
346         """
347         Returns the QTableWidgetItem of the current property.
348         """
349         return self.pageContent.propertyTable.item(self.pageContent.propertyTable.currentRow(), 0)
350     
351     def configurations(self, module):
352         """
353         Returns the configuration for the selected module.
354         """
355         configuration = self.projectInfo("MODULES")[module]["configuration"]
356         if len(configuration) > 0:
357             return self.projectInfo("CONFIGURATIONS")[configuration]
358         else:
359             return {}
360     
361     def resetPropertyDescription(self):
362         """
363         Resets the label for each property table entry.
364         """
365         for index in range(self.pageContent.propertyTable.rowCount()):
366             property_name = qvariant_converter.getString(self.pageContent.propertyTable.item(index, 0).data(Qt.UserRole))
367             # Awful solution! Needed because if the user change the module, the selection changed...
368             if property_name not in self.currentModuleConfigurations():
369                 break
370             self.pageContent.propertyTable.item(index, 0).setText(self.currentModuleConfigurations()[property_name]['brief'])
371     
372     def moduleSelected(self, selectedModule):
373         """
374         Resolves the selection dependencies.
375         """
376         modules = self.projectInfo("MODULES")
377         modules[selectedModule]["enabled"] = True
378         self.setProjectInfo("MODULES", modules)
379         depends = self.projectInfo("MODULES")[selectedModule]["depends"]
380         unsatisfied = []
381         if self.pageContent.automaticFix.isChecked():
382             unsatisfied = self.selectDependencyCheck(selectedModule)
383         if len(unsatisfied) > 0:
384             for module in unsatisfied:
385                 modules = self.projectInfo("MODULES")
386                 modules[module]["enabled"] = True
387             for category in range(self.pageContent.moduleTree.topLevelItemCount()):
388                 item = self.pageContent.moduleTree.topLevelItem(category)
389                 for child in range(item.childCount()):
390                     if unicode(item.child(child).text(0)) in unsatisfied:
391                         item.child(child).setCheckState(0, Qt.Checked)
392     
393     def moduleUnselected(self, unselectedModule):
394         """
395         Resolves the unselection dependencies.
396         """
397         modules = self.projectInfo("MODULES")
398         modules[unselectedModule]["enabled"] = False
399         self.setProjectInfo("MODULES", modules)
400         unsatisfied = []
401         if self.pageContent.automaticFix.isChecked():
402             unsatisfied = self.unselectDependencyCheck(unselectedModule)
403         if len(unsatisfied) > 0:
404             message = self.tr("The module %1 is needed by the following modules:\n%2.\n\nDo you want to remove these modules too?")
405             message = message.arg(unselectedModule).arg(", ".join(unsatisfied))
406             choice = QMessageBox.warning(self, self.tr("Dependency error"), message, QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)
407             if choice == QMessageBox.Yes:
408                 for module in unsatisfied:
409                     modules = self.projectInfo("MODULES")
410                     modules[module]["enabled"] = False
411                 for category in range(self.pageContent.moduleTree.topLevelItemCount()):
412                     item = self.pageContent.moduleTree.topLevelItem(category)
413                     for child in range(item.childCount()):
414                         if unicode(item.child(child).text(0)) in unsatisfied:
415                             item.child(child).setCheckState(0, Qt.Unchecked)
416     
417     def selectDependencyCheck(self, module):
418         """
419         Returns the list of unsatisfied dependencies after a selection.
420         """
421         unsatisfied = set()
422         modules = self.projectInfo("MODULES")
423         files = self.projectInfo("FILES")
424         for dependency in modules[module]["depends"]:
425             if dependency in modules and not modules[dependency]["enabled"]:
426                 unsatisfied |= set([dependency])
427                 if dependency not in unsatisfied:
428                     unsatisfied |= self.selectDependencyCheck(dependency)
429             if dependency not in modules:
430                 if dependency in files:
431                     files[dependency] += 1
432                 else:
433                     files[dependency] = 1
434         self.setProjectInfo("FILES", files)
435         return unsatisfied
436     
437     def unselectDependencyCheck(self, dependency):
438         """
439         Returns the list of unsatisfied dependencies after an unselection.
440         """
441         unsatisfied = set()
442         modules = self.projectInfo("MODULES")
443         for module, informations in modules.items():
444             if dependency in informations["depends"] and informations["enabled"]:
445                 unsatisfied |= set([module])
446                 if dependency not in unsatisfied:
447                     unsatisfied |= self.unselectDependencyCheck(module)
448         return unsatisfied
449     
450     def removeFileDependencies(self, module):
451         """
452         Removes the files dependencies of the given module.
453         """
454         modules = self.projectInfo("MODULES")
455         files = self.projectInfo("FILES")
456         dependencies = modules[module]["depends"]
457         for dependency in dependencies:
458             if dependency in files:
459                 files[dependency] -= 1
460                 if files[dependency] == 0:
461                     del files[dependency]
462         self.setProjectInfo("FILES", files)
463
464 class QControlGroup(QObject):
465     """
466     Simple class that permit to connect different signals of different widgets
467     with a slot that emit a signal. Permits to group widget and to understand which of
468     them has sent the signal.
469     """
470     
471     def __init__(self):
472         QObject.__init__(self)
473         self._controls = {}
474     
475     def addControl(self, id, control):
476         """
477         Add a control.
478         """
479         self._controls[id] = control
480         if type(control) == QCheckBox:
481             self.connect(control, SIGNAL("stateChanged(int)"), lambda: self.stateChanged(id))
482         elif type(control) == QSpinBox:
483             self.connect(control, SIGNAL("valueChanged(int)"), lambda: self.stateChanged(id))
484         elif type(control) == QComboBox:
485             self.connect(control, SIGNAL("currentIndexChanged(int)"), lambda: self.stateChanged(id))
486         elif type(control) == QDoubleSpinBox:
487             self.connect(control, SIGNAL("valueChanged(double)"), lambda: self.stateChanged(id))
488     
489     def clear(self):
490         """
491         Remove all the controls.
492         """
493         self._controls = {}
494     
495     def stateChanged(self, id):
496         """
497         Slot called when the value of one of the stored widget changes. It emits
498         another signal.
499         """
500         self.emit(SIGNAL("stateChanged"), id)