The core flow from creating a platform, a mediatype, a setup, media
[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 "setupmodel.h"
27 #include "externalexecutablemodel.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     dbMic = 0;
39     emuHelper = new EmuHelper(this);
40     initWidgets();
41     layout();
42     connectSignals();
43 }
44
45 EmuLauncher::~EmuLauncher()
46 {
47     if (emuHelper) {
48         qDebug() << "EmuLauncher destructor";
49         if (emuHelper->state() == EmuHelper::Running)
50             qDebug() << "EmuHelper process is running, killing...";
51             emuHelper->kill();
52         }
53 }
54
55 void EmuLauncher::updateData()
56 {
57 }
58
59 void EmuLauncher::initWidgets()
60 {
61     micTable = new QTableView(this);
62     micTable->setSelectionMode(QAbstractItemView::ExtendedSelection);
63     micTable->setCornerButtonEnabled(false);
64     micTable->verticalHeader()->setVisible(false);
65     micTable->horizontalHeader()->setClickable(false);
66
67     SetupModel *supModel = new SetupModel(this);
68     setupSelectBox = new QComboBox(this);
69     setupSelectBox->setModel(supModel);
70     setupSelectBox->setModelColumn(SetupModel::Setup_Name);
71
72     ExternalExecutableModel *emuModel = new ExternalExecutableModel(this);
73     execSelectBox = new QComboBox(this);
74     execSelectBox->setModel(emuModel);
75     execSelectBox->setModelColumn(ExternalExecutableModel::Executable_Name);
76
77     selectButton = new QPushButton(tr("&Update"), this);
78     launchButton = new QPushButton(tr("&Launch"), this);
79 }
80
81 void EmuLauncher::layout()
82 {
83     QGridLayout *grid = new QGridLayout;
84     grid->addWidget(setupSelectBox, 0, 0, 1, 2);
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     if (setupSelectBox->currentIndex() == -1) return;
106
107     // 1. get selected platform and media type id
108     QAbstractItemModel *setupAbsModel = setupSelectBox->model();
109     SetupModel *supModel = qobject_cast<SetupModel *>(setupAbsModel);
110     if (!supModel) return;
111     QModelIndex plfInd =
112         supModel->index(setupSelectBox->currentIndex(), SetupModel::Setup_PlatformId);
113     int plfid = supModel->data(plfInd).toInt();
114     QModelIndex mtInd =
115         supModel->index(setupSelectBox->currentIndex(), SetupModel::Setup_MediaTypeId);
116     int mtid = supModel->data(mtInd).toInt();
117
118     if (mtid < 0 || plfid < 0) return;
119
120     // 2. fetch available media image containers
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
136     // 3. filter available emulators
137     QModelIndex supInd =
138             supModel->index(setupSelectBox->currentIndex(), SetupModel::Setup_Id);
139     int supid = supModel->data(supInd).toInt();
140     QAbstractItemModel *execAbsModel = execSelectBox->model();
141     ExternalExecutableModel *execModel = qobject_cast<ExternalExecutableModel*>(execAbsModel);
142     if (!execModel) return;
143     execModel->filterBySetup(supid);
144 }
145
146 void EmuLauncher::launchEmu()
147 {
148     // if selected emulator has no extensions configured, it's assumed to be a M.A.M.E. or similar and
149     // map of media images will be no be used
150     QMap<QString, EmuFrontObject*> mediaImages;
151     QList<MediaImageContainer*> mediaImageContainers;
152     Executable *exe = 0;
153     try {
154         if (!micTable || !micTable->model()) {
155             throw EmuFrontException(tr("No search results available!"));
156         }
157         if (!execSelectBox || execSelectBox->currentIndex() == -1) {
158             throw EmuFrontException(tr("Emulator not selected!"));
159         }
160         QItemSelectionModel *selModel = micTable->selectionModel();
161         QModelIndexList listMIndex =  selModel->selectedIndexes();
162         if (listMIndex.count() < 1) {
163             throw EmuFrontException(tr("Media image container not selected!"));
164         }
165         qDebug() << listMIndex.count() << " items selected.";
166
167         QAbstractItemModel *absModel = execSelectBox->model();
168         ExternalExecutableModel *extModel = qobject_cast<ExternalExecutableModel*>(absModel);
169         exe = extModel->getExecutable(execSelectBox->currentIndex());
170         if (!exe) {
171             errorMessage->showMessage(tr("Failed creating an executable object from selection."));
172             return;
173         }
174
175         bool mame = exe->getSetup()->getSupportedFileTypeExtensions().isEmpty();
176
177         if (mame && listMIndex.count() > 1) {
178             throw EmuFrontException(tr("No supported file types configured for this emulator configuration. "
179                 "Assuming emulator support container files as is. "
180                 "Only one container can be selected without configuring supported file types."
181             ));
182         }
183
184         // Now we have one or more media image containers and an emulator selected,
185         // let's fetch the media image container data.
186
187         foreach(QModelIndex mind, listMIndex) {
188             if (!mind.isValid()) continue;
189             EmuFrontObject *obImg = dbMic->getDataObjectFromModel(&mind); // throws EmuFrontException
190             if (!obImg) {
191                 qDebug() << "Failed creating media image container at row " << mind.row();
192                 continue;
193             }
194             MediaImageContainer *mic = dynamic_cast<MediaImageContainer*>(obImg);
195             if (!mic) {
196                 qDebug() << "Failed to create media image container for " << obImg->getName();
197                 delete obImg;
198                 continue;
199             }
200             mediaImageContainers << mic;
201             QMap<QString, EmuFrontObject*> contained = mic->getMediaImages();
202             mediaImages.unite(contained);
203         }
204
205         if (mame) {
206             emuHelper->launch(exe, mediaImageContainers);
207             return;
208         }
209         else {
210             // mediaImageContainers list contains all the selected media image containers and
211             // mediaImages list contains all the media images inside all the selected containers
212
213             QList<EmuFrontObject*> selectedImages;
214             if (mediaImages.count() < 1) {
215                 throw EmuFrontException("No media images available!");
216             }
217
218             // check if command options have slots for nr media images > 1 e.g. "-diska $1 -diskb $2 ..."
219             QString opts = exe->getOptions();
220             QRegExp rx("(\\$\\d+)");
221             QStringList list;
222             int pos = 0;
223             while ((pos = rx.indexIn(opts, pos)) != -1) {
224                 list << rx.cap(1);
225                 pos += rx.matchedLength();
226             }
227             bool ok;
228
229             if (list.count() > mediaImages.count()) {
230                 throw EmuFrontException(tr("Select %1 media images for this emulator configuration").arg(list.count()));
231             }
232             if (list.count() > 1) {
233                 // more than one placeholder for media image in the command line ($1, $2, ...)
234                 int lim = list.count() == mediaImages.count() ? list.count() - 1 : list.count();
235                 // user sets the order of media images
236                 for(int i = 0; i < lim; i++) {
237                     EmuFrontObject *efo = EmuFrontInputDialog::getItem(
238                             this, tr("Select image no. %1").arg(i+1), tr("Select"), mediaImages.values(), 0, false, &ok);
239                     if (!ok)  {
240                         throw EmuFrontException(tr("Boot image selection was canceled, aborting."));
241                     }
242                     selectedImages << efo;
243                     MediaImage *mi = dynamic_cast<MediaImage*>(efo);
244                     QString key = mi->getCheckSum();
245                     mediaImages.remove(key);
246                 }
247                 // there should be at least one media image left in mediaImages map...
248                 /*if (mediaImages.count() == 1) {
249                 selectedImages << mediaImages.values().first();
250             } ... this is added later-> */
251             }
252             else if (mediaImages.count() > 1) {
253                 // show select boot image dialog
254                 EmuFrontObject *efo = EmuFrontInputDialog::getItem(
255                         this, tr("Select boot image"), tr("Select"), mediaImages.values(), 0, false, &ok);
256                 if (!ok)  {
257                     throw EmuFrontException(tr("Boot image selection was canceled, aborting."));
258                 }
259                 selectedImages << efo;
260                 MediaImage *mi = dynamic_cast<MediaImage*>(efo);
261                 QString key = mi->getCheckSum();
262                 mediaImages.remove(key);
263             }
264             else if (mediaImages.count() == 1) {
265                 EmuFrontObject *efo = mediaImages.values().first();
266                 selectedImages << efo;
267                 MediaImage *mi = dynamic_cast<MediaImage*>(efo);
268                 QString key = mi->getCheckSum();
269                 mediaImages.remove(key);
270             }
271             // in all the both cases the (ordered) list of media images will be passed to emuHelper
272
273             // wee also keep the rest of the mediaimages in the selected containers for reference!
274             foreach(EmuFrontObject *efo, mediaImages) {
275                 selectedImages << efo;
276             }
277
278             if (selectedImages.count() < 1)
279                 throw EmuFrontException(tr("No media images selected"));
280
281             emuHelper->launch(exe, mediaImageContainers, selectedImages, list.count(), tmpDirPath);
282         }
283     } catch (EmuFrontException efe) {
284         errorMessage->showMessage(efe.what());
285     }
286
287     micTable->clearSelection();
288     if (exe) delete exe;
289     qDeleteAll(mediaImageContainers);
290     //qDeleteAll(mediaImages); these are already deleted along with containers
291 }
292
293 void EmuLauncher::processError(QProcess::ProcessError e)
294 {
295     cleanTmp();
296     QString stdErr = emuHelper->readAllStandardError();
297     QMessageBox::warning(this, tr("Emulator"),
298         tr("Launching emulator failed with: %1.\n").arg(e)
299         .append(";\n").append(emuHelper->errorString().append(";\n")
300         .append(stdErr)), QMessageBox::Ok );
301 }
302
303 /* Slot for EmuHelper process finished, clears the temporary folder files */
304 void EmuLauncher::processFinished(int a)
305 {
306     cleanTmp();
307     QString stdErr = emuHelper->readAllStandardError();
308     QString stdMsg = emuHelper->readAllStandardOutput();
309     QString msg = tr("Emulator has finished with: %1.\n").arg(a).append(stdMsg);
310     if (a) msg.append("; ").append(emuHelper->errorString()).append(";\n").append(stdErr);
311     QMessageBox::information(this, tr("Emulator finished"), msg, QMessageBox::Ok);
312 }
313
314 void EmuLauncher::cleanTmp()
315 {
316     // TODO
317 }
318
319 void EmuLauncher::setTmpDirPath(QString tmp)
320 {
321     tmpDirPath = tmp;
322 }