Add exception handling for parsing error within the preset route.
[bertos.git] / wizard / BProjectPresets.py
1 #!/usr/bin/env python
2 # encoding: utf-8
3 #
4 # This file is part of slimqc.
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 2010 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 import uic
39
40 from PyQt4.QtCore import *
41 from PyQt4.QtGui import *
42
43 from BWizardPage import BWizardPage
44
45 from BCreationPage import BCreationPage
46 from BToolchainPage import BToolchainPage
47
48 from DefineException import ModuleDefineException
49
50 from bertos_utils import _cmp
51 from toolchain_manager import ToolchainManager
52
53 import const
54 import qvariant_converter
55
56 class BProjectPresetsPage(QWidget):
57     def __init__(self, preset_data, parent=None):
58         QWidget.__init__(self, parent)
59         self.pageContent = uic.loadUi(os.path.join(const.DATA_DIR, const.UI_LOCATION, "preset_page.ui"), None)
60         self.project = QApplication.instance().project
61         self.settings = QApplication.instance().settings
62         self.preset_data = preset_data
63         layout = QVBoxLayout()
64         layout.addWidget(self.pageContent)
65         self.setLayout(layout)
66         self.setupUi()
67         self.connectSignals()
68
69     def setupUi(self):
70         self.pageContent.presetList.clear()
71         self.pageContent.categoryDescription.setText(self.preset_data["info"].get("description", ""))
72         for preset in sorted(self.preset_data["children"].values(), _cmp):
73             item_name = preset["info"].get("name", preset["info"]["filename"])
74             item_icon = os.path.join(preset["info"]["path"], const.PREDEFINED_BOARD_ICON_FILE)
75             if not os.path.exists(item_icon):
76                 item_icon = const.PREDEFINED_BOARD_DEFAULT_PROJECT_ICON
77             item_icon = QIcon(item_icon)
78             item = QListWidgetItem(item_icon, item_name)
79             item.setData(Qt.UserRole, qvariant_converter.convertString(preset["info"]["path"]))
80             self.pageContent.presetList.addItem(item)
81         self.pageContent.presetList.setCurrentRow(0)
82         self.updateUi()
83
84     def connectSignals(self):
85         self.connect(self.pageContent.presetList, SIGNAL("currentItemChanged(QListWidgetItem *, QListWidgetItem*)"), self.updateUi)
86         self.connect(self.pageContent.presetList, SIGNAL("currentItemChanged(QListWidgetItem *, QListWidgetItem*)"), self, SIGNAL("completeChanged()"))
87
88     def updateUi(self):
89         if self.selected:
90             preset_path = qvariant_converter.getString(self.selected.data(Qt.UserRole))
91             preset = self.preset_data["children"][preset_path]
92             description = preset["info"].get("description", "")
93             path = unicode(QUrl.fromLocalFile(preset_path).toString())
94             description = description.replace("$path", path)
95             self.pageContent.descriptionArea.setHtml(description)
96     
97     @property
98     def selected(self):
99         return self.pageContent.presetList.currentItem()
100         
101
102 class BProjectPresets(BWizardPage):
103     def __init__(self):
104         BWizardPage.__init__(self, const.UI_LOCATION + "/project_presets.ui")
105
106     ## Overloaded QWizardPage methods ##
107
108     def isComplete(self):
109         preset_path = self.selected_path
110         if preset_path:
111             self.setProjectInfo("PROJECT_PRESET", preset_path)
112             self.setProjectInfo("BASE_MODE", not self.advanced)
113             return True
114         else:
115             self.setProjectInfo("PROJECT_PRESET", None)
116             return False
117
118     def validatePage(self):
119         """
120         This hack permits to load the preset once, when the user go press the
121         Next button.
122         """
123         preset_path = self.selected_path
124         try:
125             QApplication.instance().setOverrideCursor(Qt.WaitCursor)
126             try:
127                 self.project.loadProjectFromPreset(preset_path)
128             except ModuleDefineException, e:
129                 self.exceptionOccurred(self.tr("Error parsing line '%2' in file %1").arg(e.path).arg(e.line))
130             self.setProjectInfo("PRESET_LOADED", True)
131         finally:
132             QApplication.instance().restoreOverrideCursor()
133         # Return always True, this is a fake validation.
134         return True
135
136     def nextId(self):
137         """
138         Overload of the QWizardPage nextId method.
139         """
140         # Route to Toolchain page if the user select advanced
141         # or to Output page if the user select base
142         if self.advanced:
143             return self.wizard().pageIndex(BToolchainPage)
144         else:
145             cpu_info = self.projectInfo("CPU_INFOS")
146             if cpu_info:
147                 target = cpu_info["TOOLCHAIN"]
148                 # Try to find a suitable toolchain automatically
149                 tm = ToolchainManager()
150                 suitable_toolchains = tm.suitableToolchains(target)
151                 if len(suitable_toolchains) == 1:
152                     toolchain = suitable_toolchains.pop()
153                     toolchain_info = tm._validateToolchain(toolchain)
154                     toolchain_info["path"] = toolchain
155                     self.setProjectInfo("TOOLCHAIN", toolchain_info)
156                     return self.wizard().pageIndex(BCreationPage)
157                 else:
158                     return self.wizard().pageIndex(BToolchainPage)
159             else:
160                 # It seems that the nextId method is called before the
161                 # reloadData one (that is called after the page changing.
162                 #
163                 # TODO: fix this awful code lines
164                 target = None
165                 return self.wizard().pageIndex(BToolchainPage)
166
167     ####
168     
169     ## Overloaded BWizardPage methods ##
170     
171     def reloadData(self, previous_id=None):
172         if not self.projectInfo("PRESET_LOADED"):
173             preset_path = self.projectInfo("PROJECT_BOARD")
174             preset_tree = self.projectInfo("PRESET_TREE")
175             preset_list = preset_tree["children"][preset_path]["children"]
176             preset_list = sorted(preset_list.values(), _cmp)
177             self.setTitle(self.tr("Select the project template for %1").arg(preset_tree["children"][preset_path]["info"].get("name", preset_tree["children"][preset_path]["info"]["filename"])))
178             self.setupTabs(preset_list)
179
180     def connectSignals(self):
181         self.connect(self.pageContent.boardTabWidget, SIGNAL("currentChanged(int)"), self, SIGNAL("completeChanged()"))
182
183     ####
184     
185     ## Slots ##
186     ####
187
188     def setupTabs(self, preset_list):
189         self.pageContent.boardTabWidget.clear()
190         for preset in preset_list:
191             icon = os.path.join(preset["info"]["path"], ".icon.png")
192             preset_page = BProjectPresetsPage(preset)
193             if os.path.exists(icon):
194                 self.pageContent.boardTabWidget.addTab(preset_page, QIcon(icon), preset["info"].get("name", preset["info"]["filename"]))
195             else:
196                 self.pageContent.boardTabWidget.addTab(preset_page, preset["info"].get("name", preset["info"]["filename"]))
197             self.connect(preset_page, SIGNAL("completeChanged()"), self, SIGNAL("completeChanged()"))
198
199     @property
200     def advanced(self):
201         if self.selected_data:
202             return self.selected_data["info"].get("advanced", False)
203         else:
204             return None
205
206     @property
207     def selected_path(self):
208         current_widget = self.pageContent.boardTabWidget.currentWidget()
209         preset_path = None
210         if current_widget:
211             current_item = current_widget.pageContent.presetList.currentItem()
212             if current_item:
213                 preset_path = current_item.data(Qt.UserRole)
214                 preset_path = qvariant_converter.getString(preset_path)
215         return preset_path
216
217     @property
218     def selected_data(self):
219         if self.selected_path:
220             current_widget = self.pageContent.boardTabWidget.currentWidget()
221             return current_widget.preset_data["children"][self.selected_path]
222         else:
223             return None