Fixed bugs: dialogs remained disabled (signals were not attached to
[emufront] / src / emulauncher.cpp
1 // EmuFront
2 // Copyright 2010 Mikko Keinänen
3 //
4 // This file is part of EmuFront.
5 //
6 //
7 // EmuFront is free software: you can redistribute it and/or modify
8 // it under the terms of the GNU General Public License version 2 as published by
9 // the Free Software Foundation and appearing in the file gpl.txt included in the
10 // packaging of this file.
11 //
12 // EmuFront is distributed in the hope that it will be useful,
13 // but WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 // GNU General Public License for more details.
16 //
17 // You should have received a copy of the GNU General Public License
18 // along with EmuFront.  If not, see <http://www.gnu.org/licenses/>.
19
20 #include <QtGui>
21 #include <QProcess>
22 #include <QSqlTableModel>
23 #include <QItemSelectionModel>
24 #include "emulauncher.h"
25 #include "db/dbmediatype.h"
26 #include "db/dbplatform.h"
27 #include "db/dbexecutable.h"
28 #include "db/dbmediaimagecontainer.h"
29 #include "widgets/effileobjectcombobox.h"
30 #include "widgets/executablecombobox.h"
31 #include "dataobjects/executable.h"
32 #include "utils/emuhelper.h"
33 #include "dialogs/emufrontinputdialog.h"
34
35 EmuLauncher::EmuLauncher(QWidget *parent, QString tmp) :
36     QWidget(parent), tmpDirPath(tmp)
37 {
38     dbPlatform = new DbPlatform(this);
39     dbMediaType = new DbMediaType(this);
40     dbExec = new DbExecutable(this);
41     dbMic = 0;
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     platformSelectBox->updateDataModel();
61     mediaTypeSelectBox->updateDataModel();
62     //execSelectBox->updateDataModel();
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()->setDisabled(true);
72     micTable->horizontalHeader()->setClickable(false);
73     mediaTypeSelectBox = new EFFileObjectComboBox(dbMediaType, this);
74     platformSelectBox = new EFFileObjectComboBox(dbPlatform, this);
75     execSelectBox = new ExecutableComboBox(dbExec, this);
76     selectButton = new QPushButton(tr("&Update"), this);
77     launchButton = new QPushButton(tr("&Launch"), this);
78 }
79
80 void EmuLauncher::layout()
81 {
82     QGridLayout *grid = new QGridLayout;
83     grid->addWidget(platformSelectBox, 0, 0);
84     grid->addWidget(mediaTypeSelectBox, 0, 1);
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 implicitily 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     qDebug() << "updateMediaImageContainers slot";
106     int mtid = mediaTypeSelectBox->getSelected()
107         ? mediaTypeSelectBox->getSelected()->getId()
108         : -1;
109     int plfid = platformSelectBox->getSelected()
110         ? platformSelectBox->getSelected()->getId()
111         : -1;
112
113     if (!dbMic) dbMic = new DbMediaImageContainer(this);
114     dbMic->filter(mtid, plfid);
115     micTable->setModel(dbMic->getDataModel());
116     micTable->hideColumn(DbMediaImageContainer::MIC_FileId);
117     micTable->hideColumn(DbMediaImageContainer::MIC_FileSize);
118     micTable->hideColumn(DbMediaImageContainer::MIC_FileCheckSum);
119     micTable->hideColumn(DbMediaImageContainer::MIC_FilePathId);
120     micTable->hideColumn(DbMediaImageContainer::MIC_FilePathName);
121     micTable->hideColumn(DbMediaImageContainer::MIC_SetupId);
122     micTable->hideColumn(DbMediaImageContainer::MIC_PlatformName);
123     micTable->hideColumn(DbMediaImageContainer::MIC_PlatformId);
124     micTable->hideColumn(DbMediaImageContainer::MIC_MediaTypeName);
125     micTable->hideColumn(DbMediaImageContainer::MIC_MediaTypeId);
126     micTable->resizeColumnsToContents();
127     platformSelectBox->updateDataModel();
128     mediaTypeSelectBox->updateDataModel();
129     execSelectBox->updateToSetup(plfid, mtid);
130 }
131
132 void EmuLauncher::launchEmu()
133 {
134     // if selected emulator has no extensions configured, it's assumed to be a M.A.M.E. or similar and
135     // map of media images will be no be used
136     QMap<QString, EmuFrontObject*> mediaImages;
137     QList<MediaImageContainer*> mediaImageContainers;
138     Executable *exe = 0;
139     try {
140         if (!micTable || !micTable->model()) {
141             throw EmuFrontException(tr("No search results available!"));
142         }
143         if (!execSelectBox || execSelectBox->currentIndex() == -1) {
144             throw EmuFrontException(tr("Emulator not selected!"));
145         }
146         QItemSelectionModel *selModel = micTable->selectionModel();
147         QModelIndexList listMIndex =  selModel->selectedIndexes();
148         if (listMIndex.count() < 1) {
149             throw EmuFrontException(tr("Media image container not selected!"));
150         }
151         qDebug() << listMIndex.count() << " items selected.";
152
153         EmuFrontObject *obExe = execSelectBox->getSelected();
154         if (!obExe) {
155             throw EmuFrontException(tr("Failed fetching selected emulator!"));
156         }
157         exe = dynamic_cast<Executable*>(obExe);
158         if (!exe) {
159             throw EmuFrontException(tr("Failed creating Emulator object!"));
160         }
161
162
163         qDebug() << "File types; " << exe->getSetup()->getSupportedFileTypeExtensions().count();
164
165         bool mame = exe->getSetup()->getSupportedFileTypeExtensions().isEmpty();
166
167
168
169         if (mame && listMIndex.count() > 1) {
170             throw new EmuFrontException(tr("No supported file types configured for this emulator configuration. "
171                 "Assuming emulator support container files as is. "
172                 "Only one container can be selected without configuring supported file types."
173             ));
174         }
175
176
177         // Now we have one or more media image containers and an emulator selected,
178         // let's fetch the media image container data.
179
180         foreach(QModelIndex mind, listMIndex) {
181             if (!mind.isValid()) continue;
182             EmuFrontObject *obImg = dbMic->getDataObjectFromModel(&mind);
183             if (!obImg) {
184                 qDebug() << "Failed creating media image container at row " << mind.row();
185                 continue;
186             }
187             MediaImageContainer *mic = dynamic_cast<MediaImageContainer*>(obImg);
188             if (!mic) {
189                 qDebug() << "Failed to create media image container for " << obImg->getName();
190                 delete obImg;
191                 continue;
192             }
193             mediaImageContainers << mic;
194             QMap<QString, EmuFrontObject*> contained = mic->getMediaImages();
195             mediaImages.unite(contained);
196         }
197
198         if (mame) {
199             emuHelper->launch(exe, mediaImageContainers);
200             return;
201         }
202
203         // mediaImageContainers list contains all the selected media image containers and
204         // mediaImages list contains all the media images inside all the selected containers
205
206
207         QList<EmuFrontObject*> selectedImages;
208         if (mediaImages.count() < 1) {
209             throw EmuFrontException("No media images available!");
210         }
211
212         // check if command options have slots for nr media images > 1 e.g. "-diska $1 -diskb $2 ..."
213         QString opts = exe->getOptions();
214         QRegExp rx("(\\$\\d+)");
215         QStringList list;
216         int pos = 0;
217         while ((pos = rx.indexIn(opts, pos)) != -1) {
218             list << rx.cap(1);
219             pos += rx.matchedLength();
220         }
221         bool ok;
222
223         if (list.count() > mediaImages.count()) {
224             throw EmuFrontException(tr("Select %1 media images for this emulator configuration").arg(list.count()));
225         }
226         if (list.count() > 1) {
227             // more than one placeholder for media image in the command line ($1, $2, ...)
228             int lim = list.count() == mediaImages.count() ? list.count() - 1 : list.count();
229             // user sets the order of media images
230             for(int i = 0; i < lim; i++) {
231                 EmuFrontObject *efo = EmuFrontInputDialog::getItem(
232                         this, tr("Select image no. %1").arg(i+1), tr("Select"), mediaImages.values(), 0, false, &ok);
233                 if (!ok)  {
234                     throw EmuFrontException(tr("Boot image selection was canceled, aborting."));
235                 }
236                 selectedImages << efo;
237                 MediaImage *mi = dynamic_cast<MediaImage*>(efo);
238                 QString key = mi->getCheckSum();
239                 mediaImages.remove(key);
240             }
241             // there should be at least one media image left in mediaImages map...
242             /*if (mediaImages.count() == 1) {
243                 selectedImages << mediaImages.values().first();
244             } ... this is added later-> */
245         }
246         else if (mediaImages.count() > 1) {
247             // show select boot image dialog
248             EmuFrontObject *efo = EmuFrontInputDialog::getItem(
249                     this, tr("Select boot image"), tr("Select"), mediaImages.values(), 0, false, &ok);
250             if (!ok)  {
251                 throw EmuFrontException(tr("Boot image selection was canceled, aborting."));
252             }
253             selectedImages << efo;
254             MediaImage *mi = dynamic_cast<MediaImage*>(efo);
255             QString key = mi->getCheckSum();
256             mediaImages.remove(key);
257         }
258         else if (mediaImages.count() == 1) {
259             EmuFrontObject *efo = mediaImages.values().first();
260             selectedImages << efo;
261             MediaImage *mi = dynamic_cast<MediaImage*>(efo);
262             QString key = mi->getCheckSum();
263             mediaImages.remove(key);
264         }
265         // in all the both cases the (ordered) list of media images will be passed to emuHelper
266
267         // wee also keep the rest of the mediaimages in the selected containers for reference!
268         foreach(EmuFrontObject *efo, mediaImages) {
269             selectedImages << efo;
270         }
271
272         if (selectedImages.count() < 1)
273             throw EmuFrontException(tr("No media images selected"));
274
275         emuHelper->launch(exe, mediaImageContainers, selectedImages, list.count(), tmpDirPath);
276         micTable->clearSelection();
277     } catch (EmuFrontException efe) {
278         if (exe) delete exe;
279         qDeleteAll(mediaImageContainers);
280         //qDeleteAll(mediaImages); these are already deleted along with containers
281         QMessageBox::information(this, tr("Launching emulator"),
282                                  efe.what(), QMessageBox::Ok);
283         return;
284     }
285 }
286
287 void EmuLauncher::processError(QProcess::ProcessError e)
288 {
289     cleanTmp();
290     QString stdErr = emuHelper->readAllStandardError();
291     QMessageBox::warning(this, tr("Emulator"),
292         tr("Launching emulator failed with: %1.\n").arg(e)
293         .append(";\n").append(emuHelper->errorString().append(";\n")
294         .append(stdErr)), QMessageBox::Ok );
295 }
296
297 /* Slot for EmuHelper process finished, clears the temporary folder files */
298 void EmuLauncher::processFinished(int a)
299 {
300     cleanTmp();
301     QString stdErr = emuHelper->readAllStandardError();
302     QString stdMsg = emuHelper->readAllStandardOutput();
303     QString msg = tr("Emulator has finished with: %1.\n").arg(a).append(stdMsg);
304     if (a) msg.append("; ").append(emuHelper->errorString()).append(";\n").append(stdErr);
305     QMessageBox::information(this, tr("Emulator finished"), msg, QMessageBox::Ok);
306 }
307
308 void EmuLauncher::cleanTmp()
309 {
310     // TODO
311 }
312
313 void EmuLauncher::setTmpDirPath(QString tmp)
314 {
315     tmpDirPath = tmp;
316 }