forked from Mudlet/Mudlet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHost.cpp
3713 lines (3277 loc) · 119 KB
/
Host.cpp
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
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/***************************************************************************
* Copyright (C) 2008-2013 by Heiko Koehn - KoehnHeiko@googlemail.com *
* Copyright (C) 2014 by Ahmed Charles - acharles@outlook.com *
* Copyright (C) 2015-2021 by Stephen Lyons - slysven@virginmedia.com *
* Copyright (C) 2016 by Ian Adkins - ieadkins@gmail.com *
* Copyright (C) 2018 by Huadong Qi - novload@outlook.com *
* *
* This program 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 2 of the License, or *
* (at your option) any later version. *
* *
* This program 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 this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#include "Host.h"
#include "LuaInterface.h"
#include "TConsole.h"
#include "TDebug.h"
#include "TMainConsole.h"
#include "TCommandLine.h"
#include "TDebug.h"
#include "TDockWidget.h"
#include "TEvent.h"
#include "TLabel.h"
#include "TMap.h"
#include "TMedia.h"
#include "TRoomDB.h"
#include "TScript.h"
#include "TTextEdit.h"
#include "TToolBar.h"
#include "VarUnit.h"
#include "XMLimport.h"
#include "dlgMapper.h"
#include "dlgModuleManager.h"
#include "dlgNotepad.h"
#include "dlgPackageManager.h"
#include "dlgProfilePreferences.h"
#include "dlgIRC.h"
#include "mudlet.h"
#include "pre_guard.h"
#include <chrono>
#include <QDialog>
#include <QtUiTools>
#include <QNetworkProxy>
#include <zip.h>
#include <memory>
#include "post_guard.h"
using namespace std::chrono;
stopWatch::stopWatch()
: mIsInitialised(false)
, mIsRunning(false)
, mIsPersistent(false)
, mEffectiveStartDateTime()
, mElapsedTime()
{
mEffectiveStartDateTime.setTimeSpec(Qt::UTC);
}
bool stopWatch::start()
{
if (!mIsInitialised) {
mIsInitialised = true;
mEffectiveStartDateTime = QDateTime::currentDateTimeUtc();
mIsRunning = true;
return true;
}
if (mIsRunning) {
// Nothing to do, already running
return false;
}
// Is stopped, so subtract elapsed time from current and set that to be the
// effective start time:
mEffectiveStartDateTime = QDateTime::currentDateTimeUtc().addMSecs(-mElapsedTime);
mIsRunning = true;
return true;
}
bool stopWatch::stop()
{
if (!mIsInitialised) {
// Nothing to do, never started
return false;
}
if (!mIsRunning) {
// Nothing to do, already stopped
return false;
}
// Is running - so stop and note time:
mElapsedTime = mEffectiveStartDateTime.msecsTo(QDateTime::currentDateTimeUtc());
mIsRunning = false;
return true;
}
bool stopWatch::reset()
{
if (!mIsInitialised) {
// Nothing to do, never started
return false;
}
if (!mIsRunning) {
// Not running, so reset elapsed time:
mElapsedTime = 0;
// And reset initialised flag:
mIsInitialised = false;
return true;
}
// Is running so reset effective start time - BUT THIS DOES NOT stop the
// stopwatch:
mEffectiveStartDateTime = QDateTime::currentDateTimeUtc();
return true;
}
void stopWatch::adjustMilliSeconds(const qint64 adjustment)
{
if (!mIsInitialised) {
// We can initialise things in this case by setting the flag and falling
// through into the is not running situation - with the elapsed time
// being zero up to now we just have to add on the adjustment:
mIsInitialised = true;
}
if (!mIsRunning) {
// Not running so adjust stored elapsed time:
mElapsedTime += adjustment;
}
// Is running so adjust effective start time - to increase the effective
// elapsed time we must subtract the adjustment from the effect start time:
mEffectiveStartDateTime = mEffectiveStartDateTime.addMSecs(-adjustment);
}
qint64 stopWatch::getElapsedMilliSeconds() const
{
if (!mIsInitialised) {
// Never started so no elapsed time:
return 0;
}
if (!mIsRunning) {
// Not running - so return elapsed time:
return mElapsedTime;
}
// Is running so calculate elapsed time:
return mEffectiveStartDateTime.msecsTo(QDateTime::currentDateTimeUtc());
}
QString stopWatch::getElapsedDayTimeString() const
{
using namespace std::chrono_literals;
if (!mIsInitialised) {
return QStringLiteral("+:0:0:0:0:000");
}
qint64 elapsed = 0;
if (mIsRunning) {
elapsed = mEffectiveStartDateTime.msecsTo(QDateTime::currentDateTimeUtc());
} else {
elapsed = mElapsedTime;
}
bool isNegative = false;
if (elapsed < 0) {
isNegative = true;
elapsed *= -1;
}
qint64 days = elapsed / std::chrono::milliseconds(24h).count();
qint64 remainder = elapsed - (days * std::chrono::milliseconds(24h).count());
quint8 hours = static_cast<quint8>(remainder / std::chrono::milliseconds(1h).count());
remainder = remainder - (hours * std::chrono::milliseconds(1h).count());
quint8 minutes = static_cast<quint8>(remainder / std::chrono::milliseconds(1min).count());
remainder = remainder - (minutes * std::chrono::milliseconds(1min).count());
quint8 seconds = static_cast<quint8>(remainder / std::chrono::milliseconds(1s).count());
quint16 milliSeconds = static_cast<quint16>(remainder - (seconds * std::chrono::milliseconds(1s).count()));
return QStringLiteral("%1:%2:%3:%4:%5:%6").arg((isNegative ? QLatin1String("-") : QLatin1String("+")), QString::number(days), QString::number(hours), QString::number(minutes), QString::number(seconds), QString::number(milliSeconds));
}
Host::Host(int port, const QString& hostname, const QString& login, const QString& pass, int id)
: mTelnet(this, hostname)
, mpConsole(nullptr)
, mpPackageManager(nullptr)
, mpModuleManager(nullptr)
, mLuaInterpreter(this, hostname, id)
, commandLineMinimumHeight(30)
, mAlertOnNewData(true)
, mAllowToSendCommand(true)
, mAutoClearCommandLineAfterSend(false)
, mHighlightHistory(true)
, mBlockScriptCompile(true)
, mBlockStopWatchCreation(true)
, mEchoLuaErrors(false)
, mBorderBottomHeight(0)
, mBorderLeftWidth(0)
, mBorderRightWidth(0)
, mBorderTopHeight(0)
, mCommandLineFont(QFont(QStringLiteral("Bitstream Vera Sans Mono"), 14, QFont::Normal))
, mCommandSeparator(QStringLiteral(";;"))
, mEnableGMCP(true)
, mEnableMSSP(true)
, mEnableMSP(true)
, mEnableMSDP(false)
, mServerMXPenabled(true)
, mMxpClient(this)
, mMxpProcessor(&mMxpClient)
, mFORCE_GA_OFF(false)
, mFORCE_NO_COMPRESSION(false)
, mFORCE_SAVE_ON_EXIT(true)
, mSslTsl(false)
, mSslIgnoreExpired(false)
, mSslIgnoreSelfSigned(false)
, mSslIgnoreAll(false)
, mUseProxy(false)
, mProxyPort(0)
, mIsGoingDown(false)
, mIsProfileLoadingSequence(false)
, mNoAntiAlias(false)
, mpEditorDialog(nullptr)
, mpMap(new TMap(this, hostname))
, mpMedia(new TMedia(this, hostname))
, mpNotePad(nullptr)
, mPrintCommand(true)
, mIsRemoteEchoingActive(false)
, mIsCurrentLogFileInHtmlFormat(false)
, mIsNextLogFileInHtmlFormat(false)
, mIsLoggingTimestamps(false)
, mLogFileNameFormat(QLatin1String("yyyy-MM-dd#HH-mm-ss")) // In the past we have used "yyyy-MM-dd#hh-mm-ss" but we always want a 24-hour clock
, mResetProfile(false)
, mScreenHeight(25)
, mScreenWidth(90)
, mTimeout(60)
, mUSE_FORCE_LF_AFTER_PROMPT(false)
, mUSE_IRE_DRIVER_BUGFIX(true)
, mUSE_UNIX_EOL(false)
, mWrapAt(100)
, mWrapIndentCount(0)
, mEditorAutoComplete(true)
, mEditorTheme(QLatin1String("Mudlet"))
, mEditorThemeFile(QLatin1String("Mudlet.tmTheme"))
, mThemePreviewItemID(-1)
, mThemePreviewType(QString())
#if (QT_VERSION >= QT_VERSION_CHECK(5, 14, 0))
, mBlack(QColorConstants::Black)
, mLightBlack(QColorConstants::DarkGray)
, mRed(QColorConstants::DarkRed)
, mLightRed(QColorConstants::Red)
, mLightGreen(QColorConstants::Green)
, mGreen(QColorConstants::DarkGreen)
, mLightBlue(QColorConstants::Blue)
, mBlue(QColorConstants::DarkBlue)
, mLightYellow(QColorConstants::Yellow)
, mYellow(QColorConstants::DarkYellow)
, mLightCyan(QColorConstants::Cyan)
, mCyan(QColorConstants::DarkCyan)
, mLightMagenta(QColorConstants::Magenta)
, mMagenta(QColorConstants::DarkMagenta)
, mLightWhite(QColorConstants::White)
, mWhite(QColorConstants::LightGray)
, mFgColor(QColorConstants::LightGray)
, mBgColor(QColorConstants::Black)
, mCommandBgColor(QColorConstants::Black)
, mCommandFgColor(QColor(113, 113, 0))
, mBlack_2(QColorConstants::Black)
, mLightBlack_2(QColorConstants::DarkGray)
, mRed_2(QColorConstants::DarkRed)
, mLightRed_2(QColorConstants::Red)
, mLightGreen_2(QColorConstants::Green)
, mGreen_2(QColorConstants::DarkGreen)
, mLightBlue_2(QColorConstants::Blue)
, mBlue_2(QColorConstants::DarkBlue)
, mLightYellow_2(QColorConstants::Yellow)
, mYellow_2(QColorConstants::DarkYellow)
, mLightCyan_2(QColorConstants::Cyan)
, mCyan_2(QColorConstants::DarkCyan)
, mLightMagenta_2(QColorConstants::Magenta)
, mMagenta_2(QColorConstants::DarkMagenta)
, mLightWhite_2(QColorConstants::White)
, mWhite_2(QColorConstants::LightGray)
, mFgColor_2(QColorConstants::LightGray)
, mBgColor_2(QColorConstants::Black)
, mRoomBorderColor(QColorConstants::LightGray)
#else
, mBlack(Qt::black)
, mLightBlack(Qt::darkGray)
, mRed(Qt::darkRed)
, mLightRed(Qt::red)
, mLightGreen(Qt::green)
, mGreen(Qt::darkGreen)
, mLightBlue(Qt::blue)
, mBlue(Qt::darkBlue)
, mLightYellow(Qt::yellow)
, mYellow(Qt::darkYellow)
, mLightCyan(Qt::cyan)
, mCyan(Qt::darkCyan)
, mLightMagenta(Qt::magenta)
, mMagenta(Qt::darkMagenta)
, mLightWhite(Qt::white)
, mWhite(Qt::lightGray)
, mFgColor(Qt::lightGray)
, mBgColor(Qt::black)
, mCommandBgColor(Qt::black)
, mCommandFgColor(QColor(113, 113, 0))
, mBlack_2(Qt::black)
, mLightBlack_2(Qt::darkGray)
, mRed_2(Qt::darkRed)
, mLightRed_2(Qt::red)
, mLightGreen_2(Qt::green)
, mGreen_2(Qt::darkGreen)
, mLightBlue_2(Qt::blue)
, mBlue_2(Qt::darkBlue)
, mLightYellow_2(Qt::yellow)
, mYellow_2(Qt::darkYellow)
, mLightCyan_2(Qt::cyan)
, mCyan_2(Qt::darkCyan)
, mLightMagenta_2(Qt::magenta)
, mMagenta_2(Qt::darkMagenta)
, mLightWhite_2(Qt::white)
, mWhite_2(Qt::lightGray)
, mFgColor_2(Qt::lightGray)
, mBgColor_2(Qt::black)
, mRoomBorderColor(Qt::lightGray)
#endif
, mMapStrongHighlight(false)
, mLogStatus(false)
, mEnableSpellCheck(true)
, mDiscordDisableServerSide(true)
, mDiscordAccessFlags(DiscordLuaAccessEnabled | DiscordSetSubMask)
, mLineSize(10.0)
, mRoomSize(0.5)
, mMapInfoContributors(QSet<QString>{"Short"})
, mBubbleMode(false)
, mShowRoomID(false)
, mShowPanel(true)
, mServerGUI_Package_version(QLatin1String("-1"))
, mServerGUI_Package_name(QLatin1String("nothing"))
, mAcceptServerGUI(true)
, mAcceptServerMedia(true)
, mCommandLineFgColor(Qt::darkGray)
, mCommandLineBgColor(Qt::black)
, mMapperUseAntiAlias(true)
, mMapperShowRoomBorders(true)
, mFORCE_MXP_NEGOTIATION_OFF(false)
, mFORCE_CHARSET_NEGOTIATION_OFF(false)
, mpDockableMapWidget()
, mEnableTextAnalyzer(false)
, mTimerDebugOutputSuppressionInterval(QTime())
, mSearchOptions(dlgTriggerEditor::SearchOption::SearchOptionNone)
, mpDlgIRC(nullptr)
, mpDlgProfilePreferences(nullptr)
, mDisplayFont(QFont(QStringLiteral("Bitstream Vera Sans Mono"), 14, QFont::Normal))
, mLuaInterface(nullptr)
, mTriggerUnit(this)
, mTimerUnit(this)
, mScriptUnit(this)
, mAliasUnit(this)
, mActionUnit(this)
, mKeyUnit(this)
, mHostID(id)
, mHostName(hostname)
, mIsClosingDown(false)
, mLogin(login)
, mPass(pass)
, mPort(port)
, mRetries(5)
, mSaveProfileOnExit(false)
, mHaveMapperScript(false)
, mAutoAmbigousWidthGlyphsSetting(true)
, mWideAmbigousWidthGlyphs(false)
, mSGRCodeHasColSpaceId(false)
, mServerMayRedefineColors(false)
, mSpellDic(QStringLiteral("en_US"))
// DISABLED: - Prevent "None" option for user dictionary - changed to true and not changed anywhere else
, mEnableUserDictionary(true)
, mUseSharedDictionary(false)
, mPlayerRoomStyle(0)
, mPlayerRoomOuterColor(Qt::red)
, mPlayerRoomInnerColor(Qt::white)
, mPlayerRoomOuterDiameterPercentage(120)
, mPlayerRoomInnerDiameterPercentage(70)
, mDebugShowAllProblemCodepoints(false)
, mCompactInputLine(false)
{
TDebug::addHost(this);
// mLogStatus = mudlet::self()->mAutolog;
mLuaInterface.reset(new LuaInterface(this->getLuaInterpreter()->getLuaGlobalState()));
// Copy across the details needed for the "color_table":
mLuaInterpreter.updateAnsi16ColorsInTable();
mLuaInterpreter.updateExtendedAnsiColorsInTable();
QString directoryLogFile = mudlet::getMudletPath(mudlet::profileDataItemPath, mHostName, QStringLiteral("log"));
QString logFileName = QStringLiteral("%1/errors.txt").arg(directoryLogFile);
QDir dirLogFile;
if (!dirLogFile.exists(directoryLogFile)) {
dirLogFile.mkpath(directoryLogFile);
}
mErrorLogFile.setFileName(logFileName);
mErrorLogFile.open(QIODevice::Append);
// This is NOW used (for map
// file auditing and other issues)
mErrorLogStream.setDevice(&mErrorLogFile);
QTimer::singleShot(0, this, [this]() {
qDebug() << "Host::Host() - restore map case 4 {QTimer::singleShot(0)} lambda.";
if (mpMap->restore(QString(), false)) {
mpMap->audit();
if (mpMap->mpMapper) {
mpMap->mpMapper->mp2dMap->init();
mpMap->mpMapper->updateAreaComboBox();
mpMap->mpMapper->resetAreaComboBoxToPlayerRoomArea();
mpMap->mpMapper->show();
}
}
});
mGMCP_merge_table_keys.append("Char.Status");
mDoubleClickIgnore.insert('"');
mDoubleClickIgnore.insert('\'');
// search engine load entries
mSearchEngineData = QMap<QString, QString>(
{
{"Bing", "https://www.bing.com/search?q="},
{"DuckDuckGo", "https://duckduckgo.com/?q="},
{"Google", "https://www.google.com/search?q="}
});
auto optin = readProfileData(QStringLiteral("discordserveroptin"));
if (!optin.isEmpty()) {
mDiscordDisableServerSide = optin.toInt() == Qt::Unchecked ? true : false;
}
loadSecuredPassword();
if (mudlet::scmIsPublicTestVersion) {
thankForUsingPTB();
}
if (mudlet::self()->firstLaunch) {
QTimer::singleShot(0, this, [this]() {
mpConsole->mpCommandLine->setPlaceholderText(tr("Text to send to the game"));
});
}
connect(&mTelnet, &cTelnet::signal_disconnected, this, [this](){ purgeTimer.start(1min); });
connect(&mTelnet, &cTelnet::signal_connected, this, [this](){ purgeTimer.stop(); });
connect(&purgeTimer, &QTimer::timeout, this, &Host::slot_purgeTemps);
// enable by default in case of offline connection; if the profile connects - timer will be disabled
purgeTimer.start(1min);
}
Host::~Host()
{
if (mpDockableMapWidget) {
mpDockableMapWidget->deleteLater();
}
mIsGoingDown = true;
mIsClosingDown = true;
mErrorLogStream.flush();
mErrorLogFile.close();
TDebug::removeHost(this);
}
void Host::loadPackageInfo()
{
QStringList packages = mInstalledPackages;
for (int i = 0; i < packages.size(); i++) {
QString packagePath{mudlet::self()->getMudletPath(mudlet::profilePackagePath, getName(), packages.at(i))};
QDir dir(packagePath);
if (dir.exists(QStringLiteral("config.lua"))) {
getPackageConfig(dir.absoluteFilePath(QStringLiteral("config.lua")));
}
}
}
void Host::saveModules(int sync, bool backup)
{
QMapIterator<QString, QStringList> it(modulesToWrite);
mModulesToSync.clear();
QString savePath = mudlet::getMudletPath(mudlet::moduleBackupsPath);
auto savePathDir = QDir(savePath);
if (!savePathDir.exists()) {
savePathDir.mkpath(savePath);
}
while (it.hasNext()) {
it.next();
QStringList entry = it.value();
QString moduleName = it.key();
QString filename_xml = entry[0];
if (backup) {
QString time = QDateTime::currentDateTime().toString("yyyy-MM-dd#HH-mm-ss");
savePathDir.rename(filename_xml, savePath + moduleName + time); //move the old file, use the key (module name) as the file
}
auto writer = new XMLexport(this);
writers.insert(filename_xml, writer);
writer->writeModuleXML(moduleName, filename_xml);
if (entry[1].toInt()) {
mModulesToSync << moduleName;
}
}
modulesToWrite.clear();
if (sync) {
connect(this, &Host::profileSaveFinished, this, &Host::slot_reloadModules);
}
}
void Host::slot_reloadModules()
{
// update the module zips
updateModuleZips();
//synchronize modules across sessions
for (auto otherHost : mudlet::self()->getHostManager()) {
if (otherHost == this || !otherHost->mpConsole) {
continue;
}
QMap<QString, int>& modulePri = otherHost->mModulePriorities;
QMap<int, QStringList> moduleOrder;
auto modulePrioritiesIt = modulePri.constBegin();
while (modulePrioritiesIt != modulePri.constEnd()) {
moduleOrder[modulePrioritiesIt.value()].append(modulePrioritiesIt.key());
++modulePrioritiesIt;
}
QMapIterator<int, QStringList> it(moduleOrder);
while (it.hasNext()) {
it.next();
QStringList moduleList = it.value();
for (int i = 0, total = moduleList.size(); i < total; ++i) {
QString moduleName = moduleList[i];
if (mModulesToSync.contains(moduleName)) {
otherHost->reloadModule(moduleName);
}
}
}
}
// disconnect the one-time event so we're not always reloading modules whenever a profile save happens
mModulesToSync.clear();
QObject::disconnect(this, &Host::profileSaveFinished, this, &Host::slot_reloadModules);
}
void Host::updateModuleZips() const
{
QMapIterator<QString, QStringList> it(modulesToWrite);
while (it.hasNext()) {
it.next();
QStringList entry = it.value();
QString moduleName = it.key();
QString filename_xml = entry[0];
QString zipName;
zip* zipFile = nullptr;
if (filename_xml.endsWith(QStringLiteral("mpackage"), Qt::CaseInsensitive) || filename_xml.endsWith(QStringLiteral("zip"), Qt::CaseInsensitive)) {
QString packagePathName = mudlet::getMudletPath(mudlet::profilePackagePath, mHostName, moduleName);
filename_xml = mudlet::getMudletPath(mudlet::profilePackagePathFileName, mHostName, moduleName);
int err;
zipFile = zip_open(entry[0].toStdString().c_str(), ZIP_CREATE, &err);
zipName = filename_xml;
QDir packageDir = QDir(packagePathName);
if (!packageDir.exists()) {
packageDir.mkpath(packagePathName);
}
struct zip_source* s = zip_source_file(zipFile, filename_xml.toStdString().c_str(), 0, 0);
err = zip_add(zipFile, QString(moduleName + ".xml").toStdString().c_str(), s);
//FIXME: error checking
if (zipFile) {
err = zip_close(zipFile);
//FIXME: error checking
}
}
}
}
void Host::reloadModule(const QString& reloadModuleName)
{
QMap<QString, QStringList> installedModules = mInstalledModules;
QMapIterator<QString, QStringList> moduleIterator(installedModules);
while (moduleIterator.hasNext()) {
moduleIterator.next();
const auto& moduleName = moduleIterator.key();
const auto& moduleLocation = moduleIterator.value()[0];
if (moduleName == reloadModuleName) {
uninstallPackage(moduleName, 2);
installPackage(moduleLocation, 2);
}
}
//iterate through mInstalledModules again and reset the entry flag to be correct.
//both the installedModules and mInstalled should be in the same order now as well
moduleIterator.toFront();
while (moduleIterator.hasNext()) {
moduleIterator.next();
QStringList entry = installedModules[moduleIterator.key()];
mInstalledModules[moduleIterator.key()] = entry;
}
}
std::pair<bool, QString> Host::changeModuleSync(const QString& moduleName, const QLatin1String& value)
{
if (moduleName.isEmpty()) {
return {false, QStringLiteral("module name cannot be an empty string")};
}
if (mInstalledModules.contains(moduleName)) {
QStringList moduleStringList = mInstalledModules[moduleName];
QFileInfo moduleFile = moduleStringList[0];
QStringList accepted_suffix;
accepted_suffix << "xml" << "trigger";
if (!accepted_suffix.contains(moduleFile.suffix().trimmed(), Qt::CaseInsensitive)) {
return {false, QStringLiteral("module has to be a .xml file")};
}
moduleStringList[1] = value;
mInstalledModules[moduleName] = moduleStringList;
return {true, QString()};
}
return {false, QStringLiteral("module name '%1' not found").arg(moduleName)};
}
std::pair<bool, QString> Host::getModuleSync(const QString& moduleName)
{
if (moduleName.isEmpty()) {
return {false, QStringLiteral("module name cannot be an empty string")};
}
if (mInstalledModules.contains(moduleName)) {
QStringList moduleStringList = mInstalledModules[moduleName];
return {true, moduleStringList[1]};
}
return {false, QStringLiteral("module name '%1' not found").arg(moduleName)};
}
void Host::resetProfile_phase1()
{
mAliasUnit.stopAllTriggers();
mTriggerUnit.stopAllTriggers();
mTimerUnit.stopAllTriggers();
mKeyUnit.stopAllTriggers();
mResetProfile = true;
QTimer::singleShot(0, this, [this]() {
resetProfile_phase2();
});
}
void Host::resetProfile_phase2()
{
getAliasUnit()->removeAllTempAliases();
getTimerUnit()->removeAllTempTimers();
getTriggerUnit()->removeAllTempTriggers();
getKeyUnit()->removeAllTempKeys();
removeAllNonPersistentStopWatches();
mAliasUnit.doCleanup();
mTimerUnit.doCleanup();
mTriggerUnit.doCleanup();
mKeyUnit.doCleanup();
mpConsole->resetMainConsole();
mEventHandlerMap.clear();
mEventMap.clear();
mLuaInterpreter.initLuaGlobals();
mLuaInterpreter.loadGlobal();
mBlockScriptCompile = false;
mAliasUnit.reenableAllTriggers();
mTimerUnit.reenableAllTriggers();
mTriggerUnit.reenableAllTriggers();
mKeyUnit.reenableAllTriggers();
getTimerUnit()->compileAll();
getTriggerUnit()->compileAll();
getAliasUnit()->compileAll();
getActionUnit()->compileAll();
getKeyUnit()->compileAll();
getScriptUnit()->compileAll();
mResetProfile = false;
// Have to recopy the values into the Lua "color_table"
mLuaInterpreter.updateAnsi16ColorsInTable();
mLuaInterpreter.updateExtendedAnsiColorsInTable();
TEvent event {};
event.mArgumentList.append(QLatin1String("sysLoadEvent"));
event.mArgumentTypeList.append(ARGUMENT_TYPE_STRING);
raiseEvent(event);
qDebug() << "resetProfile() DONE";
}
// Saves profile to disk - does not save items dirty in the editor, however.
// takes a directory to save in or an empty string for the default location
// as well as a boolean whenever to sync the modules or not
// returns true+filepath if successful or false+error message otherwise
std::tuple<bool, QString, QString> Host::saveProfile(const QString& saveFolder, const QString& saveName, bool syncModules)
{
emit profileSaveStarted();
qApp->processEvents();
QString directory_xml;
if (saveFolder.isEmpty()) {
directory_xml = mudlet::getMudletPath(mudlet::profileXmlFilesPath, getName());
} else {
directory_xml = saveFolder;
}
QString filename_xml;
if (saveName.isEmpty()) {
filename_xml = QStringLiteral("%1/%2.xml").arg(directory_xml, QDateTime::currentDateTime().toString(QStringLiteral("yyyy-MM-dd#HH-mm-ss")));
} else {
filename_xml = QStringLiteral("%1/%2.xml").arg(directory_xml, saveName);
}
if (mIsProfileLoadingSequence) {
//If we're inside of profile loading sequence modules might not be loaded yet, thus we can accidetnally clear their contents
return std::make_tuple(false, filename_xml, QStringLiteral("profile loading is in progress"));
}
QDir dir_xml;
if (!dir_xml.exists(directory_xml)) {
dir_xml.mkpath(directory_xml);
}
if (currentlySavingProfile()) {
return std::make_tuple(false, QString(), QStringLiteral("a save is already in progress"));
}
auto writer = new XMLexport(this);
writers.insert(QStringLiteral("profile"), writer);
writer->exportHost(filename_xml);
saveModules(syncModules ? 1 : 0, saveName == QStringLiteral("autosave") ? false : true);
return std::make_tuple(true, filename_xml, QString());
}
// exports without the host settings for some reason
std::tuple<bool, QString, QString> Host::saveProfileAs(const QString& file)
{
emit profileSaveStarted();
qApp->processEvents();
if (currentlySavingProfile()) {
return std::make_tuple(false, QString(), QStringLiteral("a save is already in progress"));
}
auto writer = new XMLexport(this);
writers.insert(QStringLiteral("profile"), writer);
writer->exportProfile(file);
return std::make_tuple(true, file, QString());
}
void Host::xmlSaved(const QString& xmlName)
{
if (writers.contains(xmlName)) {
auto writer = writers.take(xmlName);
delete writer;
}
if (writers.empty()) {
emit profileSaveFinished();
}
}
bool Host::currentlySavingProfile()
{
return !writers.empty();
}
void Host::waitForProfileSave()
{
for (auto& writer : writers) {
for (auto& future: writer->saveFutures) {
future.waitForFinished();
}
}
}
void Host::setMmpMapLocation(const QString& data)
{
auto document = QJsonDocument::fromJson(data.toUtf8());
if (!document.isObject()) {
return;
}
auto json = document.object();
if (json.isEmpty()) {
return;
}
auto urlValue = json.value(QStringLiteral("url"));
if (urlValue == QJsonValue::Undefined) {
return;
}
auto url = QUrl(urlValue.toString());
if (!url.isValid()) {
return;
}
mpMap->setMmpMapLocation(urlValue.toString());
}
QString Host::getMmpMapLocation() const
{
return mpMap->getMmpMapLocation();
}
// error and debug consoles inherit font of the main console
void Host::updateConsolesFont()
{
if (mpConsole) {
mpConsole->refreshView();
}
if (mpEditorDialog && mpEditorDialog->mpErrorConsole) {
mpEditorDialog->mpErrorConsole->setFont(mDisplayFont.family());
mpEditorDialog->mpErrorConsole->setFontSize(mDisplayFont.pointSize());
}
if (mudlet::self()->mpDebugArea) {
mudlet::self()->mpDebugConsole->setFont(mDisplayFont.family());
mudlet::self()->mpDebugConsole->setFontSize(mDisplayFont.pointSize());
}
}
// a little message to make the player feel special for helping us find bugs
void Host::thankForUsingPTB()
{
const QStringList happyIcons {"😀", "😃", "😄", "😁", "🙂", "🙃", "🤩", "🎉", "🚀", "🤟", "✌️", "👊"};
const auto randomIcon = happyIcons.at(QRandomGenerator::global()->bounded(happyIcons.size()));
postMessage(tr(R"([ OK ] - %1 Thanks a lot for using the Public Test Build!)", "%1 will be a random happy emoji").arg(randomIcon));
postMessage(tr(R"([ OK ] - %1 Help us make Mudlet better by reporting any problems.)", "%1 will be a random happy emoji").arg(randomIcon));
}
void Host::setMediaLocationGMCP(const QString& mediaUrl)
{
QUrl url = QUrl(mediaUrl);
if (!url.isValid()) {
return;
}
mMediaLocationGMCP = mediaUrl;
}
QString Host::getMediaLocationGMCP() const
{
return mMediaLocationGMCP;
}
void Host::setMediaLocationMSP(const QString& mediaUrl)
{
QUrl url = QUrl(mediaUrl);
if (!url.isValid()) {
return;
}
mMediaLocationMSP = mediaUrl;
}
QString Host::getMediaLocationMSP() const
{
return mMediaLocationMSP;
}
std::pair<bool, QString> Host::setDisplayFont(const QFont& font)
{
const QFontMetrics metrics(font);
if (metrics.averageCharWidth() == 0) {
return {false, QStringLiteral("specified font is invalid (its letters have 0 width)")};
}
mDisplayFont = font;
updateConsolesFont();
return {true, QString()};
}
std::pair<bool, QString> Host::setDisplayFont(const QString& fontName)
{
const auto result = setDisplayFont(QFont(fontName));
updateConsolesFont();
return result;
}
void Host::setDisplayFontFromString(const QString& fontData)
{
mDisplayFont.fromString(fontData);
updateConsolesFont();
}
void Host::setDisplayFontSize(int size)
{
mDisplayFont.setPointSize(size);
updateConsolesFont();
}
// Now returns the total weight of the path
unsigned int Host::assemblePath()
{
unsigned int totalWeight = 0;
QStringList pathList;
for (int i : qAsConst(mpMap->mPathList)) {
QString n = QString::number(i);
pathList.append(n);
}
QStringList directionList = mpMap->mDirList;
QStringList weightList;
for (int stepWeight : qAsConst(mpMap->mWeightList)) {
totalWeight += stepWeight;
QString n = QString::number(stepWeight);
weightList.append(n);
}
QString tableName = QStringLiteral("speedWalkPath");
mLuaInterpreter.set_lua_table(tableName, pathList);
tableName = QStringLiteral("speedWalkDir");
mLuaInterpreter.set_lua_table(tableName, directionList);
tableName = QStringLiteral("speedWalkWeight");
mLuaInterpreter.set_lua_table(tableName, weightList);
return totalWeight;
}
bool Host::checkForMappingScript()
{
// the mapper script reminder is only shown once
// because it is too difficult and error prone (->proper script sequence)
// to disable this message
bool ret = (mLuaInterpreter.check_for_mappingscript() || mHaveMapperScript);
mHaveMapperScript = true;
return ret;
}
void Host::check_for_mappingscript()
{
if (!checkForMappingScript()) {
QUiLoader loader;
QFile file(":/ui/lacking_mapper_script.ui");
file.open(QFile::ReadOnly);
auto dialog = dynamic_cast<QDialog*>(loader.load(&file, mudlet::self()));
file.close();
if (!dialog) {
// could not load / not a QDialog
return;
}
connect(dialog, &QDialog::accepted, mudlet::self(), &mudlet::slot_open_mappingscripts_page);
dialog->show();
dialog->raise();
dialog->activateWindow();
}
}
bool Host::checkForCustomSpeedwalk()
{
bool ret = mLuaInterpreter.check_for_custom_speedwalk();
return ret;
}
void Host::startSpeedWalk()
{
int totalWeight = assemblePath();
Q_UNUSED(totalWeight);
QString f = QStringLiteral("doSpeedWalk");
QString n = QString();
mLuaInterpreter.call(f, n);
}
void Host::startSpeedWalk(int sourceRoom, int targetRoom)
{
QString sourceName = QStringLiteral("speedWalkFrom");