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/)
32 # Author: Lorenzo Berni <duplo@develer.com>
37 from PyQt4.QtCore import *
38 from PyQt4.QtGui import *
39 from BWizardPage import *
42 from bertos_utils import SupportedException
43 from DefineException import *
46 class BModulePage(BWizardPage):
48 Page of the wizard that permits to select and configurate the BeRTOS modules.
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)
58 ## Overloaded BWizardPage methods ##
62 Overload of BWizardPage setupUi method.
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)
75 def connectSignals(self):
77 Overload of the BWizardPage connectSignals method.
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)
83 def reloadData(self, previous_id=None):
85 Overload of the BWizardPage reloadData method.
87 # Check if the user are approaching this page from the previous or the
89 if previous_id is None or previous_id < self.wizard().currentId():
91 QApplication.instance().setOverrideCursor(Qt.WaitCursor)
96 QApplication.instance().restoreOverrideCursor()
102 def moduleClicked(self, item, column):
103 self.setBold(item, False)
105 def fillPropertyTable(self):
107 Slot called when the user selects a module from the module tree.
108 Fills the property table using the configuration parameters defined in
111 module = self.currentModule()
114 supported = bertos_utils.isSupported(self.project, module=module)
115 except SupportedException, e:
116 self.exceptionOccurred(self.tr("Error evaluating \"%1\" for module %2").arg(e.support_string).arg(module))
118 self._control_group.clear()
119 configuration = self.projectInfo("MODULES")[module]["configuration"]
120 module_description = self.projectInfo("MODULES")[module]["description"]
121 self.pageContent.moduleLabel.setText(module_description)
122 self.pageContent.moduleLabel.setVisible(True)
124 self.pageContent.warningLabel.setVisible(True)
125 selected_cpu = self.projectInfo("CPU_NAME")
126 self.pageContent.warningLabel.setText(self.tr("<font color='#FF0000'>Warning: the selected module, \
127 is not completely supported by the %1.</font>").arg(selected_cpu))
129 self.pageContent.warningLabel.setVisible(False)
130 self.pageContent.propertyTable.clear()
131 self.pageContent.propertyTable.setRowCount(0)
132 if configuration != "":
133 configurations = self.projectInfo("CONFIGURATIONS")[configuration]
134 param_list = sorted(configurations["paramlist"])
136 for i, property in param_list:
137 if "type" in configurations[property]["informations"] and configurations[property]["informations"]["type"] == "autoenabled":
138 # Doesn't show the hidden fields
141 param_supported = bertos_utils.isSupported(self.project, property_id=(configuration, property))
142 except SupportedException, e:
143 self.exceptionOccurred(self.tr("Error evaluating \"%1\" for parameter %2").arg(e.support_string).arg(property))
144 param_supported = True
145 if not param_supported:
146 # Doesn't show the unsupported parameters
148 # Set the row count to the current index + 1
149 self.pageContent.propertyTable.setRowCount(index + 1)
150 item = QTableWidgetItem(configurations[property]["brief"])
151 item.setFlags(item.flags() & ~Qt.ItemIsSelectable)
153 description = configurations[property].get("description", None)
155 tooltip = tooltip + ": " + description
156 item.setToolTip(tooltip)
157 item.setData(Qt.UserRole, qvariant_converter.convertString(property))
158 self.pageContent.propertyTable.setItem(index, 0, item)
159 if "type" in configurations[property]["informations"] and configurations[property]["informations"]["type"] == "boolean":
160 self.insertCheckBox(index, configurations[property]["value"])
161 elif "type" in configurations[property]["informations"] and configurations[property]["informations"]["type"] == "enum":
162 self.insertComboBox(index, configurations[property]["value"], configurations[property]["informations"]["value_list"])
163 elif "type" in configurations[property]["informations"] and configurations[property]["informations"]["type"] == "int":
164 self.insertSpinBox(index, configurations[property]["value"], configurations[property]["informations"])
166 # Not defined type, rendered as a text field
167 self.pageContent.propertyTable.setItem(index, 1, QTableWidgetItem(configurations[property]["value"]))
169 if self.pageContent.propertyTable.rowCount() == 0:
170 module_label = self.pageContent.moduleLabel.text()
171 module_label += "\n\nNo configuration needed."
172 self.pageContent.moduleLabel.setText(module_label)
174 self.pageContent.moduleLabel.setText("")
175 self.pageContent.moduleLabel.setVisible(False)
176 self.pageContent.propertyTable.clear()
177 self.pageContent.propertyTable.setRowCount(0)
179 def dependencyCheck(self, item):
181 Checks the dependencies of the module associated with the given item.
184 module = unicode(item.text(0))
185 if item.checkState(0) == Qt.Checked:
186 self.moduleSelected(module)
188 self.moduleUnselected(module)
189 self.removeFileDependencies(module)
191 def showPropertyDescription(self):
193 Slot called when the property selection changes. Shows the description
194 of the selected property.
196 self.resetPropertyDescription()
197 configurations = self.currentModuleConfigurations()
198 if self.currentProperty() in configurations:
199 description = configurations[self.currentProperty()]["brief"]
200 name = self.currentProperty()
201 self.currentPropertyItem().setText(description + "\n" + name)
203 def saveValue(self, index):
205 Slot called when the user modifies one of the configuration parameters.
206 It stores the new value."""
207 property = qvariant_converter.getString(self.pageContent.propertyTable.item(index, 0).data(Qt.UserRole))
208 configuration = self.projectInfo("MODULES")[self.currentModule()]["configuration"]
209 configurations = self.projectInfo("CONFIGURATIONS")
210 if "type" not in configurations[configuration][property]["informations"] or configurations[configuration][property]["informations"]["type"] == "int":
211 configurations[configuration][property]["value"] = unicode(int(self.pageContent.propertyTable.cellWidget(index, 1).value()))
212 elif configurations[configuration][property]["informations"]["type"] == "enum":
213 configurations[configuration][property]["value"] = unicode(self.pageContent.propertyTable.cellWidget(index, 1).currentText())
214 elif configurations[configuration][property]["informations"]["type"] == "boolean":
215 if self.pageContent.propertyTable.cellWidget(index, 1).isChecked():
216 configurations[configuration][property]["value"] = "1"
218 configurations[configuration][property]["value"] = "0"
219 self.setProjectInfo("CONFIGURATIONS", configurations)
220 if self.moduleItem(self.currentModule()).checkState(0) == Qt.Checked:
221 self.dependencyCheck(self.moduleItem(self.currentModule()))
225 def loadModuleData(self):
227 Loads the module data.
229 # Do not load the module data again when the Wizard is in editing mode
230 # or when it's working on a preset.
231 if not self.project.edit and not self.project.from_preset:
232 # Load the module data every time so that if the user changed the cpu
233 # the right configurations are picked up.
235 self.project.loadModuleData()
236 except ModuleDefineException, e:
237 self.exceptionOccurred(self.tr("Error parsing line '%2' in file %1").arg(e.path).arg(e.line))
238 except EnumDefineException, e:
239 self.exceptionOccurred(self.tr("Error parsing line '%2' in file %1").arg(e.path).arg(e.line))
240 except ConfigurationDefineException, e:
241 self.exceptionOccurred(self.tr("Error parsing line '%2' in file %1").arg(e.path).arg(e.line))
243 def fillModuleTree(self):
245 Fills the module tree with the module entries separated in categories.
247 self.pageContent.moduleTree.clear()
248 modules = self.projectInfo("MODULES")
252 for module, information in modules.items():
253 if information["category"] not in categories:
254 categories[information["category"]] = []
255 categories[information["category"]].append(module)
256 for category, module_list in categories.items():
257 item = QTreeWidgetItem(QStringList([category]))
258 for module in module_list:
259 enabled = modules[module]["enabled"]
260 module_item = QTreeWidgetItem(item, QStringList([module]))
262 supported = bertos_utils.isSupported(self.project, module=module)
263 except SupportedException, e:
264 self.exceptionOccurred(self.tr("Error evaluating \"%1\" for module %2").arg(e.support_string).arg(module))
267 module_item.setForeground(0, QBrush(QColor(Qt.red)))
269 module_item.setCheckState(0, Qt.Checked)
271 module_item.setCheckState(0, Qt.Unchecked)
272 self.pageContent.moduleTree.addTopLevelItem(item)
273 self.pageContent.moduleTree.sortItems(0, Qt.AscendingOrder)
274 self.fillPropertyTable()
276 def insertCheckBox(self, index, value):
278 Inserts in the table at index a checkbox for a boolean property setted
281 check_box = QCheckBox()
282 self.pageContent.propertyTable.setCellWidget(index, 1, check_box)
284 check_box.setChecked(True)
286 check_box.setChecked(False)
287 self._control_group.addControl(index, check_box)
289 def insertComboBox(self, index, value, value_list):
291 Inserts in the table at index a combobox for an enum property setted
295 enum = self.projectInfo("LISTS")[value_list]
296 combo_box = QComboBox()
297 self.pageContent.propertyTable.setCellWidget(index, 1, combo_box)
298 for i, element in enumerate(enum):
299 combo_box.addItem(element)
301 combo_box.setCurrentIndex(i)
302 self._control_group.addControl(index, combo_box)
304 self.exceptionOccurred(self.tr("Define list \"%1\" not found. Check definition files.").arg(value_list))
305 self.pageContent.propertyTable.setItem(index, 1, QTableWidgetItem(value))
307 def insertSpinBox(self, index, value, informations):
309 Inserts in the table at index a spinbox for an int, a long or an unsigned
310 long property setted to value.
312 # int, long or undefined type property
314 if bertos_utils.isLong(informations) or bertos_utils.isUnsignedLong(informations):
315 spin_box = QDoubleSpinBox()
316 spin_box.setDecimals(0)
318 spin_box = QSpinBox()
319 self.pageContent.propertyTable.setCellWidget(index, 1, spin_box)
323 if bertos_utils.isLong(informations):
324 minimum = -2147483648
327 elif bertos_utils.isUnsigned(informations):
331 elif bertos_utils.isUnsignedLong(informations):
335 if "min" in informations:
336 minimum = int(informations["min"])
337 if "max" in informations:
338 maximum = int(informations["max"])
339 spin_box.setRange(minimum, maximum)
340 spin_box.setSuffix(suff)
341 spin_box.setValue(int(value.replace("L", "").replace("U", "")))
342 self._control_group.addControl(index, spin_box)
345 def currentModule(self):
347 Retuns the current module name.
349 current_module = self.pageContent.moduleTree.currentItem()
350 # return only the child items
351 if current_module and current_module.parent():
352 return unicode(current_module.text(0))
356 def moduleItem(self, module):
357 for top_level_index in range(self.pageContent.moduleTree.topLevelItemCount()):
358 top_level_item = self.pageContent.moduleTree.topLevelItem(top_level_index)
359 for child_index in range(top_level_item.childCount()):
360 child_item = top_level_item.child(child_index)
361 if unicode(child_item.text(0)) == module:
365 def currentModuleConfigurations(self):
367 Returns the current module configuration.
369 return self.configurations(self.currentModule())
371 def currentProperty(self):
373 Rerturns the current property from the property table.
375 return qvariant_converter.getString(self.pageContent.propertyTable.item(self.pageContent.propertyTable.currentRow(), 0).data(Qt.UserRole))
377 def currentPropertyItem(self):
379 Returns the QTableWidgetItem of the current property.
381 return self.pageContent.propertyTable.item(self.pageContent.propertyTable.currentRow(), 0)
383 def configurations(self, module):
385 Returns the configuration for the selected module.
389 # On linux platform it seems that the behaviour of the focus
390 # changing is a bit different from the mac one. So if module is
391 # None then no configurations should be returned.
392 configuration = self.projectInfo("MODULES")[module]["configuration"]
393 if len(configuration) > 0:
394 return self.projectInfo("CONFIGURATIONS")[configuration]
398 def resetPropertyDescription(self):
400 Resets the label for each property table entry.
402 for index in range(self.pageContent.propertyTable.rowCount()):
403 property_name = qvariant_converter.getString(self.pageContent.propertyTable.item(index, 0).data(Qt.UserRole))
404 # Awful solution! Needed because if the user change the module, the selection changed...
405 if property_name not in self.currentModuleConfigurations():
407 self.pageContent.propertyTable.item(index, 0).setText(self.currentModuleConfigurations()[property_name]['brief'])
409 def setBold(self, item, bold):
410 self.pageContent.moduleTree.blockSignals(True)
413 item.setFont(0, font)
414 self.pageContent.moduleTree.blockSignals(False)
416 def isBold(self, item):
417 return item.font(0).bold()
419 def moduleSelected(self, selectedModule):
421 Resolves the selection dependencies.
424 qApp.setOverrideCursor(Qt.WaitCursor)
425 modules = self.projectInfo("MODULES")
426 modules[selectedModule]["enabled"] = True
427 self.setProjectInfo("MODULES", modules)
428 depends = self.projectInfo("MODULES")[selectedModule]["depends"]
430 if self.pageContent.automaticFix.isChecked():
431 unsatisfied = self.selectDependencyCheck(selectedModule)
432 if len(unsatisfied) > 0:
433 for module in unsatisfied:
434 modules = self.projectInfo("MODULES")
435 modules[module]["enabled"] = True
436 for category in range(self.pageContent.moduleTree.topLevelItemCount()):
437 item = self.pageContent.moduleTree.topLevelItem(category)
438 for child in range(item.childCount()):
439 if unicode(item.child(child).text(0)) in unsatisfied:
440 self.setBold(item.child(child), True)
441 self.setBold(item, True)
442 item.child(child).setCheckState(0, Qt.Checked)
444 qApp.restoreOverrideCursor()
446 def moduleUnselected(self, unselectedModule):
448 Resolves the unselection dependencies.
451 qApp.setOverrideCursor(Qt.WaitCursor)
452 modules = self.projectInfo("MODULES")
453 modules[unselectedModule]["enabled"] = False
454 self.setProjectInfo("MODULES", modules)
456 unsatisfied_params = []
457 if self.pageContent.automaticFix.isChecked():
458 unsatisfied, unsatisfied_params = self.unselectDependencyCheck(unselectedModule)
459 if len(unsatisfied) > 0 or len(unsatisfied_params) > 0:
461 heading = self.tr("The module %1 is needed by").arg(unselectedModule)
462 message.append(heading)
463 module_list = ", ".join(unsatisfied)
464 param_list = ", ".join(["%s (%s)" %(param_name, module) for module, param_name in unsatisfied_params])
466 message.append(QString(module_list))
467 if module_list and param_list:
468 message.append(self.tr("and by"))
470 message.append(QString(param_list))
471 message_str = QStringList(message).join(" ")
472 message_str.append(self.tr("\n\nDo you want to automatically fix these conflicts?"))
473 qApp.restoreOverrideCursor()
474 choice = QMessageBox.warning(self, self.tr("Dependency error"), message_str, QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)
475 qApp.setOverrideCursor(Qt.WaitCursor)
476 if choice == QMessageBox.Yes:
477 for module in unsatisfied:
478 modules = self.projectInfo("MODULES")
479 modules[module]["enabled"] = False
480 for category in range(self.pageContent.moduleTree.topLevelItemCount()):
481 item = self.pageContent.moduleTree.topLevelItem(category)
482 self.setBold(item, False)
483 for child in range(item.childCount()):
484 if unicode(item.child(child).text(0)) in unsatisfied:
485 self.setBold(item.child(child), False)
486 item.child(child).setCheckState(0, Qt.Unchecked)
488 if self.isBold(item.child(child)):
489 self.setBold(item, True)
490 for module, param in unsatisfied_params:
491 configuration_file = self.projectInfo("MODULES")[module]["configuration"]
492 configurations = self.projectInfo("CONFIGURATIONS")
493 configurations[configuration_file][param]["value"] = "0"
494 self.setProjectInfo("CONFIGURATIONS", configurations)
496 qApp.restoreOverrideCursor()
498 def selectDependencyCheck(self, module):
500 Returns the list of unsatisfied dependencies after a selection.
503 modules = self.projectInfo("MODULES")
504 files = self.projectInfo("FILES")
505 configurations = self.projectInfo("CONFIGURATIONS").get(modules[module]["configuration"], {"paramlist": ()})
506 conditional_deps = ()
507 for i, param_name in configurations["paramlist"]:
508 information = configurations[param_name]
509 if information["informations"]["type"] == "boolean" and \
510 information["value"] != "0" and \
511 "conditional_deps" in information["informations"]:
513 conditional_deps += information["informations"]["conditional_deps"]
515 for dependency in modules[module]["depends"] + conditional_deps:
516 if dependency in modules and not modules[dependency]["enabled"]:
517 unsatisfied |= set([dependency])
518 if dependency not in unsatisfied:
519 unsatisfied |= self.selectDependencyCheck(dependency)
520 if dependency not in modules:
521 if dependency in files:
522 files[dependency] += 1
524 files[dependency] = 1
525 self.setProjectInfo("FILES", files)
528 def unselectDependencyCheck(self, dependency):
530 Returns the list of unsatisfied dependencies after an unselection.
533 unsatisfied_params = set()
534 modules = self.projectInfo("MODULES")
535 for module, informations in modules.items():
536 configurations = self.projectInfo("CONFIGURATIONS").get(informations["configuration"], {"paramlist": ()})
537 conditional_deps = {}
538 for i, param_name in configurations["paramlist"]:
539 information = configurations[param_name]
540 if information["informations"]["type"] == "boolean" and information["value"] != "0" and "conditional_deps" in information["informations"]:
541 for dep in information["informations"]["conditional_deps"]:
542 if not dep in conditional_deps:
543 conditional_deps[dep] = []
544 conditional_deps[dep].append((module, param_name))
545 if dependency in informations["depends"] and informations["enabled"]:
546 unsatisfied |= set([module])
547 if dependency not in unsatisfied:
548 tmp = self.unselectDependencyCheck(module)
549 unsatisfied |= tmp[0]
550 unsatisfied_params |= tmp[1]
551 if dependency in conditional_deps:
552 unsatisfied_params |= set(conditional_deps[dependency])
553 return unsatisfied, unsatisfied_params
555 def removeFileDependencies(self, module):
557 Removes the files dependencies of the given module.
559 modules = self.projectInfo("MODULES")
560 files = self.projectInfo("FILES")
561 dependencies = modules[module]["depends"]
562 for dependency in dependencies:
563 if dependency in files:
564 files[dependency] -= 1
565 if files[dependency] == 0:
566 del files[dependency]
567 self.setProjectInfo("FILES", files)
569 class QControlGroup(QObject):
571 Simple class that permit to connect different signals of different widgets
572 with a slot that emit a signal. Permits to group widget and to understand which of
573 them has sent the signal.
577 QObject.__init__(self)
580 def addControl(self, id, control):
584 self._controls[id] = control
585 if type(control) == QCheckBox:
586 self.connect(control, SIGNAL("stateChanged(int)"), lambda: self.stateChanged(id))
587 elif type(control) == QSpinBox:
588 self.connect(control, SIGNAL("valueChanged(int)"), lambda: self.stateChanged(id))
589 elif type(control) == QComboBox:
590 self.connect(control, SIGNAL("currentIndexChanged(int)"), lambda: self.stateChanged(id))
591 elif type(control) == QDoubleSpinBox:
592 self.connect(control, SIGNAL("valueChanged(double)"), lambda: self.stateChanged(id))
596 Remove all the controls.
600 def stateChanged(self, id):
602 Slot called when the value of one of the stored widget changes. It emits
605 self.emit(SIGNAL("stateChanged"), id)