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