Added some exception handling. Marked all the functions throwing
[emufront] / src / emulauncher.cpp
1 // EmuFront
2 // Copyright 2010 Mikko Keinänen
3 //
4 // This file is part of EmuFront.
5 //
6 //
7 // EmuFront is free software: you can redistribute it and/or modify
8 // it under the terms of the GNU General Public License version 2 as published by
9 // the Free Software Foundation and appearing in the file gpl.txt included in the
10 // packaging of this file.
11 //
12 // EmuFront is distributed in the hope that it will be useful,
13 // but WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 // GNU General Public License for more details.
16 //
17 // You should have received a copy of the GNU General Public License
18 // along with EmuFront.  If not, see <http://www.gnu.org/licenses/>.
19
20 #include <QtGui>
21 #include <QProcess>
22 #include <QSqlTableModel>
23 #include <QItemSelectionModel>
24 #include "emulauncher.h"
25 #include "db/dbmediatype.h"
26 #include "db/dbplatform.h"
27 #include "db/dbexecutable.h"
28 #include "db/dbmediaimagecontainer.h"
29 #include "widgets/effileobjectcombobox.h"
30 #include "widgets/executablecombobox.h"
31 #include "dataobjects/executable.h"
32 #include "utils/emuhelper.h"
33 #include "dialogs/emufrontinputdialog.h"
34
35 EmuLauncher::EmuLauncher(QWidget *parent, QString tmp) :
36     QWidget(parent), tmpDirPath(tmp)
37 {
38     dbPlatform = new DbPlatform(this);
39     dbMediaType = new DbMediaType(this);
40     dbExec = new DbExecutable(this);
41     dbMic = 0;
42     emuHelper = new EmuHelper(this);
43     initWidgets();
44     layout();
45     connectSignals();
46 }
47
48 EmuLauncher::~EmuLauncher()
49 {
50     if (emuHelper) {
51         qDebug() << "EmuLauncher destructor";
52         if (emuHelper->state() == EmuHelper::Running)
53             qDebug() << "EmuHelper process is running, killing...";
54             emuHelper->kill();
55         }
56 }
57
58 void EmuLauncher::updateData()
59 {
60     platformSelectBox->updateDataModel();
61     mediaTypeSelectBox->updateDataModel();
62     //execSelectBox->updateDataModel();
63 }
64
65 void EmuLauncher::initWidgets()
66 {
67     micTable = new QTableView(this);
68     micTable->setSelectionMode(QAbstractItemView::ExtendedSelection);
69     micTable->setCornerButtonEnabled(false);
70     micTable->verticalHeader()->setVisible(false);
71     //micTable->horizontalHeader()->setDisabled(true);
72     micTable->horizontalHeader()->setClickable(false);
73     mediaTypeSelectBox = new EFFileObjectComboBox(dbMediaType, this);
74     platformSelectBox = new EFFileObjectComboBox(dbPlatform, this);
75     execSelectBox = new ExecutableComboBox(dbExec, this);
76     selectButton = new QPushButton(tr("&Update"), this);
77     launchButton = new QPushButton(tr("&Launch"), this);
78 }
79
80 void EmuLauncher::layout()
81 {
82     QGridLayout *grid = new QGridLayout;
83     grid->addWidget(platformSelectBox, 0, 0);
84     grid->addWidget(mediaTypeSelectBox, 0, 1);
85     grid->addWidget(selectButton, 0, 2);
86     grid->setColumnStretch(3, 1);
87
88     grid->addWidget(micTable, 1, 0, 1, 4);
89     grid->addWidget(execSelectBox, 2, 0);
90     grid->addWidget(launchButton, 2, 1);
91     // grid will be implicitily parented to this
92     setLayout(grid);
93 }
94
95 void EmuLauncher::connectSignals()
96 {
97     connect(selectButton, SIGNAL(clicked()), this, SLOT(updateMediaImageContainers()));
98     connect(launchButton, SIGNAL(clicked()),this, SLOT(launchEmu()));
99     connect(emuHelper, SIGNAL(error(QProcess::ProcessError)), this, SLOT(processError(QProcess::ProcessError)));
100     connect(emuHelper, SIGNAL(finished(int)), this, SLOT(processFinished(int)));
101 }
102
103 void EmuLauncher::updateMediaImageContainers()
104 {
105     qDebug() << "updateMediaImageContainers slot";
106     int mtid, plfid = -1;
107     try {
108         mtid = mediaTypeSelectBox->getSelected()
109                    ? mediaTypeSelectBox->getSelected()->getId()
110                    : -1;
111         plfid = platformSelectBox->getSelected()
112                     ? platformSelectBox->getSelected()->getId()
113                     : -1;
114     }
115     catch(EmuFrontException &e){
116         QMessageBox::warning(this, "Exception", e.what());
117         return;
118     }
119
120     if (!dbMic) dbMic = new DbMediaImageContainer(this);
121     dbMic->filter(mtid, plfid);
122     micTable->setModel(dbMic->getDataModel());
123     micTable->hideColumn(DbMediaImageContainer::MIC_FileId);
124     micTable->hideColumn(DbMediaImageContainer::MIC_FileSize);
125     micTable->hideColumn(DbMediaImageContainer::MIC_FileCheckSum);
126     micTable->hideColumn(DbMediaImageContainer::MIC_FilePathId);
127     micTable->hideColumn(DbMediaImageContainer::MIC_FilePathName);
128     micTable->hideColumn(DbMediaImageContainer::MIC_SetupId);
129     micTable->hideColumn(DbMediaImageContainer::MIC_PlatformName);
130     micTable->hideColumn(DbMediaImageContainer::MIC_PlatformId);
131     micTable->hideColumn(DbMediaImageContainer::MIC_MediaTypeName);
132     micTable->hideColumn(DbMediaImageContainer::MIC_MediaTypeId);
133     micTable->resizeColumnsToContents();
134     platformSelectBox->updateDataModel();
135     mediaTypeSelectBox->updateDataModel();
136     execSelectBox->updateToSetup(plfid, mtid);
137 }
138
139 void EmuLauncher::launchEmu()
140 {
141     // if selected emulator has no extensions configured, it's assumed to be a M.A.M.E. or similar and
142     // map of media images will be no be used
143     QMap<QString, EmuFrontObject*> mediaImages;
144     QList<MediaImageContainer*> mediaImageContainers;
145     Executable *exe = 0;
146     try {
147         if (!micTable || !micTable->model()) {
148             throw EmuFrontException(tr("No search results available!"));
149         }
150         if (!execSelectBox || execSelectBox->currentIndex() == -1) {
151             throw EmuFrontException(tr("Emulator not selected!"));
152         }
153         QItemSelectionModel *selModel = micTable->selectionModel();
154         QModelIndexList listMIndex =  selModel->selectedIndexes();
155         if (listMIndex.count() < 1) {
156             throw EmuFrontException(tr("Media image container not selected!"));
157         }
158         qDebug() << listMIndex.count() << " items selected.";
159
160         EmuFrontObject *obExe = execSelectBox->getSelected();
161         if (!obExe) {
162             throw EmuFrontException(tr("Failed fetching selected emulator!"));
163         }
164         exe = dynamic_cast<Executable*>(obExe);
165         if (!exe) {
166             throw EmuFrontException(tr("Failed creating Emulator object!"));
167         }
168
169
170         qDebug() << "File types; " << exe->getSetup()->getSupportedFileTypeExtensions().count();
171
172         bool mame = exe->getSetup()->getSupportedFileTypeExtensions().isEmpty();
173
174
175
176         if (mame && listMIndex.count() > 1) {
177             throw EmuFrontException(tr("No supported file types configured for this emulator configuration. "
178                 "Assuming emulator support container files as is. "
179                 "Only one container can be selected without configuring supported file types."
180             ));
181         }
182
183
184         // Now we have one or more media image containers and an emulator selected,
185         // let's fetch the media image container data.
186
187         foreach(QModelIndex mind, listMIndex) {
188             if (!mind.isValid()) continue;
189             EmuFrontObject *obImg = dbMic->getDataObjectFromModel(&mind);
190             if (!obImg) {
191                 qDebug() << "Failed creating media image container at row " << mind.row();
192                 continue;
193             }
194             MediaImageContainer *mic = dynamic_cast<MediaImageContainer*>(obImg);
195             if (!mic) {
196                 qDebug() << "Failed to create media image container for " << obImg->getName();
197                 delete obImg;
198                 continue;
199             }
200             mediaImageContainers << mic;
201             QMap<QString, EmuFrontObject*> contained = mic->getMediaImages();
202             mediaImages.unite(contained);
203         }
204
205         if (mame) {
206             emuHelper->launch(exe, mediaImageContainers);
207             return;
208         }
209
210         // mediaImageContainers list contains all the selected media image containers and
211         // mediaImages list contains all the media images inside all the selected containers
212
213
214         QList<EmuFrontObject*> selectedImages;
215         if (mediaImages.count() < 1) {
216             throw EmuFrontException("No media images available!");
217         }
218
219         // check if command options have slots for nr media images > 1 e.g. "-diska $1 -diskb $2 ..."
220         QString opts = exe->getOptions();
221         QRegExp rx("(\\$\\d+)");
222         QStringList list;
223         int pos = 0;
224         while ((pos = rx.indexIn(opts, pos)) != -1) {
225             list << rx.cap(1);
226             pos += rx.matchedLength();
227         }
228         bool ok;
229
230         if (list.count() > mediaImages.count()) {
231             throw EmuFrontException(tr("Select %1 media images for this emulator configuration").arg(list.count()));
232         }
233         if (list.count() > 1) {
234             // more than one placeholder for media image in the command line ($1, $2, ...)
235             int lim = list.count() == mediaImages.count() ? list.count() - 1 : list.count();
236             // user sets the order of media images
237             for(int i = 0; i < lim; i++) {
238                 EmuFrontObject *efo = EmuFrontInputDialog::getItem(
239                         this, tr("Select image no. %1").arg(i+1), tr("Select"), mediaImages.values(), 0, false, &ok);
240                 if (!ok)  {
241                     throw EmuFrontException(tr("Boot image selection was canceled, aborting."));
242                 }
243                 selectedImages << efo;
244                 MediaImage *mi = dynamic_cast<MediaImage*>(efo);
245                 QString key = mi->getCheckSum();
246                 mediaImages.remove(key);
247             }
248             // there should be at least one media image left in mediaImages map...
249             /*if (mediaImages.count() == 1) {
250                 selectedImages << mediaImages.values().first();
251             } ... this is added later-> */
252         }
253         else if (mediaImages.count() > 1) {
254             // show select boot image dialog
255             EmuFrontObject *efo = EmuFrontInputDialog::getItem(
256                     this, tr("Select boot image"), tr("Select"), mediaImages.values(), 0, false, &ok);
257             if (!ok)  {
258                 throw EmuFrontException(tr("Boot image selection was canceled, aborting."));
259             }
260             selectedImages << efo;
261             MediaImage *mi = dynamic_cast<MediaImage*>(efo);
262             QString key = mi->getCheckSum();
263             mediaImages.remove(key);
264         }
265         else if (mediaImages.count() == 1) {
266             EmuFrontObject *efo = mediaImages.values().first();
267             selectedImages << efo;
268             MediaImage *mi = dynamic_cast<MediaImage*>(efo);
269             QString key = mi->getCheckSum();
270             mediaImages.remove(key);
271         }
272         // in all the both cases the (ordered) list of media images will be passed to emuHelper
273
274         // wee also keep the rest of the mediaimages in the selected containers for reference!
275         foreach(EmuFrontObject *efo, mediaImages) {
276             selectedImages << efo;
277         }
278
279         if (selectedImages.count() < 1)
280             throw EmuFrontException(tr("No media images selected"));
281
282         emuHelper->launch(exe, mediaImageContainers, selectedImages, list.count(), tmpDirPath);
283         micTable->clearSelection();
284     } catch (EmuFrontException efe) {
285         if (exe) delete exe;
286         qDeleteAll(mediaImageContainers);
287         //qDeleteAll(mediaImages); these are already deleted along with containers
288         QMessageBox::information(this, tr("Launching emulator"),
289                                  efe.what(), QMessageBox::Ok);
290         return;
291     }
292 }
293
294 void EmuLauncher::processError(QProcess::ProcessError e)
295 {
296     cleanTmp();
297     QString stdErr = emuHelper->readAllStandardError();
298     QMessageBox::warning(this, tr("Emulator"),
299         tr("Launching emulator failed with: %1.\n").arg(e)
300         .append(";\n").append(emuHelper->errorString().append(";\n")
301         .append(stdErr)), QMessageBox::Ok );
302 }
303
304 /* Slot for EmuHelper process finished, clears the temporary folder files */
305 void EmuLauncher::processFinished(int a)
306 {
307     cleanTmp();
308     QString stdErr = emuHelper->readAllStandardError();
309     QString stdMsg = emuHelper->readAllStandardOutput();
310     QString msg = tr("Emulator has finished with: %1.\n").arg(a).append(stdMsg);
311     if (a) msg.append("; ").append(emuHelper->errorString()).append(";\n").append(stdErr);
312     QMessageBox::information(this, tr("Emulator finished"), msg, QMessageBox::Ok);
313 }
314
315 void EmuLauncher::cleanTmp()
316 {
317     // TODO
318 }
319
320 void EmuLauncher::setTmpDirPath(QString tmp)
321 {
322     tmpDirPath = tmp;
323 }