Change some strings.
[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.QtCore import *
39 from PyQt4.QtGui import *
40 from BWizardPage import *
41 import bertos_utils
42
43 from bertos_utils import SupportedException
44 from DefineException import *
45 from const import *
46
47 class BModulePage(BWizardPage):
48     """
49     Page of the wizard that permits to select and configurate the BeRTOS modules.
50     """
51     
52     def __init__(self):
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)
58     
59     ## Overloaded BWizardPage methods ##
60
61     def setupUi(self):
62         """
63         Overload of BWizardPage setupUi method.
64         """
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)
75     
76     def connectSignals(self):
77         """
78         Overload of the BWizardPage connectSignals method.
79         """
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)
84
85     def reloadData(self):
86         """
87         Overload of the BWizardPage reloadData method.
88         """
89         try:
90             QApplication.instance().setOverrideCursor(Qt.WaitCursor)
91             self.setupUi()
92             self.loadModuleData()
93             self.fillModuleTree()
94         finally:
95             QApplication.instance().restoreOverrideCursor()
96     
97     ####
98     
99     ## Slots ##
100
101     def moduleClicked(self, item, column):
102         self.setBold(item, False)
103
104     def fillPropertyTable(self):
105         """
106         Slot called when the user selects a module from the module tree.
107         Fills the property table using the configuration parameters defined in
108         the source tree.
109         """
110         module = self.currentModule()
111         if module:
112             try:
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))
116                 supported = True
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)
122             if not supported:
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))
127             else:
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"])
134                 index = 0
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
138                         continue
139                     try:
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
146                         continue
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.setFlags(item.flags() & ~Qt.ItemIsSelectable)
151                     item.setToolTip(property)
152                     item.setData(Qt.UserRole, qvariant_converter.convertString(property))
153                     self.pageContent.propertyTable.setItem(index, 0, item)
154                     if "type" in configurations[property]["informations"] and configurations[property]["informations"]["type"] == "boolean":
155                         self.insertCheckBox(index, configurations[property]["value"])
156                     elif "type" in configurations[property]["informations"] and configurations[property]["informations"]["type"] == "enum":
157                         self.insertComboBox(index, configurations[property]["value"], configurations[property]["informations"]["value_list"])
158                     elif "type" in configurations[property]["informations"] and configurations[property]["informations"]["type"] == "int":
159                         self.insertSpinBox(index, configurations[property]["value"], configurations[property]["informations"])
160                     else:
161                         # Not defined type, rendered as a text field
162                         self.pageContent.propertyTable.setItem(index, 1, QTableWidgetItem(configurations[property]["value"]))
163                     index += 1
164             if self.pageContent.propertyTable.rowCount() == 0:
165                 module_label = self.pageContent.moduleLabel.text()
166                 module_label += "\n\nNo configuration needed."
167                 self.pageContent.moduleLabel.setText(module_label) 
168         else:
169             self.pageContent.moduleLabel.setText("")
170             self.pageContent.moduleLabel.setVisible(False)
171             self.pageContent.propertyTable.clear()
172             self.pageContent.propertyTable.setRowCount(0)
173
174     def dependencyCheck(self, item):
175         """
176         Checks the dependencies of the module associated with the given item.
177         """
178         checked = False
179         module = unicode(item.text(0))
180         if item.checkState(0) == Qt.Checked:
181             self.moduleSelected(module)
182         else:
183             self.moduleUnselected(module)
184             self.removeFileDependencies(module)
185
186     def showPropertyDescription(self):
187         """
188         Slot called when the property selection changes. Shows the description
189         of the selected property.
190         """
191         self.resetPropertyDescription()
192         configurations = self.currentModuleConfigurations()
193         if self.currentProperty() in configurations:
194             description = configurations[self.currentProperty()]["brief"]
195             name = self.currentProperty()
196             self.currentPropertyItem().setText(description + "\n" + name)
197
198     def saveValue(self, index):
199         """
200         Slot called when the user modifies one of the configuration parameters.
201         It stores the new value."""
202         property = qvariant_converter.getString(self.pageContent.propertyTable.item(index, 0).data(Qt.UserRole))
203         configuration = self.projectInfo("MODULES")[self.currentModule()]["configuration"]
204         configurations = self.projectInfo("CONFIGURATIONS")
205         if "type" not in configurations[configuration][property]["informations"] or configurations[configuration][property]["informations"]["type"] == "int":
206             configurations[configuration][property]["value"] = unicode(int(self.pageContent.propertyTable.cellWidget(index, 1).value()))
207         elif configurations[configuration][property]["informations"]["type"] == "enum":
208             configurations[configuration][property]["value"] = unicode(self.pageContent.propertyTable.cellWidget(index, 1).currentText())
209         elif configurations[configuration][property]["informations"]["type"] == "boolean":
210             if self.pageContent.propertyTable.cellWidget(index, 1).isChecked():
211                 configurations[configuration][property]["value"] = "1"
212             else:
213                 configurations[configuration][property]["value"] = "0"
214         self.setProjectInfo("CONFIGURATIONS", configurations)
215         if self.moduleItem(self.currentModule()).checkState(0) == Qt.Checked:
216             self.dependencyCheck(self.moduleItem(self.currentModule()))
217
218     ####
219     
220     def loadModuleData(self):
221         """
222         Loads the module data.
223         """
224         # Do not load the module data again when the Wizard is in editing mode
225         # or when it's working on a preset.
226         if not self.project.edit and not self.project.from_preset:
227             # Load the module data every time so that if the user changed the cpu
228             # the right configurations are picked up.
229             try:
230                 self.project.loadModuleData()
231             except ModuleDefineException, e:
232                 self.exceptionOccurred(self.tr("Error parsing line '%2' in file %1").arg(e.path).arg(e.line))
233             except EnumDefineException, e:
234                 self.exceptionOccurred(self.tr("Error parsing line '%2' in file %1").arg(e.path).arg(e.line))
235             except ConfigurationDefineException, e:
236                 self.exceptionOccurred(self.tr("Error parsing line '%2' in file %1").arg(e.path).arg(e.line))
237     
238     def fillModuleTree(self):
239         """
240         Fills the module tree with the module entries separated in categories.
241         """
242         self.pageContent.moduleTree.clear()
243         modules = self.projectInfo("MODULES")
244         if not modules:
245             return
246         categories = {}
247         for module, information in modules.items():
248             if information["category"] not in categories:
249                 categories[information["category"]] = []
250             categories[information["category"]].append(module)
251         for category, module_list in categories.items():
252             item = QTreeWidgetItem(QStringList([category]))
253             for module in module_list:
254                 enabled = modules[module]["enabled"]
255                 module_item = QTreeWidgetItem(item, QStringList([module]))
256                 try:
257                     supported = bertos_utils.isSupported(self.project, module=module)
258                 except SupportedException, e:
259                     self.exceptionOccurred(self.tr("Error evaluating \"%1\" for module %2").arg(e.support_string).arg(module))
260                     supported = True
261                 if not supported:
262                     module_item.setForeground(0, QBrush(QColor(Qt.red)))
263                 if enabled:
264                     module_item.setCheckState(0, Qt.Checked)
265                 else:
266                     module_item.setCheckState(0, Qt.Unchecked)
267             self.pageContent.moduleTree.addTopLevelItem(item)
268         self.pageContent.moduleTree.sortItems(0, Qt.AscendingOrder)
269         self.fillPropertyTable()
270             
271     def insertCheckBox(self, index, value):
272         """
273         Inserts in the table at index a checkbox for a boolean property setted
274         to value.
275         """
276         check_box = QCheckBox()
277         self.pageContent.propertyTable.setCellWidget(index, 1, check_box)
278         if value == "1":
279             check_box.setChecked(True)
280         else:
281             check_box.setChecked(False)
282         self._control_group.addControl(index, check_box)
283     
284     def insertComboBox(self, index, value, value_list):
285         """
286         Inserts in the table at index a combobox for an enum property setted
287         to value.
288         """
289         try:
290             enum = self.projectInfo("LISTS")[value_list]
291             combo_box = QComboBox()
292             self.pageContent.propertyTable.setCellWidget(index, 1, combo_box)
293             for i, element in enumerate(enum):
294                 combo_box.addItem(element)
295                 if element == value:
296                     combo_box.setCurrentIndex(i)
297             self._control_group.addControl(index, combo_box)
298         except KeyError:
299             self.exceptionOccurred(self.tr("Define list \"%1\" not found. Check definition files.").arg(value_list))
300             self.pageContent.propertyTable.setItem(index, 1, QTableWidgetItem(value))
301     
302     def insertSpinBox(self, index, value, informations):
303         """
304         Inserts in the table at index a spinbox for an int, a long or an unsigned
305         long property setted to value.
306         """
307         # int, long or undefined type property
308         spin_box = None
309         if bertos_utils.isLong(informations) or bertos_utils.isUnsignedLong(informations):
310             spin_box = QDoubleSpinBox()
311             spin_box.setDecimals(0)
312         else:
313             spin_box = QSpinBox()
314         self.pageContent.propertyTable.setCellWidget(index, 1, spin_box)
315         minimum = -32768
316         maximum = 32767
317         suff = ""
318         if bertos_utils.isLong(informations):
319             minimum = -2147483648
320             maximum = 2147483647
321             suff = "L"
322         elif bertos_utils.isUnsigned(informations):
323             minimum = 0
324             maximum = 65535
325             suff = "U"
326         elif bertos_utils.isUnsignedLong(informations):
327             minimum = 0
328             maximum = 4294967295
329             suff = "UL"
330         if "min" in informations:
331             minimum = int(informations["min"])
332         if "max" in informations:
333             maximum = int(informations["max"])
334         spin_box.setRange(minimum, maximum)
335         spin_box.setSuffix(suff)
336         spin_box.setValue(int(value.replace("L", "").replace("U", "")))
337         self._control_group.addControl(index, spin_box)
338         
339     
340     def currentModule(self):
341         """
342         Retuns the current module name.
343         """
344         current_module = self.pageContent.moduleTree.currentItem()
345         # return only the child items
346         if current_module and current_module.parent():
347             return unicode(current_module.text(0))
348         else:
349             return None
350
351     def moduleItem(self, module):
352         for top_level_index in range(self.pageContent.moduleTree.topLevelItemCount()):
353             top_level_item = self.pageContent.moduleTree.topLevelItem(top_level_index)
354             for child_index in range(top_level_item.childCount()):
355                 child_item = top_level_item.child(child_index)
356                 if unicode(child_item.text(0)) == module:
357                     return child_item
358         return None
359     
360     def currentModuleConfigurations(self):
361         """
362         Returns the current module configuration.
363         """
364         return self.configurations(self.currentModule())
365     
366     def currentProperty(self):
367         """
368         Rerturns the current property from the property table.
369         """
370         return qvariant_converter.getString(self.pageContent.propertyTable.item(self.pageContent.propertyTable.currentRow(), 0).data(Qt.UserRole))
371     
372     def currentPropertyItem(self):
373         """
374         Returns the QTableWidgetItem of the current property.
375         """
376         return self.pageContent.propertyTable.item(self.pageContent.propertyTable.currentRow(), 0)
377     
378     def configurations(self, module):
379         """
380         Returns the configuration for the selected module.
381         """
382         configuration = []
383         if module:
384             # On linux platform it seems that the behaviour of the focus
385             # changing is a bit different from the mac one. So if module is
386             # None then no configurations should be returned.
387             configuration = self.projectInfo("MODULES")[module]["configuration"]
388         if len(configuration) > 0:
389             return self.projectInfo("CONFIGURATIONS")[configuration]
390         else:
391             return {}
392     
393     def resetPropertyDescription(self):
394         """
395         Resets the label for each property table entry.
396         """
397         for index in range(self.pageContent.propertyTable.rowCount()):
398             property_name = qvariant_converter.getString(self.pageContent.propertyTable.item(index, 0).data(Qt.UserRole))
399             # Awful solution! Needed because if the user change the module, the selection changed...
400             if property_name not in self.currentModuleConfigurations():
401                 break
402             self.pageContent.propertyTable.item(index, 0).setText(self.currentModuleConfigurations()[property_name]['brief'])
403     
404     def setBold(self, item, bold):
405         self.pageContent.moduleTree.blockSignals(True)
406         font = item.font(0)
407         font.setBold(bold)
408         item.setFont(0, font)
409         self.pageContent.moduleTree.blockSignals(False)
410
411     def moduleSelected(self, selectedModule):
412         """
413         Resolves the selection dependencies.
414         """
415         try:
416             qApp.setOverrideCursor(Qt.WaitCursor)
417             modules = self.projectInfo("MODULES")
418             modules[selectedModule]["enabled"] = True
419             self.setProjectInfo("MODULES", modules)
420             depends = self.projectInfo("MODULES")[selectedModule]["depends"]
421             unsatisfied = []
422             if self.pageContent.automaticFix.isChecked():
423                 unsatisfied = self.selectDependencyCheck(selectedModule)
424             if len(unsatisfied) > 0:
425                 for module in unsatisfied:
426                     modules = self.projectInfo("MODULES")
427                     modules[module]["enabled"] = True
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                             self.setBold(item.child(child), True)
433                             self.setBold(item, True)
434                             item.child(child).setCheckState(0, Qt.Checked)
435         finally:
436             qApp.restoreOverrideCursor()
437     
438     def moduleUnselected(self, unselectedModule):
439         """
440         Resolves the unselection dependencies.
441         """
442         try:
443             qApp.setOverrideCursor(Qt.WaitCursor)
444             modules = self.projectInfo("MODULES")
445             modules[unselectedModule]["enabled"] = False
446             self.setProjectInfo("MODULES", modules)
447             unsatisfied = []
448             unsatisfied_params = []
449             if self.pageContent.automaticFix.isChecked():
450                 unsatisfied, unsatisfied_params = self.unselectDependencyCheck(unselectedModule)
451             if len(unsatisfied) > 0 or len(unsatisfied_params) > 0:
452                 message = []
453                 heading = self.tr("The module %1 is needed by").arg(unselectedModule)
454                 message.append(heading)
455                 module_list = ", ".join(unsatisfied)
456                 param_list = ", ".join(["%s (%s)" %(param_name, module) for module, param_name in unsatisfied_params])
457                 if module_list:
458                     message.append(QString(module_list))
459                 if module_list and param_list:
460                     message.append(self.tr("and by"))
461                 if param_list:
462                     message.append(QString(param_list))
463                 message_str = QStringList(message).join(" ")
464                 message_str.append(self.tr("\n\nDo you want to automatically fix these conflicts?"))
465                 qApp.restoreOverrideCursor()
466                 choice = QMessageBox.warning(self, self.tr("Dependency error"), message_str, QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)
467                 qApp.setOverrideCursor(Qt.WaitCursor)
468                 if choice == QMessageBox.Yes:
469                     for module in unsatisfied:
470                         modules = self.projectInfo("MODULES")
471                         modules[module]["enabled"] = False
472                     for category in range(self.pageContent.moduleTree.topLevelItemCount()):
473                         item = self.pageContent.moduleTree.topLevelItem(category)
474                         for child in range(item.childCount()):
475                             if unicode(item.child(child).text(0)) in unsatisfied:
476                                 item.child(child).setCheckState(0, Qt.Unchecked)
477                     for module, param in unsatisfied_params:
478                         configuration_file = self.projectInfo("MODULES")[module]["configuration"]
479                         configurations = self.projectInfo("CONFIGURATIONS")
480                         configurations[configuration_file][param]["value"] = "0"
481                         self.setProjectInfo("CONFIGURATIONS", configurations)
482         finally:
483             qApp.restoreOverrideCursor()
484     
485     def selectDependencyCheck(self, module):
486         """
487         Returns the list of unsatisfied dependencies after a selection.
488         """
489         unsatisfied = set()
490         modules = self.projectInfo("MODULES")
491         files = self.projectInfo("FILES")
492         configurations = self.projectInfo("CONFIGURATIONS").get(modules[module]["configuration"], {"paramlist": ()})
493         conditional_deps = ()
494         for i, param_name in configurations["paramlist"]:
495             information = configurations[param_name]
496             if information["informations"]["type"] == "boolean" and \
497                 information["value"] != "0" and \
498                 "conditional_deps" in information["informations"]:
499
500                 conditional_deps += information["informations"]["conditional_deps"]
501
502         for dependency in modules[module]["depends"] + conditional_deps:
503             if dependency in modules and not modules[dependency]["enabled"]:
504                 unsatisfied |= set([dependency])
505                 if dependency not in unsatisfied:
506                     unsatisfied |= self.selectDependencyCheck(dependency)
507             if dependency not in modules:
508                 if dependency in files:
509                     files[dependency] += 1
510                 else:
511                     files[dependency] = 1
512         self.setProjectInfo("FILES", files)
513         return unsatisfied
514     
515     def unselectDependencyCheck(self, dependency):
516         """
517         Returns the list of unsatisfied dependencies after an unselection.
518         """
519         unsatisfied = set()
520         unsatisfied_params = set()
521         modules = self.projectInfo("MODULES")
522         for module, informations in modules.items():
523             configurations = self.projectInfo("CONFIGURATIONS").get(informations["configuration"], {"paramlist": ()})
524             conditional_deps = {}
525             for i, param_name in configurations["paramlist"]:
526                 information = configurations[param_name]
527                 if information["informations"]["type"] == "boolean" and information["value"] != "0" and "conditional_deps" in information["informations"]:
528                     for dep in information["informations"]["conditional_deps"]:
529                         if not dep in conditional_deps:
530                             conditional_deps[dep] = []
531                         conditional_deps[dep].append((module, param_name))
532             if dependency in informations["depends"] and informations["enabled"]:
533                 unsatisfied |= set([module])
534                 if dependency not in unsatisfied:
535                     tmp = self.unselectDependencyCheck(module)
536                     unsatisfied |= tmp[0]
537                     unsatisfied_params |= tmp[1]
538             if dependency in conditional_deps:
539                 unsatisfied_params |= set(conditional_deps[dependency])
540         return unsatisfied, unsatisfied_params
541     
542     def removeFileDependencies(self, module):
543         """
544         Removes the files dependencies of the given module.
545         """
546         modules = self.projectInfo("MODULES")
547         files = self.projectInfo("FILES")
548         dependencies = modules[module]["depends"]
549         for dependency in dependencies:
550             if dependency in files:
551                 files[dependency] -= 1
552                 if files[dependency] == 0:
553                     del files[dependency]
554         self.setProjectInfo("FILES", files)
555
556 class QControlGroup(QObject):
557     """
558     Simple class that permit to connect different signals of different widgets
559     with a slot that emit a signal. Permits to group widget and to understand which of
560     them has sent the signal.
561     """
562     
563     def __init__(self):
564         QObject.__init__(self)
565         self._controls = {}
566     
567     def addControl(self, id, control):
568         """
569         Add a control.
570         """
571         self._controls[id] = control
572         if type(control) == QCheckBox:
573             self.connect(control, SIGNAL("stateChanged(int)"), lambda: self.stateChanged(id))
574         elif type(control) == QSpinBox:
575             self.connect(control, SIGNAL("valueChanged(int)"), lambda: self.stateChanged(id))
576         elif type(control) == QComboBox:
577             self.connect(control, SIGNAL("currentIndexChanged(int)"), lambda: self.stateChanged(id))
578         elif type(control) == QDoubleSpinBox:
579             self.connect(control, SIGNAL("valueChanged(double)"), lambda: self.stateChanged(id))
580     
581     def clear(self):
582         """
583         Remove all the controls.
584         """
585         self._controls = {}
586     
587     def stateChanged(self, id):
588         """
589         Slot called when the value of one of the stored widget changes. It emits
590         another signal.
591         """
592         self.emit(SIGNAL("stateChanged"), id)