79165aab84b76ed90820a93de08c7f2de80330b1
[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         // TODO2: rewrite ExecutableComboBox and reimplement getSelected?
205         /*EmuFrontObject *obExe = execSelectBox->getSelected();
206         if (!obExe) {
207             throw EmuFrontException(tr("Failed fetching selected emulator!"));
208         }
209         exe = dynamic_cast<Executable*>(obExe);
210         if (!exe) {
211             throw EmuFrontException(tr("Failed creating Emulator object!"));
212         }*/
213
214         qDebug() << "File types; " << exe->getSetup()->getSupportedFileTypeExtensions().count();
215
216         bool mame = exe->getSetup()->getSupportedFileTypeExtensions().isEmpty();
217
218         if (mame && listMIndex.count() > 1) {
219             throw EmuFrontException(tr("No supported file types configured for this emulator configuration. "
220                 "Assuming emulator support container files as is. "
221                 "Only one container can be selected without configuring supported file types."
222             ));
223         }
224
225         // Now we have one or more media image containers and an emulator selected,
226         // let's fetch the media image container data.
227
228         foreach(QModelIndex mind, listMIndex) {
229             if (!mind.isValid()) continue;
230             EmuFrontObject *obImg = dbMic->getDataObjectFromModel(&mind); // throws EmuFrontException
231             if (!obImg) {
232                 qDebug() << "Failed creating media image container at row " << mind.row();
233                 continue;
234             }
235             MediaImageContainer *mic = dynamic_cast<MediaImageContainer*>(obImg);
236             if (!mic) {
237                 qDebug() << "Failed to create media image container for " << obImg->getName();
238                 delete obImg;
239                 continue;
240             }
241             mediaImageContainers << mic;
242             QMap<QString, EmuFrontObject*> contained = mic->getMediaImages();
243             mediaImages.unite(contained);
244         }
245
246         if (mame) {
247             emuHelper->launch(exe, mediaImageContainers);
248             return;
249         }
250         else {
251             // mediaImageContainers list contains all the selected media image containers and
252             // mediaImages list contains all the media images inside all the selected containers
253
254             QList<EmuFrontObject*> selectedImages;
255             if (mediaImages.count() < 1) {
256                 throw EmuFrontException("No media images available!");
257             }
258
259             // check if command options have slots for nr media images > 1 e.g. "-diska $1 -diskb $2 ..."
260             QString opts = exe->getOptions();
261             QRegExp rx("(\\$\\d+)");
262             QStringList list;
263             int pos = 0;
264             while ((pos = rx.indexIn(opts, pos)) != -1) {
265                 list << rx.cap(1);
266                 pos += rx.matchedLength();
267             }
268             bool ok;
269
270             if (list.count() > mediaImages.count()) {
271                 throw EmuFrontException(tr("Select %1 media images for this emulator configuration").arg(list.count()));
272             }
273             if (list.count() > 1) {
274                 // more than one placeholder for media image in the command line ($1, $2, ...)
275                 int lim = list.count() == mediaImages.count() ? list.count() - 1 : list.count();
276                 // user sets the order of media images
277                 for(int i = 0; i < lim; i++) {
278                     EmuFrontObject *efo = EmuFrontInputDialog::getItem(
279                             this, tr("Select image no. %1").arg(i+1), tr("Select"), mediaImages.values(), 0, false, &ok);
280                     if (!ok)  {
281                         throw EmuFrontException(tr("Boot image selection was canceled, aborting."));
282                     }
283                     selectedImages << efo;
284                     MediaImage *mi = dynamic_cast<MediaImage*>(efo);
285                     QString key = mi->getCheckSum();
286                     mediaImages.remove(key);
287                 }
288                 // there should be at least one media image left in mediaImages map...
289                 /*if (mediaImages.count() == 1) {
290                 selectedImages << mediaImages.values().first();
291             } ... this is added later-> */
292             }
293             else if (mediaImages.count() > 1) {
294                 // show select boot image dialog
295                 EmuFrontObject *efo = EmuFrontInputDialog::getItem(
296                         this, tr("Select boot image"), tr("Select"), mediaImages.values(), 0, false, &ok);
297                 if (!ok)  {
298                     throw EmuFrontException(tr("Boot image selection was canceled, aborting."));
299                 }
300                 selectedImages << efo;
301                 MediaImage *mi = dynamic_cast<MediaImage*>(efo);
302                 QString key = mi->getCheckSum();
303                 mediaImages.remove(key);
304             }
305             else if (mediaImages.count() == 1) {
306                 EmuFrontObject *efo = mediaImages.values().first();
307                 selectedImages << efo;
308                 MediaImage *mi = dynamic_cast<MediaImage*>(efo);
309                 QString key = mi->getCheckSum();
310                 mediaImages.remove(key);
311             }
312             // in all the both cases the (ordered) list of media images will be passed to emuHelper
313
314             // wee also keep the rest of the mediaimages in the selected containers for reference!
315             foreach(EmuFrontObject *efo, mediaImages) {
316                 selectedImages << efo;
317             }
318
319             if (selectedImages.count() < 1)
320                 throw EmuFrontException(tr("No media images selected"));
321
322             emuHelper->launch(exe, mediaImageContainers, selectedImages, list.count(), tmpDirPath);
323         }
324     } catch (EmuFrontException efe) {
325         errorMessage->showMessage(efe.what());
326     }
327
328     micTable->clearSelection();
329     if (exe) delete exe;
330     qDeleteAll(mediaImageContainers);
331     //qDeleteAll(mediaImages); these are already deleted along with containers
332 }
333
334 void EmuLauncher::processError(QProcess::ProcessError e)
335 {
336     cleanTmp();
337     QString stdErr = emuHelper->readAllStandardError();
338     QMessageBox::warning(this, tr("Emulator"),
339         tr("Launching emulator failed with: %1.\n").arg(e)
340         .append(";\n").append(emuHelper->errorString().append(";\n")
341         .append(stdErr)), QMessageBox::Ok );
342 }
343
344 /* Slot for EmuHelper process finished, clears the temporary folder files */
345 void EmuLauncher::processFinished(int a)
346 {
347     cleanTmp();
348     QString stdErr = emuHelper->readAllStandardError();
349     QString stdMsg = emuHelper->readAllStandardOutput();
350     QString msg = tr("Emulator has finished with: %1.\n").arg(a).append(stdMsg);
351     if (a) msg.append("; ").append(emuHelper->errorString()).append(";\n").append(stdErr);
352     QMessageBox::information(this, tr("Emulator finished"), msg, QMessageBox::Ok);
353 }
354
355 void EmuLauncher::cleanTmp()
356 {
357     // TODO
358 }
359
360 void EmuLauncher::setTmpDirPath(QString tmp)
361 {
362     tmpDirPath = tmp;
363 }