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