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