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