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