Some comments about heap-objects and cleaning up some heap-objects.
[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(QErrorMessage *errorMessage, QWidget *parent, QString tmp) :
36     QWidget(parent), tmpDirPath(tmp), errorMessage(errorMessage)
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, 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     platformSelectBox->updateDataModel();
137     mediaTypeSelectBox->updateDataModel();
138     execSelectBox->updateToSetup(plfid, mtid);
139 }
140
141 void EmuLauncher::launchEmu()
142 {
143     // if selected emulator has no extensions configured, it's assumed to be a M.A.M.E. or similar and
144     // map of media images will be no be used
145     QMap<QString, EmuFrontObject*> mediaImages;
146     QList<MediaImageContainer*> mediaImageContainers;
147     Executable *exe = 0;
148     try {
149         if (!micTable || !micTable->model()) {
150             throw EmuFrontException(tr("No search results available!"));
151         }
152         if (!execSelectBox || execSelectBox->currentIndex() == -1) {
153             throw EmuFrontException(tr("Emulator not selected!"));
154         }
155         QItemSelectionModel *selModel = micTable->selectionModel();
156         QModelIndexList listMIndex =  selModel->selectedIndexes();
157         if (listMIndex.count() < 1) {
158             throw EmuFrontException(tr("Media image container not selected!"));
159         }
160         qDebug() << listMIndex.count() << " items selected.";
161
162         EmuFrontObject *obExe = execSelectBox->getSelected();
163         if (!obExe) {
164             throw EmuFrontException(tr("Failed fetching selected emulator!"));
165         }
166         exe = dynamic_cast<Executable*>(obExe);
167         if (!exe) {
168             throw EmuFrontException(tr("Failed creating Emulator object!"));
169         }
170
171         qDebug() << "File types; " << exe->getSetup()->getSupportedFileTypeExtensions().count();
172
173         bool mame = exe->getSetup()->getSupportedFileTypeExtensions().isEmpty();
174
175         if (mame && listMIndex.count() > 1) {
176             throw EmuFrontException(tr("No supported file types configured for this emulator configuration. "
177                 "Assuming emulator support container files as is. "
178                 "Only one container can be selected without configuring supported file types."
179             ));
180         }
181
182         // Now we have one or more media image containers and an emulator selected,
183         // let's fetch the media image container data.
184
185         foreach(QModelIndex mind, listMIndex) {
186             if (!mind.isValid()) continue;
187             EmuFrontObject *obImg = dbMic->getDataObjectFromModel(&mind); // throws EmuFrontException
188             if (!obImg) {
189                 qDebug() << "Failed creating media image container at row " << mind.row();
190                 continue;
191             }
192             MediaImageContainer *mic = dynamic_cast<MediaImageContainer*>(obImg);
193             if (!mic) {
194                 qDebug() << "Failed to create media image container for " << obImg->getName();
195                 delete obImg;
196                 continue;
197             }
198             mediaImageContainers << mic;
199             QMap<QString, EmuFrontObject*> contained = mic->getMediaImages();
200             mediaImages.unite(contained);
201         }
202
203         if (mame) {
204             emuHelper->launch(exe, mediaImageContainers);
205             return;
206         }
207         else {
208             // mediaImageContainers list contains all the selected media image containers and
209             // mediaImages list contains all the media images inside all the selected containers
210
211             QList<EmuFrontObject*> selectedImages;
212             if (mediaImages.count() < 1) {
213                 throw EmuFrontException("No media images available!");
214             }
215
216             // check if command options have slots for nr media images > 1 e.g. "-diska $1 -diskb $2 ..."
217             QString opts = exe->getOptions();
218             QRegExp rx("(\\$\\d+)");
219             QStringList list;
220             int pos = 0;
221             while ((pos = rx.indexIn(opts, pos)) != -1) {
222                 list << rx.cap(1);
223                 pos += rx.matchedLength();
224             }
225             bool ok;
226
227             if (list.count() > mediaImages.count()) {
228                 throw EmuFrontException(tr("Select %1 media images for this emulator configuration").arg(list.count()));
229             }
230             if (list.count() > 1) {
231                 // more than one placeholder for media image in the command line ($1, $2, ...)
232                 int lim = list.count() == mediaImages.count() ? list.count() - 1 : list.count();
233                 // user sets the order of media images
234                 for(int i = 0; i < lim; i++) {
235                     EmuFrontObject *efo = EmuFrontInputDialog::getItem(
236                             this, tr("Select image no. %1").arg(i+1), tr("Select"), mediaImages.values(), 0, false, &ok);
237                     if (!ok)  {
238                         throw EmuFrontException(tr("Boot image selection was canceled, aborting."));
239                     }
240                     selectedImages << efo;
241                     MediaImage *mi = dynamic_cast<MediaImage*>(efo);
242                     QString key = mi->getCheckSum();
243                     mediaImages.remove(key);
244                 }
245                 // there should be at least one media image left in mediaImages map...
246                 /*if (mediaImages.count() == 1) {
247                 selectedImages << mediaImages.values().first();
248             } ... this is added later-> */
249             }
250             else if (mediaImages.count() > 1) {
251                 // show select boot image dialog
252                 EmuFrontObject *efo = EmuFrontInputDialog::getItem(
253                         this, tr("Select boot image"), 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             else if (mediaImages.count() == 1) {
263                 EmuFrontObject *efo = mediaImages.values().first();
264                 selectedImages << efo;
265                 MediaImage *mi = dynamic_cast<MediaImage*>(efo);
266                 QString key = mi->getCheckSum();
267                 mediaImages.remove(key);
268             }
269             // in all the both cases the (ordered) list of media images will be passed to emuHelper
270
271             // wee also keep the rest of the mediaimages in the selected containers for reference!
272             foreach(EmuFrontObject *efo, mediaImages) {
273                 selectedImages << efo;
274             }
275
276             if (selectedImages.count() < 1)
277                 throw EmuFrontException(tr("No media images selected"));
278
279             emuHelper->launch(exe, mediaImageContainers, selectedImages, list.count(), tmpDirPath);
280         }
281     } catch (EmuFrontException efe) {
282         errorMessage->showMessage(efe.what());
283     }
284
285     micTable->clearSelection();
286     if (exe) delete exe;
287     qDeleteAll(mediaImageContainers);
288     //qDeleteAll(mediaImages); these are already deleted along with containers
289 }
290
291 void EmuLauncher::processError(QProcess::ProcessError e)
292 {
293     cleanTmp();
294     QString stdErr = emuHelper->readAllStandardError();
295     QMessageBox::warning(this, tr("Emulator"),
296         tr("Launching emulator failed with: %1.\n").arg(e)
297         .append(";\n").append(emuHelper->errorString().append(";\n")
298         .append(stdErr)), QMessageBox::Ok );
299 }
300
301 /* Slot for EmuHelper process finished, clears the temporary folder files */
302 void EmuLauncher::processFinished(int a)
303 {
304     cleanTmp();
305     QString stdErr = emuHelper->readAllStandardError();
306     QString stdMsg = emuHelper->readAllStandardOutput();
307     QString msg = tr("Emulator has finished with: %1.\n").arg(a).append(stdMsg);
308     if (a) msg.append("; ").append(emuHelper->errorString()).append(";\n").append(stdErr);
309     QMessageBox::information(this, tr("Emulator finished"), msg, QMessageBox::Ok);
310 }
311
312 void EmuLauncher::cleanTmp()
313 {
314     // TODO
315 }
316
317 void EmuLauncher::setTmpDirPath(QString tmp)
318 {
319     tmpDirPath = tmp;
320 }