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