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