forked from Skarsnik/QUsb2snes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathappui.cpp
More file actions
811 lines (742 loc) · 30.2 KB
/
appui.cpp
File metadata and controls
811 lines (742 loc) · 30.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
/*
* Copyright (c) 2018 Sylvain "Skarsnik" Colinet.
*
* This file is part of the QUsb2Snes project.
* (see https://github.com/Skarsnik/QUsb2snes).
*
* QUsb2Snes is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QUsb2Snes is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QUsb2Snes. If not, see <https://www.gnu.org/licenses/>.
*/
#include <QApplication>
#include <QDesktopServices>
#include <QDir>
#include <QFileInfo>
#include <QJsonObject>
#include <QJsonDocument>
#include <QLoggingCategory>
#include <QMessageBox>
#include <QProcess>
#include <QStyle>
#include <QTranslator>
#include <QtNetwork>
#include <QNetworkAccessManager>
#include <QVBoxLayout>
Q_LOGGING_CATEGORY(log_appUi, "APPUI")
#define sDebug() qCDebug(log_appUi)
#define sInfo() qCInfo(log_appUi)
#include "usb2snes.h"
#include "appui.h"
#include "devices/snesclassic.h"
#include "wsserver.h"
#include "tempdeviceselector.h"
const QString applicationJsonFileName = "qusb2snesapp.json";
extern WSServer wsServer;
extern QSettings* globalSettings;
AppUi::AppUi(QObject *parent) : QObject(parent)
{
sysTray = new QSystemTrayIcon(QIcon(":/img/icon64x64.ico"));
qApp->setQuitOnLastWindowClosed(false);
retroarchFactory = nullptr;
sd2snesFactory = nullptr;
luaBridge = nullptr;
snesClassic = nullptr;
emuNWAccess = nullptr;
dlManager = nullptr;
QTranslator translator;
QString locale = QLocale::system().name().split('_').first();
translator.load(qApp->applicationDirPath() + "/i18n/qusb2snes_" + locale + ".qm");
qApp->installTranslator(&translator);
// Main menu creation is here
menu = new QMenu();
menu->addAction(QIcon(":/img/icon64x64.ico"), "QUsb2Snes v" + QApplication::applicationVersion());
connect(menu->addAction("Joins us on Discord!"), &QAction::triggered, [=]()
{
QDesktopServices::openUrl(QUrl("https://discord.gg/2JgefTX"));
});
menu->addSeparator();
deviceMenu = menu->addMenu(QIcon(":/img/deviceicon.svg"), tr("Devices", "Menu entry"));
connect(&wsServer, &WSServer::untrustedConnection, this, &AppUi::onUntrustedConnection);
connect(deviceMenu, SIGNAL(aboutToShow()), this, SLOT(onMenuAboutToshow()));
appsMenu = menu->addMenu(QIcon(":/img/appicon.svg"), tr("Applications", "Menu entry"));
appsMenu->addAction("No applications");
sysTray->setContextMenu(menu);
QTimer::singleShot(50, this, &AppUi::init);
}
void AppUi::init()
{
sd2snesAction = new QAction(QIcon(":/img/ikari.ico"), tr("Enable SD2SNES Support"));
sd2snesAction->setCheckable(true);
connect(sd2snesAction, SIGNAL(triggered(bool)), this, SLOT(onSD2SnesTriggered(bool)));
retroarchAction = new QAction(QIcon(":/img/retroarch.png"), tr("Enable RetroArch virtual device (use bsnes-mercury if possible)"));
retroarchAction->setCheckable(true);
connect(retroarchAction, SIGNAL(triggered(bool)), this, SLOT(onRetroarchTriggered(bool)));
luaBridgeAction = new QAction(QIcon(":/img/icone-snes9x.gif"), tr("Enable Lua bridge (Snes9x-rr/BizHawk)"));
luaBridgeAction->setCheckable(true);
connect(luaBridgeAction, SIGNAL(triggered(bool)), this, SLOT(onLuaBridgeTriggered(bool)));
snesClassicAction = new QAction(QIcon(":/img/chrysalis.png"), tr("Enable SNES Classic support (experimental)"));
snesClassicAction->setCheckable(true);
connect(snesClassicAction, SIGNAL(triggered(bool)), this, SLOT(onSNESClassicTriggered(bool)));
emuNWAccessAction = new QAction(QIcon(":/img/cheer.png"), tr("Enable EmuNetworkAccess (experimental)"));
emuNWAccessAction->setCheckable(true);
connect(emuNWAccessAction, &QAction::triggered, this, &AppUi::onEmuNWAccessTriggered);
if (globalSettings->value("sd2snessupport").toBool())
{
sd2snesFactory = new SD2SnesFactory();
wsServer.addDeviceFactory(sd2snesFactory);
sd2snesAction->setChecked(true);
}
if (globalSettings->value("retroarchdevice").toBool())
{
retroarchFactory = new RetroArchFactory();
wsServer.addDeviceFactory(retroarchFactory);
retroarchAction->setChecked(true);
}
if (globalSettings->value("luabridge").toBool())
{
luaBridge = new LuaBridge();
wsServer.addDeviceFactory(luaBridge);
luaBridgeAction->setChecked(true);
}
if (globalSettings->value("snesclassic").toBool())
{
snesClassic = new SNESClassicFactory();
wsServer.addDeviceFactory(snesClassic);
snesClassicAction->setChecked(true);
}
if (globalSettings->value("emunwaccess").toBool())
{
emuNWAccess = new EmuNetworkAccessFactory();
wsServer.addDeviceFactory(emuNWAccess);
emuNWAccessAction->setChecked(true);
}
if (globalSettings->contains("trustedOrigin"))
{
sDebug() << globalSettings->value("trustedOrigin").toString().split(";");
foreach (QString ori, globalSettings->value("trustedOrigin").toString().split(";"))
{
wsServer.addTrusted(ori);
}
}
checkForApplications();
menu->addSeparator();
if (QFile::exists(qApp->applicationDirPath() + "/Magic2Snes") && globalSettings->value("Magic2SnesLocation").toString().isEmpty())
handleMagic2Snes(qApp->applicationDirPath() + "/Magic2Snes");
if (!QFile::exists(qApp->applicationDirPath() + "/Magic2Snes") && globalSettings->value("Magic2SnesLocation").toString().isEmpty())
handleMagic2Snes("");
if (!globalSettings->value("Magic2SnesLocation").toString().isEmpty())
handleMagic2Snes(globalSettings->value("Magic2SnesLocation").toString());
menu->addSeparator();
miscMenu = menu->addMenu(tr("Misc", "Menu entry"));
#ifdef Q_OS_WIN
QObject::connect(miscMenu->addAction(QIcon(":/img/updateicon.svg"), tr( "Check for Update")), &QAction::triggered, [this] {
this->checkForNewVersion(true);
});
miscMenu->addSeparator();
QObject::connect(miscMenu->addAction(QIcon(":/img/microsoft-windows-logo.svg"), tr("Add a 'Send To' entry in the Windows menu")),
&QAction::triggered, this, &AppUi::addWindowsSendToEntry);
if (!globalSettings->contains("checkUpdateCounter") || globalSettings->value("checkUpdateCounter").toInt() == 5)
{
globalSettings->setValue("checkUpdateCounter", 0);
checkForNewVersion();
} else {
globalSettings->setValue("checkUpdateCounter", globalSettings->value("checkUpdateCounter").toInt() + 1);
}
#endif
miscMenu->setToolTipsVisible(true);
QAction* debugLogAction = miscMenu->addAction(tr("Enable debug logs"));
debugLogAction->setCheckable(true);
debugLogAction->setChecked(globalSettings->value("debugLog").toBool());
debugLogAction->setToolTip(tr("Enable the creation of a log file with lot of debug informations"));
QObject::connect(debugLogAction, &QAction::changed, [=]() {
if (debugLogAction->isChecked())
{
QMessageBox msg;
msg.setText(tr("Are you sure you want to enable debug log? The file generated could easily go over hundred of MBytes"));
msg.setInformativeText(tr("You will need to restart QUsb2Snes for this setting to take effect"));
msg.setWindowTitle("QUsb2Snes");
msg.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel);
msg.setDefaultButton(QMessageBox::Ok);
int ret = msg.exec();
if (ret == QMessageBox::Ok)
{
sInfo() << "Debug log enabled";
globalSettings->setValue("debugLog", true);
}
else {
debugLogAction->setChecked(false);
}
} else {
sInfo() << "Debug log disabled";
globalSettings->setValue("debugLog", false);
}
});
QObject::connect(menu->addAction(tr("Exit")), &QAction::triggered, qApp, &QApplication::exit);
appsMenu->addSeparator();
appsMenu->addAction(tr("Remote Applications"));
appsMenu->addSeparator();
appsMenu->addAction(QIcon(":/img/multitroid.png"), "Multitroid");
appsMenu->addAction(QIcon(":/img/BK small.png"), "SMZ3 Multiworld");
connect(qApp, &QCoreApplication::aboutToQuit, [=]() {
sysTray->hide();
});
if (!globalSettings->contains("FirstTime"))
{
globalSettings->setValue("FirstTime", true);
TempDeviceSelector selector;
if (selector.exec() == QDialog::Accepted)
{
if (selector.devices.contains("SD2SNES"))
{
onSD2SnesTriggered(true);
#ifdef Q_OS_WIN
QMessageBox msg;
msg.setText(tr("Do you want to create a entry in the 'Send To' menu of Windows to upload file to the sd2snes?"));
msg.setInformativeText(tr("This will only be asked once, if you want to add it later go into the Misc menu."));
msg.setWindowTitle("QUsb2Snes");
msg.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel);
msg.setDefaultButton(QMessageBox::Ok);
int ret = msg.exec();
if (ret == QMessageBox::Ok)
addWindowsSendToEntry();
#endif
}
if (selector.devices.contains("LUA"))
onLuaBridgeTriggered(true);
if (selector.devices.contains("RETROARCH"))
onRetroarchTriggered(true);
if (selector.devices.contains("CLASSIC"))
onSNESClassicTriggered(true);
}
}
startWServer();
}
void AppUi::startWServer()
{
quint16 port = 0;
QHostAddress addr(QHostAddress::Any);
if (globalSettings->contains("listen"))
addr = QHostInfo::fromName(globalSettings->value("listen").toString()).addresses().first();
if (globalSettings->contains("port"))
port = globalSettings->value("port").toUInt();
QString status;
// If the port is changed manually
if (port != 0)
{
status = wsServer.start(addr, port);
if (!status.isEmpty())
{
QMessageBox::critical(nullptr, tr("Error starting the application"), QString(tr("Error starting the core of the application\n Error listening on %1:%2 : %3\nMake sure nothing else is using this port").arg(addr.toString()).arg(port).arg(status)));
qApp->exit(1);
}
return ;
}
// Default behavior
status = wsServer.start(addr, USB2SnesWS::legacyPort);
if (!status.isEmpty())
{
QMessageBox::warning(nullptr, tr("Error listening on legacy port"),
QString(tr("There was an error listenning on port 8080 :%1\n"
"This can be that QUsb2Snes is already running, the legacy USB2SNES application or something else.\n\n"
"Old applications would likely not work.")).arg(status));
}
status = wsServer.start(addr, USB2SnesWS::defaultPort);
if (!status.isEmpty())
{
QMessageBox::critical(nullptr, tr("Error listenning on normal port"),
QString(tr("There was an error starting the core of the application : %1\n"
"Make sure there is no other Usb2Snes webserver application running (QUsb2Snes/Crowd Control")));
qApp->exit(1);
}
}
void AppUi::updated(QString fromVersion)
{
QMessageBox::about(nullptr, tr("QUsb2Snes updated succesfully"),
QString(tr("QUsb2Snes successfully updated from %1 to version %2")).arg(fromVersion).arg(qApp->applicationVersion()));
}
void AppUi::onMenuAboutToshow()
{
deviceMenu->clear();
deviceMenu->addAction("Devices state");
deviceMenu->addSeparator();
if (sd2snesFactory != nullptr)
addDevicesInfo(sd2snesFactory);
if (luaBridge != nullptr)
addDevicesInfo(luaBridge);
if (snesClassic != nullptr)
addDevicesInfo(snesClassic);
if (retroarchFactory != nullptr)
addDevicesInfo(retroarchFactory);
deviceMenu->addSeparator();
deviceMenu->addAction(sd2snesAction);
deviceMenu->addAction(retroarchAction);
deviceMenu->addAction(luaBridgeAction);
deviceMenu->addAction(snesClassicAction);
deviceMenu->addAction(emuNWAccessAction);
//(deviceMenu + 1)->addAction(snesClassicAction);
}
void AppUi::onAppsMenuTriggered(QAction *action)
{
if (action->text() == "Multitroid")
QDesktopServices::openUrl(QUrl("http://multitroid.com/"));
if (action->text() == "SMZ3 Multiworld")
QDesktopServices::openUrl(QUrl("https://samus.link"));
if (action->data().isNull())
return ;
const ApplicationInfo& appInfo = regularApps[action->data().toString()];
QProcess proc(this);
//proc.setWorkingDirectory(fi.path());
QString exec;
QString wDir = appInfo.folder;
QStringList arg;
if (appInfo.isQtApp)
{
wDir = qApp->applicationDirPath();
#ifdef Q_OS_WIN
arg << "-platformpluginpath" << qApp->applicationDirPath() + "/platforms/";
#endif
}
#ifdef Q_OS_WIN
exec = appInfo.folder + "/" + appInfo.executable + ".exe";
#else
exec = appInfo.folder + "/" + appInfo.executable;
#endif
bool ok = proc.startDetached(exec, arg, wDir);
sDebug() << "Running " << exec << " in " << wDir << ok;
if (!ok)
sDebug() << "Error running " << exec << proc.errorString();
}
AppUi::ApplicationInfo AppUi::parseJsonAppInfo(QString fileName)
{
ApplicationInfo info;
QFile file(fileName);
file.open(QIODevice::ReadOnly);
QJsonDocument jdoc = QJsonDocument::fromJson(file.readAll());
QJsonObject job = jdoc.object();
if (job.contains("QtApp"))
info.isQtApp = job["QtApp"].toBool();
info.name = job["name"].toString();
info.folder = QFileInfo(fileName).absolutePath();
info.description = job["description"].toString();
info.executable = job["executable"].toString();
info.icon = job["icon"].toString();
return info;
}
void AppUi::checkForNewVersion(bool manual)
{
sInfo() << "Checking for new version - SSL support is : " << QSslSocket::supportsSsl() << QSslSocket::sslLibraryBuildVersionString();
if (!QSslSocket::supportsSsl())
return;
QNetworkAccessManager* manager = new QNetworkAccessManager();
QObject::connect(manager, &QNetworkAccessManager::finished, [=](QNetworkReply* reply)
{
sDebug() << "Finished" << reply->size();
QByteArray data = reply->readAll();
QJsonDocument doc = QJsonDocument::fromJson(data);
QJsonArray jArr = doc.array();
QString lastTag = jArr.at(0).toObject().value("tag_name").toString();
QString body = jArr.at(0).toObject().value("body").toString();
QString name = jArr.at(0).toObject().value("name").toString();
sInfo() << "Latest release is " << lastTag;
sDebug() << body;
body.replace('\n', "<br/>");
body.replace('\r', "");
if (QVersionNumber::fromString(qApp->applicationVersion()) < QVersionNumber::fromString(lastTag.remove(0, 1)))
{
QMessageBox msg;
msg.setText(QString(tr("A new version of QUsb2Snes is available : QUsb2Snes %1\nDo you want to upgrade to it?")).arg(lastTag));
msg.setWindowTitle(tr("New version of QUsb2Snes available"));
msg.setInformativeText(QString("<b>%1</b><p>%2</p>").arg(name).arg(body));
msg.addButton(QMessageBox::Yes);
msg.addButton(QMessageBox::No);
msg.setDefaultButton(QMessageBox::No);
int but = msg.exec();
if (but == QMessageBox::Yes)
{
if (dlManager == nullptr)
{
dlManager = new QNetworkAccessManager();
dlManager->setRedirectPolicy(QNetworkRequest::NoLessSafeRedirectPolicy);
QObject::connect(dlManager, &QNetworkAccessManager::finished, this, &AppUi::DLManagerRequestFinished);
dlLabel = new QLabel();
dlProgressBar = new QProgressBar();
dlProgressBar->setTextVisible(false);
dlLabel->setText(tr("Downloading the Windows Updater"));
dlWindow = new QWidget();
QVBoxLayout* layout = new QVBoxLayout();
dlWindow->setWindowTitle("Updating Updater");
dlWindow->setWindowIcon(QIcon(":/icon64x64.ico"));
dlWindow->setLayout(layout);
layout->addWidget(dlLabel);
layout->addWidget(dlProgressBar);
}
dlWindow->show();
dlManager->get(QNetworkRequest(QUrl("https://api.github.com/repos/Skarsnik/QUsb2Snes/releases")));
//QString upExe(qApp->applicationDirPath() + "/WinUpdater.exe");
//(int)::ShellExecute(0, reinterpret_cast<const WCHAR*>("runas"), reinterpret_cast<const WCHAR*>(upExe.utf16()), 0, 0, SW_SHOWNORMAL);
//QProcess::startDetached(upExe);
//qApp->exit(0);
}
} else {
if (manual)
QMessageBox::information(nullptr, tr("No new version of QUsb2Snes available"), tr("No new version of QUsb2Snes available"));
}
});
manager->get(QNetworkRequest(QUrl("https://api.github.com/repos/Skarsnik/QUsb2snes/releases")));
sDebug() << "Get";
}
void AppUi::checkForApplications()
{
QDir appsDir(qApp->applicationDirPath() + "/apps");
if (!appsDir.exists())
return ;
foreach (QFileInfo fi, appsDir.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot))
{
sInfo() << "Scanning " << fi.absoluteFilePath();
ApplicationInfo appInfo;
sDebug() << "Searching for " << fi.absoluteFilePath() + "/" + applicationJsonFileName;
if (QFile::exists(fi.absoluteFilePath() + "/" + applicationJsonFileName))
{
qDebug() << "Found a json description file " + applicationJsonFileName;
appInfo = parseJsonAppInfo(fi.absoluteFilePath() + "/" + applicationJsonFileName);
} else {
QDir dir(fi.absoluteFilePath());
QFileInfoList fil = dir.entryInfoList(QDir::Files | QDir::Executable);
if (!fil.isEmpty())
{
appInfo.name = fi.baseName();
appInfo.executable = fil.first().baseName();
appInfo.folder = fi.absoluteFilePath();
if (QFile::exists(fi.absoluteFilePath() + "/icone.png"))
appInfo.icon = "icone.png";
}
}
if (!appInfo.name.isEmpty())
{
regularApps[appInfo.folder] = appInfo;
sInfo() << "Found an application" << appInfo;
}
}
if (regularApps.isEmpty())
return ;
appsMenu->clear();
appsMenu->addAction(tr("Local Applications"));
appsMenu->addSeparator();
appsMenu->setToolTipsVisible(true);
connect(appsMenu, SIGNAL(triggered(QAction*)), this, SLOT(onAppsMenuTriggered(QAction*)));
QMapIterator<QString, ApplicationInfo> it(regularApps);
while (it.hasNext())
{
it.next();
ApplicationInfo info = it.value();
sDebug() << "Adding " << it.key() << " - " << info.name;
sDebug() << info;
QAction *act;
if (!it.value().icon.isEmpty())
act = appsMenu->addAction(QIcon(info.folder + "/" + info.icon), info.name);
else
act = appsMenu->addAction(info.name);
act->setData(it.key());
if (!info.description.isEmpty())
act->setToolTip(info.description);
}
}
void AppUi::addWindowsSendToEntry()
{
QDir appData(QStandardPaths::writableLocation(QStandardPaths::AppDataLocation));
appData.cdUp();
appData.cd("Microsoft");
appData.cd("Windows");
appData.cd("SendTo");
bool ok = QFile::link(qApp->applicationDirPath() + "/SendToSd2Snes.exe", appData.path() + "/SD2Snes.lnk");
QMessageBox msg;
if (ok)
{
msg.setText(tr("Entry in the Send To menu has been added successfully."));
sInfo() << "Entry in the Send to menu added";
} else {
msg.setText(QString(tr("Error while creating the Send To entry.<br>Check in %1 if it does not already exist.")).arg(appData.path()));
}
msg.exec();
}
void AppUi::onUntrustedConnection(QString origin)
{
disconnect(&wsServer, &WSServer::untrustedConnection, this, &AppUi::onUntrustedConnection);
QMessageBox msg;
msg.setText(QString(tr("Received a connection from an untrusted origin %1. Do you want to add this source to the trusted origin list?")).arg(origin));
msg.setWindowTitle(tr("Untrusted origin"));
msg.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
msg.setDefaultButton(QMessageBox::No);
int but = msg.exec();
if (but == QMessageBox::Yes)
{
QStringList tList = globalSettings->value("trustedOrigin").toString().split(";");
wsServer.addTrusted(origin);
tList.append(origin);
globalSettings->setValue("trustedOrigin", tList.join(";"));
}
connect(&wsServer, &WSServer::untrustedConnection, this, &AppUi::onUntrustedConnection);
}
QDebug operator<<(QDebug debug, const AppUi::ApplicationInfo &req)
{
debug << "Name : " << req.name << " Description : " << req.description
<< "Folder : " << req.folder << "Icon : " <<req.icon << "Exe :" << req.executable
<< "QtApp :" << req.isQtApp;
return debug;
}
void AppUi::onSD2SnesTriggered(bool checked)
{
if (checked == true)
{
if (sd2snesFactory == nullptr)
sd2snesFactory = new SD2SnesFactory();
wsServer.addDeviceFactory(sd2snesFactory);
}
globalSettings->setValue("sd2snessupport", checked);
}
void AppUi::onRetroarchTriggered(bool checked)
{
if (checked == true)
{
if (retroarchFactory == nullptr)
retroarchFactory = new RetroArchFactory();
wsServer.addDeviceFactory(retroarchFactory);
} else {
//wsServer.removeDevice(retroarchFactory);
}
globalSettings->setValue("retroarchdevice", checked);
}
void AppUi::onLuaBridgeTriggered(bool checked)
{
if (checked == true)
{
if (luaBridge == nullptr)
luaBridge = new LuaBridge();
wsServer.addDeviceFactory(luaBridge);
} else {
//wsServer.removeDevice(luaBridgeDevice);
}
globalSettings->setValue("luabridge", checked);
}
void AppUi::onSNESClassicTriggered(bool checked)
{
if (checked == true)
{
if (snesClassic == nullptr)
snesClassic = new SNESClassicFactory();
wsServer.addDeviceFactory(snesClassic);
} else {
//wsServer.removeDevice(snesClassic);
}
globalSettings->setValue("snesclassic", checked);
}
void AppUi::onEmuNWAccessTriggered(bool checked)
{
if (checked == true)
{
if (emuNWAccess == nullptr)
emuNWAccess = new EmuNetworkAccessFactory();
wsServer.addDeviceFactory(emuNWAccess);
}
globalSettings->setValue("emunwaccess", checked);
}
// TODO, probably need to rework the whole device status thing again
void AppUi::addDevicesInfo(DeviceFactory* devFact)
{
QString statusString;
QList<ADevice*> devs = devFact->getDevices();
if (devs.isEmpty())
{
statusString = QString("%1 : %2").arg(devFact->name(), -20).arg(devFact->status());
} else {
foreach (ADevice* dev, devs)
{
statusString = dev->name();
QStringList clients = wsServer.getClientsName(dev);
if (clients.isEmpty())
{
if (dev->state() == ADevice::READY)
statusString += tr(" - No client connected");
if (dev->state() == ADevice::CLOSED)
statusString += tr("Device not ready : ") + devFact->status();
} else {
statusString += " : " + clients.join(" - ");
}
}
}
deviceMenu->addAction(statusString);
}
// Code to download the updater
void AppUi::DLManagerRequestFinished(QNetworkReply* reply)
{
static int step = 0;
QByteArray data = reply->readAll();
qDebug() << reply->error();
if (step == 0)
{
QJsonDocument doc = QJsonDocument::fromJson(data);
QJsonArray jArr = doc.array();
QJsonArray assets = jArr.at(0).toObject().value("assets").toArray();
foreach(const QJsonValue& value, assets)
{
if (value.toObject().value("name").toString() == "WinUpdater.exe")
{
sDebug() << "Downloading " << value.toObject().value("browser_download_url").toString();
dlLabel->setText(QString(QObject::tr("Downloading new WinUpdater %1")).arg(
jArr.at(0).toObject().value("tag_name").toString()));
QNetworkRequest req(QUrl(value.toObject().value("browser_download_url").toString()));
req.setRawHeader("Accept", "application/octet-stream");
QNetworkReply* dlReply = dlManager->get(req);
QObject::connect(dlReply, &QNetworkReply::redirected, [=] {
sDebug() << "DL reply redirected";
});
QObject::connect(dlReply, &QNetworkReply::downloadProgress, [=](qint64 bytesRcv, qint64 bytesTotal)
{
qDebug() << 20 + (bytesRcv / bytesTotal) * 80;
dlProgressBar->setValue(20 + (bytesRcv / bytesTotal) * 80);
});
sDebug() << "Found WinUpdater.exe asset";
step = 1;
return ;
}
}
qApp->exit(1);
}
if (step == 1)
{
QFile file(qApp->applicationDirPath() + "/WinUpdater.exe");
step = 0;
dlProgressBar->setValue(100);
dlLabel->setText(QObject::tr("Writing WinUpdater.exe"));
if (file.open(QIODevice::WriteOnly))
{
sDebug() << data.size();
file.write(data);
sDebug() << "WinUpdater written";
file.flush();
file.close();
dlLabel->setText(QObject::tr("Starting the Windows Updater"));
QProcess::startDetached(qApp->applicationDirPath() + "/WinUpdater.exe");
QTimer::singleShot(200, [=] {qApp->exit(0);});
} else {
dlWindow->hide();
QMessageBox::warning(nullptr, tr("Error downloading the updater"), tr("There was an error downloading or writing the updater file, please try to download it manually on the release page"));
}
}
}
/*
* MAGIC2SNES Stuff
*/
void AppUi::onMagic2SnesMenuTriggered(QAction *action)
{
if (!action->data().isNull() && action->data().toString() == "DDDDIR")
return ;
if (!action->data().isNull())
QProcess::startDetached(magic2SnesExe, QStringList() << action->data().toString());
else
QProcess::startDetached(magic2SnesExe);
}
static bool searchForQUsb2snesEntry(QString qmlFile)
{
QFile f(qmlFile);
if (f.open(QIODevice::Text | QIODevice::ReadOnly))
{
while (true)
{
QByteArray line = f.readLine();
if (line.isEmpty())
return false;
if (line.indexOf("USB2Snes") != -1)
return true;
}
}
return false;
}
static QString searchWindowTitle(QString qmlFile)
{
QFile f(qmlFile);
sDebug() << "Searching in " << qmlFile;
if (f.open(QIODevice::Text | QIODevice::ReadOnly))
{
while (true)
{
QByteArray line = f.readLine();
if (line.isEmpty())
break;
if (line.indexOf("windowTitle") != -1)
{
sDebug() << line;
QRegExp exp("windowTitle\\s*\\:\\s*\"(.+)\"");
if (exp.indexIn(line) != -1)
{
sDebug() << "Found : " << exp.cap(1);
return exp.cap(1);
}
}
}
}
return QString();
}
void AppUi::addMagic2SnesFolder(QString path)
{
sDebug() << "Adding magic2snes qml path " << path;
QFileInfo fi(path);
QDir exDir(path);
magic2SnesMenu->addSeparator();
magic2SnesMenu->addAction(menu->style()->standardIcon(QStyle::SP_DirOpenIcon), fi.baseName())->setData("DDDDIR");
magic2SnesMenu->addSeparator();
auto fil = exDir.entryInfoList(QStringList() << "*.qml");
foreach (QFileInfo efi, fil)
{
QString wTitle = searchWindowTitle(efi.absoluteFilePath());
if (wTitle.isEmpty())
magic2SnesMenu->addAction(efi.fileName())->setData(efi.absoluteFilePath());
else
magic2SnesMenu->addAction(wTitle)->setData(efi.absoluteFilePath());
}
fil = exDir.entryInfoList(QDir::NoDotAndDotDot | QDir::Dirs);
foreach(QFileInfo efi, fil)
{
auto filI = QDir(efi.absoluteFilePath()).entryInfoList(QStringList() << "*.qml");
foreach (QFileInfo qmlFI, filI)
if (searchForQUsb2snesEntry(qmlFI.absoluteFilePath()))
{
QString wTitle = searchWindowTitle(qmlFI.absoluteFilePath());
if (wTitle.isEmpty())
magic2SnesMenu->addAction(qmlFI.fileName())->setData(qmlFI.absoluteFilePath());
else
magic2SnesMenu->addAction(wTitle)->setData(qmlFI.absoluteFilePath());
}
}
}
void AppUi::handleMagic2Snes(QString path)
{
magic2SnesMenu = menu->addMenu(QIcon(":/img/magic2snesicon.png"), "Magic2Snes");
if (path.isEmpty())
{
magic2SnesExe = "";
magic2SnesMenu->addAction(tr("Could not find Magic2Snes"));
magic2SnesMenu->addAction(tr("Click here to set the path to it"));
return ;
}
magic2SnesExe = path + "/Magic2Snes";
magic2SnesMenu->addAction(QIcon(":/img/magic2snesicon.png"), tr("Run Magic2Snes"));
magic2SnesMenu->addSeparator();
connect(magic2SnesMenu, SIGNAL(triggered(QAction*)), this, SLOT(onMagic2SnesMenuTriggered(QAction*)));
QFileInfo fi(path);
QString examplePath = fi.absoluteFilePath() + "/examples";
QString scriptPath = fi.absoluteFilePath() + "/scripts";
if (QFile::exists(examplePath))
addMagic2SnesFolder(examplePath);
if (QFile::exists(scriptPath))
addMagic2SnesFolder(scriptPath);
}