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