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.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)
82 self.connect(self.pageContent.propertyTable, SIGNAL("itemSelectionChanged()"), self.showPropertyDescription)
86 Overload of the BWizardPage reloadData method.
88 QApplication.instance().setOverrideCursor(Qt.WaitCursor)
92 QApplication.instance().restoreOverrideCursor()
98 def moduleClicked(self, item, column):
99 self.setBold(item, False)
101 def fillPropertyTable(self):
103 Slot called when the user selects a module from the module tree.
104 Fills the property table using the configuration parameters defined in
107 module = self.currentModule()
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))
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)
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))
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"])
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
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
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"])
156 # Not defined type, rendered as a text field
157 self.pageContent.propertyTable.setItem(index, 1, QTableWidgetItem(configurations[property]["value"]))
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)
164 self.pageContent.moduleLabel.setText("")
165 self.pageContent.moduleLabel.setVisible(False)
166 self.pageContent.propertyTable.clear()
167 self.pageContent.propertyTable.setRowCount(0)
169 def dependencyCheck(self, item):
171 Checks the dependencies of the module associated with the given item.
174 module = unicode(item.text(0))
175 if item.checkState(0) == Qt.Checked:
176 self.moduleSelected(module)
178 self.moduleUnselected(module)
179 self.removeFileDependencies(module)
181 def showPropertyDescription(self):
183 Slot called when the property selection changes. Shows the description
184 of the selected property.
186 self.resetPropertyDescription()
187 configurations = self.currentModuleConfigurations()
188 if self.currentProperty() in configurations:
189 description = configurations[self.currentProperty()]["brief"]
190 name = self.currentProperty()
191 self.currentPropertyItem().setText(description + "\n" + name)
193 def saveValue(self, index):
195 Slot called when the user modifies one of the configuration parameters.
196 It stores the new value."""
197 property = qvariant_converter.getString(self.pageContent.propertyTable.item(index, 0).data(Qt.UserRole))
198 configuration = self.projectInfo("MODULES")[self.currentModule()]["configuration"]
199 configurations = self.projectInfo("CONFIGURATIONS")
200 if "type" not in configurations[configuration][property]["informations"] or configurations[configuration][property]["informations"]["type"] == "int":
201 configurations[configuration][property]["value"] = unicode(int(self.pageContent.propertyTable.cellWidget(index, 1).value()))
202 elif configurations[configuration][property]["informations"]["type"] == "enum":
203 configurations[configuration][property]["value"] = unicode(self.pageContent.propertyTable.cellWidget(index, 1).currentText())
204 elif configurations[configuration][property]["informations"]["type"] == "boolean":
205 if self.pageContent.propertyTable.cellWidget(index, 1).isChecked():
206 configurations[configuration][property]["value"] = "1"
208 configurations[configuration][property]["value"] = "0"
209 self.setProjectInfo("CONFIGURATIONS", configurations)
210 if self.moduleItem(self.currentModule()).checkState(0) == Qt.Checked:
211 self.dependencyCheck(self.moduleItem(self.currentModule()))
215 def loadModuleData(self):
217 Loads the module data.
219 # Load the module data only if it isn't already loaded
220 if not self.projectInfo("MODULES") \
221 and not self.projectInfo("LISTS") \
222 and not self.projectInfo("CONFIGURATIONS"):
224 bertos_utils.loadModuleData(self.project())
225 except ModuleDefineException, e:
226 self.exceptionOccurred(self.tr("Error parsing line '%2' in file %1").arg(e.path).arg(e.line))
227 except EnumDefineException, e:
228 self.exceptionOccurred(self.tr("Error parsing line '%2' in file %1").arg(e.path).arg(e.line))
229 except ConfigurationDefineException, e:
230 self.exceptionOccurred(self.tr("Error parsing line '%2' in file %1").arg(e.path).arg(e.line))
232 def fillModuleTree(self):
234 Fills the module tree with the module entries separated in categories.
236 self.pageContent.moduleTree.clear()
237 modules = self.projectInfo("MODULES")
241 for module, information in modules.items():
242 if information["category"] not in categories:
243 categories[information["category"]] = []
244 categories[information["category"]].append(module)
245 for category, module_list in categories.items():
246 item = QTreeWidgetItem(QStringList([category]))
247 for module in module_list:
248 enabled = modules[module]["enabled"]
249 module_item = QTreeWidgetItem(item, QStringList([module]))
251 supported = bertos_utils.isSupported(self.project(), module=module)
252 except SupportedException, e:
253 self.exceptionOccurred(self.tr("Error evaluating \"%1\" for module %2").arg(e.support_string).arg(module))
256 module_item.setForeground(0, QBrush(QColor(Qt.red)))
258 module_item.setCheckState(0, Qt.Checked)
260 module_item.setCheckState(0, Qt.Unchecked)
261 self.pageContent.moduleTree.addTopLevelItem(item)
262 self.pageContent.moduleTree.sortItems(0, Qt.AscendingOrder)
263 self.fillPropertyTable()
265 def insertCheckBox(self, index, value):
267 Inserts in the table at index a checkbox for a boolean property setted
270 check_box = QCheckBox()
271 self.pageContent.propertyTable.setCellWidget(index, 1, check_box)
273 check_box.setChecked(True)
275 check_box.setChecked(False)
276 self._control_group.addControl(index, check_box)
278 def insertComboBox(self, index, value, value_list):
280 Inserts in the table at index a combobox for an enum property setted
284 enum = self.projectInfo("LISTS")[value_list]
285 combo_box = QComboBox()
286 self.pageContent.propertyTable.setCellWidget(index, 1, combo_box)
287 for i, element in enumerate(enum):
288 combo_box.addItem(element)
290 combo_box.setCurrentIndex(i)
291 self._control_group.addControl(index, combo_box)
293 self.exceptionOccurred(self.tr("Define list \"%1\" not found. Check definition files.").arg(value_list))
294 self.pageContent.propertyTable.setItem(index, 1, QTableWidgetItem(value))
296 def insertSpinBox(self, index, value, informations):
298 Inserts in the table at index a spinbox for an int, a long or an unsigned
299 long property setted to value.
301 # int, long or undefined type property
303 if bertos_utils.isLong(informations) or bertos_utils.isUnsignedLong(informations):
304 spin_box = QDoubleSpinBox()
305 spin_box.setDecimals(0)
307 spin_box = QSpinBox()
308 self.pageContent.propertyTable.setCellWidget(index, 1, spin_box)
312 if bertos_utils.isLong(informations):
313 minimum = -2147483648
316 elif bertos_utils.isUnsigned(informations):
320 elif bertos_utils.isUnsignedLong(informations):
324 if "min" in informations:
325 minimum = int(informations["min"])
326 if "max" in informations:
327 maximum = int(informations["max"])
328 spin_box.setRange(minimum, maximum)
329 spin_box.setSuffix(suff)
330 spin_box.setValue(int(value.replace("L", "").replace("U", "")))
331 self._control_group.addControl(index, spin_box)
334 def currentModule(self):
336 Retuns the current module name.
338 current_module = self.pageContent.moduleTree.currentItem()
339 # return only the child items
340 if current_module and current_module.parent():
341 return unicode(current_module.text(0))
345 def moduleItem(self, module):
346 for top_level_index in range(self.pageContent.moduleTree.topLevelItemCount()):
347 top_level_item = self.pageContent.moduleTree.topLevelItem(top_level_index)
348 for child_index in range(top_level_item.childCount()):
349 child_item = top_level_item.child(child_index)
350 if unicode(child_item.text(0)) == module:
354 def currentModuleConfigurations(self):
356 Returns the current module configuration.
358 return self.configurations(self.currentModule())
360 def currentProperty(self):
362 Rerturns the current property from the property table.
364 return qvariant_converter.getString(self.pageContent.propertyTable.item(self.pageContent.propertyTable.currentRow(), 0).data(Qt.UserRole))
366 def currentPropertyItem(self):
368 Returns the QTableWidgetItem of the current property.
370 return self.pageContent.propertyTable.item(self.pageContent.propertyTable.currentRow(), 0)
372 def configurations(self, module):
374 Returns the configuration for the selected module.
376 configuration = self.projectInfo("MODULES")[module]["configuration"]
377 if len(configuration) > 0:
378 return self.projectInfo("CONFIGURATIONS")[configuration]
382 def resetPropertyDescription(self):
384 Resets the label for each property table entry.
386 for index in range(self.pageContent.propertyTable.rowCount()):
387 property_name = qvariant_converter.getString(self.pageContent.propertyTable.item(index, 0).data(Qt.UserRole))
388 # Awful solution! Needed because if the user change the module, the selection changed...
389 if property_name not in self.currentModuleConfigurations():
391 self.pageContent.propertyTable.item(index, 0).setText(self.currentModuleConfigurations()[property_name]['brief'])
393 def setBold(self, item, bold):
394 self.pageContent.moduleTree.blockSignals(True)
397 item.setFont(0, font)
398 self.pageContent.moduleTree.blockSignals(False)
400 def moduleSelected(self, selectedModule):
402 Resolves the selection dependencies.
404 modules = self.projectInfo("MODULES")
405 modules[selectedModule]["enabled"] = True
406 self.setProjectInfo("MODULES", modules)
407 depends = self.projectInfo("MODULES")[selectedModule]["depends"]
409 if self.pageContent.automaticFix.isChecked():
410 unsatisfied = self.selectDependencyCheck(selectedModule)
411 if len(unsatisfied) > 0:
412 for module in unsatisfied:
413 modules = self.projectInfo("MODULES")
414 modules[module]["enabled"] = True
415 for category in range(self.pageContent.moduleTree.topLevelItemCount()):
416 item = self.pageContent.moduleTree.topLevelItem(category)
417 for child in range(item.childCount()):
418 if unicode(item.child(child).text(0)) in unsatisfied:
419 self.setBold(item.child(child), True)
420 self.setBold(item, True)
421 item.child(child).setCheckState(0, Qt.Checked)
423 def moduleUnselected(self, unselectedModule):
425 Resolves the unselection dependencies.
427 modules = self.projectInfo("MODULES")
428 modules[unselectedModule]["enabled"] = False
429 self.setProjectInfo("MODULES", modules)
431 unsatisfied_params = []
432 if self.pageContent.automaticFix.isChecked():
433 unsatisfied, unsatisfied_params = self.unselectDependencyCheck(unselectedModule)
434 if len(unsatisfied) > 0 or len(unsatisfied_params) > 0:
436 heading = self.tr("The module %1 is needed by").arg(unselectedModule)
437 message.append(heading)
438 module_list = ", ".join(unsatisfied)
439 param_list = ", ".join(["%s (%s)" %(param_name, module) for module, param_name in unsatisfied_params])
441 message.append(QString(module_list))
442 if module_list and param_list:
443 message.append(self.tr("and by"))
445 message.append(QString(param_list))
446 message_str = QStringList(message).join(" ")
447 message_str.append(self.tr("\n\nDo you want to automatically fix these conflicts?"))
448 choice = QMessageBox.warning(self, self.tr("Dependency error"), message_str, QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)
449 if choice == QMessageBox.Yes:
450 for module in unsatisfied:
451 modules = self.projectInfo("MODULES")
452 modules[module]["enabled"] = False
453 for category in range(self.pageContent.moduleTree.topLevelItemCount()):
454 item = self.pageContent.moduleTree.topLevelItem(category)
455 for child in range(item.childCount()):
456 if unicode(item.child(child).text(0)) in unsatisfied:
457 item.child(child).setCheckState(0, Qt.Unchecked)
458 for module, param in unsatisfied_params:
459 configuration_file = self.projectInfo("MODULES")[module]["configuration"]
460 configurations = self.projectInfo("CONFIGURATIONS")
461 configurations[configuration_file][param]["value"] = "0"
462 self.setProjectInfo("CONFIGURATIONS", configurations)
464 def selectDependencyCheck(self, module):
466 Returns the list of unsatisfied dependencies after a selection.
469 modules = self.projectInfo("MODULES")
470 files = self.projectInfo("FILES")
471 configurations = self.projectInfo("CONFIGURATIONS").get(modules[module]["configuration"], {"paramlist": ()})
472 conditional_deps = ()
473 for i, param_name in configurations["paramlist"]:
474 information = configurations[param_name]
475 if information["informations"]["type"] == "boolean" and \
476 information["value"] != "0" and \
477 "conditional_deps" in information["informations"]:
479 conditional_deps += information["informations"]["conditional_deps"]
481 for dependency in modules[module]["depends"] + conditional_deps:
482 if dependency in modules and not modules[dependency]["enabled"]:
483 unsatisfied |= set([dependency])
484 if dependency not in unsatisfied:
485 unsatisfied |= self.selectDependencyCheck(dependency)
486 if dependency not in modules:
487 if dependency in files:
488 files[dependency] += 1
490 files[dependency] = 1
491 self.setProjectInfo("FILES", files)
494 def unselectDependencyCheck(self, dependency):
496 Returns the list of unsatisfied dependencies after an unselection.
499 unsatisfied_params = set()
500 modules = self.projectInfo("MODULES")
501 for module, informations in modules.items():
502 configurations = self.projectInfo("CONFIGURATIONS").get(informations["configuration"], {"paramlist": ()})
503 conditional_deps = {}
504 for i, param_name in configurations["paramlist"]:
505 information = configurations[param_name]
506 if information["informations"]["type"] == "boolean" and information["value"] != "0" and "conditional_deps" in information["informations"]:
507 for dep in information["informations"]["conditional_deps"]:
508 if not dep in conditional_deps:
509 conditional_deps[dep] = []
510 conditional_deps[dep].append((module, param_name))
511 if dependency in informations["depends"] and informations["enabled"]:
512 unsatisfied |= set([module])
513 if dependency not in unsatisfied:
514 tmp = self.unselectDependencyCheck(module)
515 unsatisfied |= tmp[0]
516 unsatisfied_params |= tmp[1]
517 if dependency in conditional_deps:
518 unsatisfied_params |= set(conditional_deps[dependency])
519 return unsatisfied, unsatisfied_params
521 def removeFileDependencies(self, module):
523 Removes the files dependencies of the given module.
525 modules = self.projectInfo("MODULES")
526 files = self.projectInfo("FILES")
527 dependencies = modules[module]["depends"]
528 for dependency in dependencies:
529 if dependency in files:
530 files[dependency] -= 1
531 if files[dependency] == 0:
532 del files[dependency]
533 self.setProjectInfo("FILES", files)
535 class QControlGroup(QObject):
537 Simple class that permit to connect different signals of different widgets
538 with a slot that emit a signal. Permits to group widget and to understand which of
539 them has sent the signal.
543 QObject.__init__(self)
546 def addControl(self, id, control):
550 self._controls[id] = control
551 if type(control) == QCheckBox:
552 self.connect(control, SIGNAL("stateChanged(int)"), lambda: self.stateChanged(id))
553 elif type(control) == QSpinBox:
554 self.connect(control, SIGNAL("valueChanged(int)"), lambda: self.stateChanged(id))
555 elif type(control) == QComboBox:
556 self.connect(control, SIGNAL("currentIndexChanged(int)"), lambda: self.stateChanged(id))
557 elif type(control) == QDoubleSpinBox:
558 self.connect(control, SIGNAL("valueChanged(double)"), lambda: self.stateChanged(id))
562 Remove all the controls.
566 def stateChanged(self, id):
568 Slot called when the value of one of the stored widget changes. It emits
571 self.emit(SIGNAL("stateChanged"), id)