8e95a53aa4996445fd87795fd3371965ea626cea
[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 "dbmediatype.h"
26 #include "dbplatform.h"
27 #include "dbexecutable.h"
28 #include "dbmediaimagecontainer.h"
29 #include "effileobjectcombobox.h"
30 #include "executablecombobox.h"
31 #include "executable.h"
32 #include "emuhelper.h"
33 #include "emufrontinputdialog.h"
34
35 EmuLauncher::EmuLauncher(QErrorMessage *errorMessage, QWidget *parent, QString tmp) :
36     QWidget(parent), tmpDirPath(tmp), errorMessage(errorMessage)
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 implicitly 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     int mtid, plfid = -1;
106     MediaType *mt = 0;
107     Platform *plf = 0;
108     try {
109         mt = dynamic_cast<MediaType*>(mediaTypeSelectBox->getSelected());
110         plf = dynamic_cast<Platform*>(platformSelectBox->getSelected());
111     }
112     catch(EmuFrontException &e){
113         errorMessage->showMessage(e.what());
114         return;
115     }
116     mtid = mt ? mt->getId() : -1;
117     plfid = plf ? plf->getId() : -1;
118     if (mt) delete mt;
119     if (plf) delete plf;
120
121     if (!dbMic) dbMic = new DbMediaImageContainer(this);
122     dbMic->filter(mtid, plfid);
123     micTable->setModel(dbMic->getDataModel());
124     micTable->hideColumn(DbMediaImageContainer::MIC_FileId);
125     micTable->hideColumn(DbMediaImageContainer::MIC_FileSize);
126     micTable->hideColumn(DbMediaImageContainer::MIC_FileCheckSum);
127     micTable->hideColumn(DbMediaImageContainer::MIC_FilePathId);
128     micTable->hideColumn(DbMediaImageContainer::MIC_FilePathName);
129     micTable->hideColumn(DbMediaImageContainer::MIC_SetupId);
130     micTable->hideColumn(DbMediaImageContainer::MIC_PlatformName);
131     micTable->hideColumn(DbMediaImageContainer::MIC_PlatformId);
132     micTable->hideColumn(DbMediaImageContainer::MIC_MediaTypeName);
133     micTable->hideColumn(DbMediaImageContainer::MIC_MediaTypeId);
134     micTable->resizeColumnsToContents();
135     execSelectBox->updateToSetup(plfid, mtid);
136 }
137
138 void EmuLauncher::launchEmu()
139 {
140     // if selected emulator has no extensions configured, it's assumed to be a M.A.M.E. or similar and
141     // map of media images will be no be used
142     QMap<QString, EmuFrontObject*> mediaImages;
143     QList<MediaImageContainer*> mediaImageContainers;
144     Executable *exe = 0;
145     try {
146         if (!micTable || !micTable->model()) {
147             throw EmuFrontException(tr("No search results available!"));
148         }
149         if (!execSelectBox || execSelectBox->currentIndex() == -1) {
150             throw EmuFrontException(tr("Emulator not selected!"));
151         }
152         QItemSelectionModel *selModel = micTable->selectionModel();
153         QModelIndexList listMIndex =  selModel->selectedIndexes();
154         if (listMIndex.count() < 1) {
155             throw EmuFrontException(tr("Media image container not selected!"));
156         }
157         qDebug() << listMIndex.count() << " items selected.";
158
159         EmuFrontObject *obExe = execSelectBox->getSelected();
160         if (!obExe) {
161             throw EmuFrontException(tr("Failed fetching selected emulator!"));
162         }
163         exe = dynamic_cast<Executable*>(obExe);
164         if (!exe) {
165             throw EmuFrontException(tr("Failed creating Emulator object!"));
166         }
167
168         qDebug() << "File types; " << exe->getSetup()->getSupportedFileTypeExtensions().count();
169
170         bool mame = exe->getSetup()->getSupportedFileTypeExtensions().isEmpty();
171
172         if (mame && listMIndex.count() > 1) {
173             throw EmuFrontException(tr("No supported file types configured for this emulator configuration. "
174                 "Assuming emulator support container files as is. "
175                 "Only one container can be selected without configuring supported file types."
176             ));
177         }
178
179         // Now we have one or more media image containers and an emulator selected,
180         // let's fetch the media image container data.
181
182         foreach(QModelIndex mind, listMIndex) {
183             if (!mind.isValid()) continue;
184             EmuFrontObject *obImg = dbMic->getDataObjectFromModel(&mind); // throws EmuFrontException
185             if (!obImg) {
186                 qDebug() << "Failed creating media image container at row " << mind.row();
187                 continue;
188             }
189             MediaImageContainer *mic = dynamic_cast<MediaImageContainer*>(obImg);
190             if (!mic) {
191                 qDebug() << "Failed to create media image container for " << obImg->getName();
192                 delete obImg;
193                 continue;
194             }
195             mediaImageContainers << mic;
196             QMap<QString, EmuFrontObject*> contained = mic->getMediaImages();
197             mediaImages.unite(contained);
198         }
199
200         if (mame) {
201             emuHelper->launch(exe, mediaImageContainers);
202             return;
203         }
204         else {
205             // mediaImageContainers list contains all the selected media image containers and
206             // mediaImages list contains all the media images inside all the selected containers
207
208             QList<EmuFrontObject*> selectedImages;
209             if (mediaImages.count() < 1) {
210                 throw EmuFrontException("No media images available!");
211             }
212
213             // check if command options have slots for nr media images > 1 e.g. "-diska $1 -diskb $2 ..."
214             QString opts = exe->getOptions();
215             QRegExp rx("(\\$\\d+)");
216             QStringList list;
217             int pos = 0;
218             while ((pos = rx.indexIn(opts, pos)) != -1) {
219                 list << rx.cap(1);
220                 pos += rx.matchedLength();
221             }
222             bool ok;
223
224             if (list.count() > mediaImages.count()) {
225                 throw EmuFrontException(tr("Select %1 media images for this emulator configuration").arg(list.count()));
226             }
227             if (list.count() > 1) {
228                 // more than one placeholder for media image in the command line ($1, $2, ...)
229                 int lim = list.count() == mediaImages.count() ? list.count() - 1 : list.count();
230                 // user sets the order of media images
231                 for(int i = 0; i < lim; i++) {
232                     EmuFrontObject *efo = EmuFrontInputDialog::getItem(
233                             this, tr("Select image no. %1").arg(i+1), tr("Select"), mediaImages.values(), 0, false, &ok);
234                     if (!ok)  {
235                         throw EmuFrontException(tr("Boot image selection was canceled, aborting."));
236                     }
237                     selectedImages << efo;
238                     MediaImage *mi = dynamic_cast<MediaImage*>(efo);
239                     QString key = mi->getCheckSum();
240                     mediaImages.remove(key);
241                 }
242                 // there should be at least one media image left in mediaImages map...
243                 /*if (mediaImages.count() == 1) {
244                 selectedImages << mediaImages.values().first();
245             } ... this is added later-> */
246             }
247             else if (mediaImages.count() > 1) {
248                 // show select boot image dialog
249                 EmuFrontObject *efo = EmuFrontInputDialog::getItem(
250                         this, tr("Select boot image"), tr("Select"), mediaImages.values(), 0, false, &ok);
251                 if (!ok)  {
252                     throw EmuFrontException(tr("Boot image selection was canceled, aborting."));
253                 }
254                 selectedImages << efo;
255                 MediaImage *mi = dynamic_cast<MediaImage*>(efo);
256                 QString key = mi->getCheckSum();
257                 mediaImages.remove(key);
258             }
259             else if (mediaImages.count() == 1) {
260                 EmuFrontObject *efo = mediaImages.values().first();
261                 selectedImages << efo;
262                 MediaImage *mi = dynamic_cast<MediaImage*>(efo);
263                 QString key = mi->getCheckSum();
264                 mediaImages.remove(key);
265             }
266             // in all the both cases the (ordered) list of media images will be passed to emuHelper
267
268             // wee also keep the rest of the mediaimages in the selected containers for reference!
269             foreach(EmuFrontObject *efo, mediaImages) {
270                 selectedImages << efo;
271             }
272
273             if (selectedImages.count() < 1)
274                 throw EmuFrontException(tr("No media images selected"));
275
276             emuHelper->launch(exe, mediaImageContainers, selectedImages, list.count(), tmpDirPath);
277         }
278     } catch (EmuFrontException efe) {
279         errorMessage->showMessage(efe.what());
280     }
281
282     micTable->clearSelection();
283     if (exe) delete exe;
284     qDeleteAll(mediaImageContainers);
285     //qDeleteAll(mediaImages); these are already deleted along with containers
286 }
287
288 void EmuLauncher::processError(QProcess::ProcessError e)
289 {
290     cleanTmp();
291     QString stdErr = emuHelper->readAllStandardError();
292     QMessageBox::warning(this, tr("Emulator"),
293         tr("Launching emulator failed with: %1.\n").arg(e)
294         .append(";\n").append(emuHelper->errorString().append(";\n")
295         .append(stdErr)), QMessageBox::Ok );
296 }
297
298 /* Slot for EmuHelper process finished, clears the temporary folder files */
299 void EmuLauncher::processFinished(int a)
300 {
301     cleanTmp();
302     QString stdErr = emuHelper->readAllStandardError();
303     QString stdMsg = emuHelper->readAllStandardOutput();
304     QString msg = tr("Emulator has finished with: %1.\n").arg(a).append(stdMsg);
305     if (a) msg.append("; ").append(emuHelper->errorString()).append(";\n").append(stdErr);
306     QMessageBox::information(this, tr("Emulator finished"), msg, QMessageBox::Ok);
307 }
308
309 void EmuLauncher::cleanTmp()
310 {
311     // TODO
312 }
313
314 void EmuLauncher::setTmpDirPath(QString tmp)
315 {
316     tmpDirPath = tmp;
317 }