4 # This file is part of BeRTOS.
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.
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.
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
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.
29 # Copyright 2008 Develer S.r.l. (http://www.develer.com/)
33 # Author: Lorenzo Berni <duplo@develer.com>
38 from PyQt4.QtCore import *
39 from PyQt4.QtGui import *
40 from BWizardPage import *
43 from bertos_utils import SupportedException
44 from DefineException import *
47 class BModulePage(BWizardPage):
49 Page of the wizard that permits to select and configurate the BeRTOS modules.
53 BWizardPage.__init__(self, UI_LOCATION + "/module_select.ui")
54 self.setTitle(self.tr("Configure the BeRTOS modules"))
55 self._control_group = QControlGroup()
56 ## special connection needed for the QControlGroup
57 self.connect(self._control_group, SIGNAL("stateChanged"), self.saveValue)
59 ## Overloaded BWizardPage methods ##
63 Overload of BWizardPage setupUi method.
65 self.pageContent.moduleTree.clear()
66 self.pageContent.moduleTree.setHeaderHidden(True)
67 self.pageContent.propertyTable.horizontalHeader().setResizeMode(QHeaderView.Stretch)
68 self.pageContent.propertyTable.horizontalHeader().setVisible(False)
69 self.pageContent.propertyTable.verticalHeader().setResizeMode(QHeaderView.ResizeToContents)
70 self.pageContent.propertyTable.verticalHeader().setVisible(False)
71 self.pageContent.propertyTable.setColumnCount(2)
72 self.pageContent.propertyTable.setRowCount(0)
73 self.pageContent.moduleLabel.setVisible(False)
74 self.pageContent.warningLabel.setVisible(False)
76 def connectSignals(self):
78 Overload of the BWizardPage connectSignals method.
80 self.connect(self.pageContent.moduleTree, SIGNAL("itemPressed(QTreeWidgetItem*, int)"), self.fillPropertyTable)
81 self.connect(self.pageContent.moduleTree, SIGNAL("itemPressed(QTreeWidgetItem*, int)"), self.moduleClicked)
82 self.connect(self.pageContent.moduleTree, SIGNAL("itemChanged(QTreeWidgetItem*, int)"), self.dependencyCheck)
83 self.connect(self.pageContent.propertyTable, SIGNAL("itemSelectionChanged()"), self.showPropertyDescription)
87 Overload of the BWizardPage reloadData method.
90 QApplication.instance().setOverrideCursor(Qt.WaitCursor)
95 QApplication.instance().restoreOverrideCursor()
101 def moduleClicked(self, item, column):
102 self.setBold(item, False)
104 def fillPropertyTable(self):
106 Slot called when the user selects a module from the module tree.
107 Fills the property table using the configuration parameters defined in
110 module = self.currentModule()
113 supported = bertos_utils.isSupported(self.project, module=module)
114 except SupportedException, e:
115 self.exceptionOccurred(self.tr("Error evaluating \"%1\" for module %2").arg(e.support_string).arg(module))
117 self._control_group.clear()
118 configuration = self.projectInfo("MODULES")[module]["configuration"]
119 module_description = self.projectInfo("MODULES")[module]["description"]
120 self.pageContent.moduleLabel.setText(module_description)
121 self.pageContent.moduleLabel.setVisible(True)
123 self.pageContent.warningLabel.setVisible(True)
124 selected_cpu = self.projectInfo("CPU_NAME")
125 self.pageContent.warningLabel.setText(self.tr("<font color='#FF0000'>Warning: the selected module, \
126 is not completely supported by the %1.</font>").arg(selected_cpu))
128 self.pageContent.warningLabel.setVisible(False)
129 self.pageContent.propertyTable.clear()
130 self.pageContent.propertyTable.setRowCount(0)
131 if configuration != "":
132 configurations = self.projectInfo("CONFIGURATIONS")[configuration]
133 param_list = sorted(configurations["paramlist"])
135 for i, property in param_list:
136 if "type" in configurations[property]["informations"] and configurations[property]["informations"]["type"] == "autoenabled":
137 # Doesn't show the hidden fields
140 param_supported = bertos_utils.isSupported(self.project, property_id=(configuration, property))
141 except SupportedException, e:
142 self.exceptionOccurred(self.tr("Error evaluating \"%1\" for parameter %2").arg(e.support_string).arg(property))
143 param_supported = True
144 if not param_supported:
145 # Doesn't show the unsupported parameters
147 # Set the row count to the current index + 1
148 self.pageContent.propertyTable.setRowCount(index + 1)
149 item = QTableWidgetItem(configurations[property]["brief"])
150 item.setData(Qt.UserRole, qvariant_converter.convertString(property))
151 self.pageContent.propertyTable.setItem(index, 0, item)
152 if "type" in configurations[property]["informations"] and configurations[property]["informations"]["type"] == "boolean":
153 self.insertCheckBox(index, configurations[property]["value"])
154 elif "type" in configurations[property]["informations"] and configurations[property]["informations"]["type"] == "enum":
155 self.insertComboBox(index, configurations[property]["value"], configurations[property]["informations"]["value_list"])
156 elif "type" in configurations[property]["informations"] and configurations[property]["informations"]["type"] == "int":
157 self.insertSpinBox(index, configurations[property]["value"], configurations[property]["informations"])
159 # Not defined type, rendered as a text field
160 self.pageContent.propertyTable.setItem(index, 1, QTableWidgetItem(configurations[property]["value"]))
162 if self.pageContent.propertyTable.rowCount() == 0:
163 module_label = self.pageContent.moduleLabel.text()
164 module_label += "\n\nNo configuration needed."
165 self.pageContent.moduleLabel.setText(module_label)
167 self.pageContent.moduleLabel.setText("")
168 self.pageContent.moduleLabel.setVisible(False)
169 self.pageContent.propertyTable.clear()
170 self.pageContent.propertyTable.setRowCount(0)
172 def dependencyCheck(self, item):
174 Checks the dependencies of the module associated with the given item.
177 module = unicode(item.text(0))
178 if item.checkState(0) == Qt.Checked:
179 self.moduleSelected(module)
181 self.moduleUnselected(module)
182 self.removeFileDependencies(module)
184 def showPropertyDescription(self):
186 Slot called when the property selection changes. Shows the description
187 of the selected property.
189 self.resetPropertyDescription()
190 configurations = self.currentModuleConfigurations()
191 if self.currentProperty() in configurations:
192 description = configurations[self.currentProperty()]["brief"]
193 name = self.currentProperty()
194 self.currentPropertyItem().setText(description + "\n" + name)
196 def saveValue(self, index):
198 Slot called when the user modifies one of the configuration parameters.
199 It stores the new value."""
200 property = qvariant_converter.getString(self.pageContent.propertyTable.item(index, 0).data(Qt.UserRole))
201 configuration = self.projectInfo("MODULES")[self.currentModule()]["configuration"]
202 configurations = self.projectInfo("CONFIGURATIONS")
203 if "type" not in configurations[configuration][property]["informations"] or configurations[configuration][property]["informations"]["type"] == "int":
204 configurations[configuration][property]["value"] = unicode(int(self.pageContent.propertyTable.cellWidget(index, 1).value()))
205 elif configurations[configuration][property]["informations"]["type"] == "enum":
206 configurations[configuration][property]["value"] = unicode(self.pageContent.propertyTable.cellWidget(index, 1).currentText())
207 elif configurations[configuration][property]["informations"]["type"] == "boolean":
208 if self.pageContent.propertyTable.cellWidget(index, 1).isChecked():
209 configurations[configuration][property]["value"] = "1"
211 configurations[configuration][property]["value"] = "0"
212 self.setProjectInfo("CONFIGURATIONS", configurations)
213 if self.moduleItem(self.currentModule()).checkState(0) == Qt.Checked:
214 self.dependencyCheck(self.moduleItem(self.currentModule()))
218 def loadModuleData(self):
220 Loads the module data.
222 # Do not load the module data again when the Wizard is in editing mode
223 # or when it's working on a preset.
224 if not self.project.edit and not self.project.from_preset:
225 # Load the module data every time so that if the user changed the cpu
226 # the right configurations are picked up.
228 self.project.loadModuleData()
229 except ModuleDefineException, e:
230 self.exceptionOccurred(self.tr("Error parsing line '%2' in file %1").arg(e.path).arg(e.line))
231 except EnumDefineException, e:
232 self.exceptionOccurred(self.tr("Error parsing line '%2' in file %1").arg(e.path).arg(e.line))
233 except ConfigurationDefineException, e:
234 self.exceptionOccurred(self.tr("Error parsing line '%2' in file %1").arg(e.path).arg(e.line))
236 def fillModuleTree(self):
238 Fills the module tree with the module entries separated in categories.
240 self.pageContent.moduleTree.clear()
241 modules = self.projectInfo("MODULES")
245 for module, information in modules.items():
246 if information["category"] not in categories:
247 categories[information["category"]] = []
248 categories[information["category"]].append(module)
249 for category, module_list in categories.items():
250 item = QTreeWidgetItem(QStringList([category]))
251 for module in module_list:
252 enabled = modules[module]["enabled"]
253 module_item = QTreeWidgetItem(item, QStringList([module]))
255 supported = bertos_utils.isSupported(self.project, module=module)
256 except SupportedException, e:
257 self.exceptionOccurred(self.tr("Error evaluating \"%1\" for module %2").arg(e.support_string).arg(module))
260 module_item.setForeground(0, QBrush(QColor(Qt.red)))
262 module_item.setCheckState(0, Qt.Checked)
264 module_item.setCheckState(0, Qt.Unchecked)
265 self.pageContent.moduleTree.addTopLevelItem(item)
266 self.pageContent.moduleTree.sortItems(0, Qt.AscendingOrder)
267 self.fillPropertyTable()
269 def insertCheckBox(self, index, value):
271 Inserts in the table at index a checkbox for a boolean property setted
274 check_box = QCheckBox()
275 self.pageContent.propertyTable.setCellWidget(index, 1, check_box)
277 check_box.setChecked(True)
279 check_box.setChecked(False)
280 self._control_group.addControl(index, check_box)
282 def insertComboBox(self, index, value, value_list):
284 Inserts in the table at index a combobox for an enum property setted
288 enum = self.projectInfo("LISTS")[value_list]
289 combo_box = QComboBox()
290 self.pageContent.propertyTable.setCellWidget(index, 1, combo_box)
291 for i, element in enumerate(enum):
292 combo_box.addItem(element)
294 combo_box.setCurrentIndex(i)
295 self._control_group.addControl(index, combo_box)
297 self.exceptionOccurred(self.tr("Define list \"%1\" not found. Check definition files.").arg(value_list))
298 self.pageContent.propertyTable.setItem(index, 1, QTableWidgetItem(value))
300 def insertSpinBox(self, index, value, informations):
302 Inserts in the table at index a spinbox for an int, a long or an unsigned
303 long property setted to value.
305 # int, long or undefined type property
307 if bertos_utils.isLong(informations) or bertos_utils.isUnsignedLong(informations):
308 spin_box = QDoubleSpinBox()
309 spin_box.setDecimals(0)
311 spin_box = QSpinBox()
312 self.pageContent.propertyTable.setCellWidget(index, 1, spin_box)
316 if bertos_utils.isLong(informations):
317 minimum = -2147483648
320 elif bertos_utils.isUnsigned(informations):
324 elif bertos_utils.isUnsignedLong(informations):
328 if "min" in informations:
329 minimum = int(informations["min"])
330 if "max" in informations:
331 maximum = int(informations["max"])
332 spin_box.setRange(minimum, maximum)
333 spin_box.setSuffix(suff)
334 spin_box.setValue(int(value.replace("L", "").replace("U", "")))
335 self._control_group.addControl(index, spin_box)
338 def currentModule(self):
340 Retuns the current module name.
342 current_module = self.pageContent.moduleTree.currentItem()
343 # return only the child items
344 if current_module and current_module.parent():
345 return unicode(current_module.text(0))
349 def moduleItem(self, module):
350 for top_level_index in range(self.pageContent.moduleTree.topLevelItemCount()):
351 top_level_item = self.pageContent.moduleTree.topLevelItem(top_level_index)
352 for child_index in range(top_level_item.childCount()):
353 child_item = top_level_item.child(child_index)
354 if unicode(child_item.text(0)) == module:
358 def currentModuleConfigurations(self):
360 Returns the current module configuration.
362 return self.configurations(self.currentModule())
364 def currentProperty(self):
366 Rerturns the current property from the property table.
368 return qvariant_converter.getString(self.pageContent.propertyTable.item(self.pageContent.propertyTable.currentRow(), 0).data(Qt.UserRole))
370 def currentPropertyItem(self):
372 Returns the QTableWidgetItem of the current property.
374 return self.pageContent.propertyTable.item(self.pageContent.propertyTable.currentRow(), 0)
376 def configurations(self, module):
378 Returns the configuration for the selected module.
382 # On linux platform it seems that the behaviour of the focus
383 # changing is a bit different from the mac one. So if module is
384 # None then no configurations should be returned.
385 configuration = self.projectInfo("MODULES")[module]["configuration"]
386 if len(configuration) > 0:
387 return self.projectInfo("CONFIGURATIONS")[configuration]
391 def resetPropertyDescription(self):
393 Resets the label for each property table entry.
395 for index in range(self.pageContent.propertyTable.rowCount()):
396 property_name = qvariant_converter.getString(self.pageContent.propertyTable.item(index, 0).data(Qt.UserRole))
397 # Awful solution! Needed because if the user change the module, the selection changed...
398 if property_name not in self.currentModuleConfigurations():
400 self.pageContent.propertyTable.item(index, 0).setText(self.currentModuleConfigurations()[property_name]['brief'])
402 def setBold(self, item, bold):
403 self.pageContent.moduleTree.blockSignals(True)
406 item.setFont(0, font)
407 self.pageContent.moduleTree.blockSignals(False)
409 def moduleSelected(self, selectedModule):
411 Resolves the selection dependencies.
414 qApp.setOverrideCursor(Qt.WaitCursor)
415 modules = self.projectInfo("MODULES")
416 modules[selectedModule]["enabled"] = True
417 self.setProjectInfo("MODULES", modules)
418 depends = self.projectInfo("MODULES")[selectedModule]["depends"]
420 if self.pageContent.automaticFix.isChecked():
421 unsatisfied = self.selectDependencyCheck(selectedModule)
422 if len(unsatisfied) > 0:
423 for module in unsatisfied:
424 modules = self.projectInfo("MODULES")
425 modules[module]["enabled"] = True
426 for category in range(self.pageContent.moduleTree.topLevelItemCount()):
427 item = self.pageContent.moduleTree.topLevelItem(category)
428 for child in range(item.childCount()):
429 if unicode(item.child(child).text(0)) in unsatisfied:
430 self.setBold(item.child(child), True)
431 self.setBold(item, True)
432 item.child(child).setCheckState(0, Qt.Checked)
434 qApp.restoreOverrideCursor()
436 def moduleUnselected(self, unselectedModule):
438 Resolves the unselection dependencies.
441 qApp.setOverrideCursor(Qt.WaitCursor)
442 modules = self.projectInfo("MODULES")
443 modules[unselectedModule]["enabled"] = False
444 self.setProjectInfo("MODULES", modules)
446 unsatisfied_params = []
447 if self.pageContent.automaticFix.isChecked():
448 unsatisfied, unsatisfied_params = self.unselectDependencyCheck(unselectedModule)
449 if len(unsatisfied) > 0 or len(unsatisfied_params) > 0:
451 heading = self.tr("The module %1 is needed by").arg(unselectedModule)
452 message.append(heading)
453 module_list = ", ".join(unsatisfied)
454 param_list = ", ".join(["%s (%s)" %(param_name, module) for module, param_name in unsatisfied_params])
456 message.append(QString(module_list))
457 if module_list and param_list:
458 message.append(self.tr("and by"))
460 message.append(QString(param_list))
461 message_str = QStringList(message).join(" ")
462 message_str.append(self.tr("\n\nDo you want to automatically fix these conflicts?"))
463 qApp.restoreOverrideCursor()
464 choice = QMessageBox.warning(self, self.tr("Dependency error"), message_str, QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)
465 qApp.setOverrideCursor(Qt.WaitCursor)
466 if choice == QMessageBox.Yes:
467 for module in unsatisfied:
468 modules = self.projectInfo("MODULES")
469 modules[module]["enabled"] = False
470 for category in range(self.pageContent.moduleTree.topLevelItemCount()):
471 item = self.pageContent.moduleTree.topLevelItem(category)
472 for child in range(item.childCount()):
473 if unicode(item.child(child).text(0)) in unsatisfied:
474 item.child(child).setCheckState(0, Qt.Unchecked)
475 for module, param in unsatisfied_params:
476 configuration_file = self.projectInfo("MODULES")[module]["configuration"]
477 configurations = self.projectInfo("CONFIGURATIONS")
478 configurations[configuration_file][param]["value"] = "0"
479 self.setProjectInfo("CONFIGURATIONS", configurations)
481 qApp.restoreOverrideCursor()
483 def selectDependencyCheck(self, module):
485 Returns the list of unsatisfied dependencies after a selection.
488 modules = self.projectInfo("MODULES")
489 files = self.projectInfo("FILES")
490 configurations = self.projectInfo("CONFIGURATIONS").get(modules[module]["configuration"], {"paramlist": ()})
491 conditional_deps = ()
492 for i, param_name in configurations["paramlist"]:
493 information = configurations[param_name]
494 if information["informations"]["type"] == "boolean" and \
495 information["value"] != "0" and \
496 "conditional_deps" in information["informations"]:
498 conditional_deps += information["informations"]["conditional_deps"]
500 for dependency in modules[module]["depends"] + conditional_deps:
501 if dependency in modules and not modules[dependency]["enabled"]:
502 unsatisfied |= set([dependency])
503 if dependency not in unsatisfied:
504 unsatisfied |= self.selectDependencyCheck(dependency)
505 if dependency not in modules:
506 if dependency in files:
507 files[dependency] += 1
509 files[dependency] = 1
510 self.setProjectInfo("FILES", files)
513 def unselectDependencyCheck(self, dependency):
515 Returns the list of unsatisfied dependencies after an unselection.
518 unsatisfied_params = set()
519 modules = self.projectInfo("MODULES")
520 for module, informations in modules.items():
521 configurations = self.projectInfo("CONFIGURATIONS").get(informations["configuration"], {"paramlist": ()})
522 conditional_deps = {}
523 for i, param_name in configurations["paramlist"]:
524 information = configurations[param_name]
525 if information["informations"]["type"] == "boolean" and information["value"] != "0" and "conditional_deps" in information["informations"]:
526 for dep in information["informations"]["conditional_deps"]:
527 if not dep in conditional_deps:
528 conditional_deps[dep] = []
529 conditional_deps[dep].append((module, param_name))
530 if dependency in informations["depends"] and informations["enabled"]:
531 unsatisfied |= set([module])
532 if dependency not in unsatisfied:
533 tmp = self.unselectDependencyCheck(module)
534 unsatisfied |= tmp[0]
535 unsatisfied_params |= tmp[1]
536 if dependency in conditional_deps:
537 unsatisfied_params |= set(conditional_deps[dependency])
538 return unsatisfied, unsatisfied_params
540 def removeFileDependencies(self, module):
542 Removes the files dependencies of the given module.
544 modules = self.projectInfo("MODULES")
545 files = self.projectInfo("FILES")
546 dependencies = modules[module]["depends"]
547 for dependency in dependencies:
548 if dependency in files:
549 files[dependency] -= 1
550 if files[dependency] == 0:
551 del files[dependency]
552 self.setProjectInfo("FILES", files)
554 class QControlGroup(QObject):
556 Simple class that permit to connect different signals of different widgets
557 with a slot that emit a signal. Permits to group widget and to understand which of
558 them has sent the signal.
562 QObject.__init__(self)
565 def addControl(self, id, control):
569 self._controls[id] = control
570 if type(control) == QCheckBox:
571 self.connect(control, SIGNAL("stateChanged(int)"), lambda: self.stateChanged(id))
572 elif type(control) == QSpinBox:
573 self.connect(control, SIGNAL("valueChanged(int)"), lambda: self.stateChanged(id))
574 elif type(control) == QComboBox:
575 self.connect(control, SIGNAL("currentIndexChanged(int)"), lambda: self.stateChanged(id))
576 elif type(control) == QDoubleSpinBox:
577 self.connect(control, SIGNAL("valueChanged(double)"), lambda: self.stateChanged(id))
581 Remove all the controls.
585 def stateChanged(self, id):
587 Slot called when the value of one of the stored widget changes. It emits
590 self.emit(SIGNAL("stateChanged"), id)