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