/
app.cpp
1031 lines (866 loc) · 26.5 KB
/
app.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
/*
* The Doomsday Engine Project -- libcore
*
* Copyright © 2010-2017 Jaakko Keränen <jaakko.keranen@iki.fi>
*
* @par License
* LGPL: http://www.gnu.org/licenses/lgpl.html
*
* <small>This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 3 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 Lesser
* General Public License for more details. You should have received a copy of
* the GNU Lesser General Public License along with this program; if not, see:
* http://www.gnu.org/licenses</small>
*/
#include "de/Animation"
#include "de/App"
#include "de/ArchiveFeed"
#include "de/ArchiveFolder"
#include "de/ArrayValue"
#include "de/Block"
#include "de/CommandLine"
#include "de/Config"
#include "de/DictionaryValue"
#include "de/DirectoryFeed"
#include "de/EscapeParser"
#include "de/FileLogSink"
#include "de/FileSystem"
//#include "de/LibraryFile"
#include "de/Log"
#include "de/LogBuffer"
#include "de/LogFilter"
#include "de/Loop"
#include "de/math.h"
#include "de/MetadataBank"
#include "de/Module"
#include "de/NativeFile"
#include "de/NumberValue"
#include "de/PackageFeed"
#include "de/PackageLoader"
#include "de/Record"
#include "de/RemoteFeedRelay"
#include "de/ScriptSystem"
//#include "de/StaticLibraryFeed"
#include "de/TextValue"
#include "de/UnixInfo"
#include "de/Version"
#include "de/Writer"
#include "de/ZipArchive"
#ifdef UNIX
# include <locale.h>
#endif
#include <the_Foundation/thread.h>
namespace de {
static App *singletonApp;
const char *App::ORG_NAME = "org.name";
const char *App::ORG_DOMAIN = "org.domain";
const char *App::APP_NAME = "name";
const char *App::APP_VERSION = "version";
const char *App::CONFIG_PATH = "config";
const char *App::UNIX_HOME = "unixHome";
static Value *Function_App_Locate(Context &, Function::ArgumentValues const &args)
{
std::unique_ptr<DictionaryValue> result(new DictionaryValue);
String const packageId = args.first()->asText();
// Local packages.
if (File const *pkg = PackageLoader::get().select(packageId))
{
result->add(new TextValue(packageId), RecordValue::takeRecord(
Record::withMembers(
"localPath", pkg->path(),
"description", pkg->description()
)));
}
// Remote packages.
auto found = App::remoteFeedRelay().locatePackages({packageId});
for (auto i = found.begin(); i != found.end(); ++i)
{
result->add(new TextValue(i->first), RecordValue::takeRecord(
Record::withMembers(
"repository", i->second.link->address(),
"localPath", i->second.localPath,
"remotePath", i->second.remotePath
)));
}
return result.release();
}
DE_PIMPL(App)
, DE_OBSERVES(PackageLoader, Activity)
{
thrd_t mainThread = nullptr;
/// Metadata about the application.
Record metadata;
CommandLine cmdLine;
LogFilter logFilter;
LogBuffer logBuffer;
/// Path of the application executable.
NativePath appPath;
NativePath cachedBasePath;
NativePath cachedHomePath;
/// Primary (wall) clock.
Clock clock;
/// Subsystems (not owned).
Flags initFlags;
List<System *> systems;
ScriptSystem scriptSys;
Record appModule;
Binder binder;
FileSystem fs;
std::unique_ptr<MetadataBank> metaBank;
std::unique_ptr<NativeFile> basePackFile;
/// Archive where persistent data should be stored. Written to /home/persist.pack.
/// The archive is owned by the file system.
//Archive *persistentData;
std::unique_ptr<UnixInfo> unixInfo;
filesys::RemoteFeedRelay remoteFeedRelay;
/// The configuration.
Config *config;
StringList packagesToLoadAtInit;
PackageLoader packageLoader;
void (*terminateFunc)(char const *);
/// Optional sink for warnings and errors (set with "-errors").
std::unique_ptr<FileLogSink> errorSink;
Impl(Public *a, const StringList &args)
: Base(a)
, cmdLine(args)
//, persistentData(nullptr)
, config(nullptr)
, terminateFunc(nullptr)
{
DE_ASSERT(isInitialized_Foundation());
appPath = cmdLine.startupPath() / cmdLine.at(0);
metadata.set(APP_NAME, "Doomsday Engine");
metadata.set(CONFIG_PATH, "/packs/net.dengine.stdlib/modules/Config.ds");
metadata.set(UNIX_HOME, ".doomsday");
#ifdef UNIX
{
setlocale(LC_NUMERIC, "C");
}
#endif
packagesToLoadAtInit << "net.dengine.stdlib";
singletonApp = a;
mainThread = thrd_current();
logBuffer.setEntryFilter(&logFilter);
Clock::setAppClock(&clock);
Animation::setClock(&clock);
srand(unsigned(Time().toTime_t()));
// Built-in systems.
systems << &fs << &scriptSys;
// Built-in file interpreters.
// static LibraryFile::Interpreter intrpLibraryFile;
// fs.addInterpreter(intrpLibraryFile);
static ZipArchive::Interpreter intrpZipArchive;
fs.addInterpreter(intrpZipArchive);
// Native App module.
{
scriptSys.addNativeModule("App", appModule);
binder.init(appModule)
<< DE_FUNC(App_Locate, "locate", "packageId");
}
}
~Impl()
{
metaBank.reset();
if (errorSink)
{
logBuffer.removeSink(*errorSink);
}
if (config)
{
// Update the log filter in the persistent configuration.
Record *filter = new Record;
logFilter.write(*filter);
config->objectNamespace().add("log.filter", filter);
delete config;
}
Clock::setAppClock(nullptr);
logBuffer.setOutputFile("");
}
NativePath defaultNativeModulePath() const
{
#ifdef WIN32
{
NativePath appDir = appPath.fileNamePath();
return appDir / "..\\modules";
}
#else
{
return self().nativeBasePath() / "modules";
}
#endif
}
void initFileSystem()
{
Folder::checkDefaultSettings();
// Executables.
Folder &binFolder = fs.makeFolder("/bin");
// Initialize the built-in folders. This hooks up the default native
// directories into the appropriate places in the file system.
// All of these are in read-only mode.
if (ZipArchive::recognize(self().nativeBasePath()))
{
// As a special case, if the base path points to a resource pack,
// use the contents of the pack as the root of the file system.
// The pack itself does not appear in the file system.
basePackFile.reset(NativeFile::newStandalone(self().nativeBasePath()));
fs.root().attach(new ArchiveFeed(*basePackFile));
}
else
{
#ifdef MACOSX
{
NativePath appDir = appPath.fileNamePath();
binFolder.attach(new DirectoryFeed(appDir));
fs.makeFolder("/data").attach(new DirectoryFeed(self().nativeBasePath()));
}
#elif WIN32
{
NativePath appDir = appPath.fileNamePath();
fs.makeFolder("/data").attach(new DirectoryFeed(appDir / "..\\data"));
}
#else // UNIX
{
if ((self().nativeBasePath() / "data").exists())
{
fs.makeFolder("/data").attach(new DirectoryFeed(self().nativeBasePath() / "data"));
}
else
{
fs.makeFolder("/data").attach(new DirectoryFeed(self().nativeBasePath()));
}
}
#endif
if (defaultNativeModulePath().exists())
{
fs.makeFolder("/modules").attach(new DirectoryFeed(defaultNativeModulePath()));
}
}
// User's home folder.
fs.makeFolder("/home", FS::DontInheritFeeds).attach(new DirectoryFeed(self().nativeHomePath(),
DirectoryFeed::AllowWrite | DirectoryFeed::CreateIfMissing | DirectoryFeed::DefaultFlags));
// Loaded packages (as links).
fs.makeFolder("/packs").attach(new PackageFeed(packageLoader));
// Internal data (for runtime use only, thus writable).
fs.makeFolder("/sys").setMode(File::Write);
// Metadata for files.
metaBank.reset(new MetadataBank);
// Populate the file system (blocking).
fs.root().populate(Folder::PopulateFullTree);
// Ensure known subfolders exist:
// - /home/configs is used by de::Profiles.
fs.makeFolder("/home/configs");
packageLoader.audienceForActivity() += this;
}
void setLogLevelAccordingToOptions()
{
// Override the log message level.
if (cmdLine.has("-loglevel") || cmdLine.has("-verbose") || cmdLine.has("-v") ||
cmdLine.has("-vv") || cmdLine.has("-vvv"))
{
LogEntry::Level level = LogEntry::Message;
try
{
int pos;
if ((pos = cmdLine.check("-loglevel", 1)) > 0)
{
level = LogEntry::textToLevel(cmdLine.at(pos + 1));
}
}
catch (Error const &er)
{
warning("%s", er.asText().c_str());
}
level = LogEntry::Level(level
- cmdLine.has("-verbose")
- cmdLine.has("-v") * (cmdLine.isAliasDefinedFor("-verbose")? 0 : 1)
- cmdLine.has("-vv") * 2
- cmdLine.has("-vvv") * 3);
if (level < LogEntry::XVerbose)
{
// Even more verbosity requested, so enable dev messages, too.
logFilter.setAllowDev(LogEntry::AllDomains, true);
level = LogEntry::XVerbose;
}
logFilter.setMinLevel(LogEntry::AllDomains, level);
}
// Enable developer messages across the board?
if (cmdLine.has("-devlog"))
{
logFilter.setAllowDev(LogEntry::AllDomains, true);
}
if (cmdLine.has("-nodevlog"))
{
logFilter.setAllowDev(LogEntry::AllDomains, false);
}
}
void checkForErrorDumpFile()
{
if (CommandLine::ArgWithParams arg = cmdLine.check("-errors", 1))
{
File &errors = self().rootFolder().replaceFile(Path("/home") / arg.params.at(0));
errorSink.reset(new FileLogSink(errors));
errorSink->setMode(LogSink::OnlyWarningEntries);
logBuffer.addSink(*errorSink);
}
}
ArchiveFolder &persistPackFolder() const
{
return self().homeFolder().locate<ArchiveFolder>("persist.pack");
}
void setOfLoadedPackagesChanged()
{
// Make sure the package links are up to date.
fs.root().locate<Folder>("/packs").populate();
}
Record const *findAsset(const String &identifier) const
{
// Access the package that has this asset via a link.
Folder const *pkg = fs.root().tryLocate<Folder>(String("/packs/asset.") + identifier + "/.");
if (!pkg) return nullptr;
// Find the record that has this asset's metadata.
const String ns = "package." + identifier;
if (pkg->objectNamespace().has(ns))
{
return &(*pkg)[ns].valueAsRecord();
}
return nullptr;
}
DE_PIMPL_AUDIENCE(StartupComplete)
};
DE_AUDIENCE_METHOD(App, StartupComplete)
App::App(const StringList &args)
: d(new Impl(this, args))
{
d->unixInfo.reset(new UnixInfo);
// Global time source for animations.
Animation::setClock(&d->clock);
// This instance of LogBuffer is used globally.
LogBuffer::setAppBuffer(d->logBuffer);
// Do not flush the log buffer until we've found out where messages should
// be flushed (Config.log.file).
d->logBuffer.enableFlushing(false);
if (d->cmdLine.has("-stdout"))
{
// Standard output can be flushed straight away.
d->logBuffer.enableStandardOutput(true);
d->logBuffer.enableFlushing(true);
}
// The log filter will be read from Config, but until that time we can use
// the options from the command line.
d->setLogLevelAccordingToOptions();
//d->appPath = appFilePath;
LOG_NOTE("Application path: ") << d->appPath;
LOG_NOTE("Version: ") << Version::currentBuild().asHumanReadableText();
#if defined (MACOSX)
{
// When the application is started through Finder, we get a special command
// line argument. The working directory needs to be changed.
if (d->cmdLine.count() >= 2 && d->cmdLine.at(1).beginsWith("-psn"))
{
DirectoryFeed::changeWorkingDir(d->cmdLine.at(0).fileNamePath() / "..");
}
}
#endif
}
App::~App()
{
LOG_AS("~App");
d.reset();
singletonApp = nullptr;
}
Record &App::metadata()
{
return d->metadata;
}
const Record &App::metadata() const
{
return d->metadata;
}
void App::addInitPackage(String const &identifier)
{
d->packagesToLoadAtInit << identifier;
}
void App::setUnixHomeFolderName(String const &name)
{
d->metadata.set(UNIX_HOME, name);
// Reload Unix config files.
d->unixInfo.reset(new UnixInfo);
}
String App::unixHomeFolderName() const
{
return d->metadata.gets(UNIX_HOME);
}
String App::unixEtcFolderName() const
{
String unixHome = d->metadata.gets(UNIX_HOME);
if (unixHome.beginsWith("."))
{
return unixHome.substr(BytePos(1));
}
return unixHome;
}
String App::reverseDomainIdentifier() const
{
const DotPath domain(metadata().gets(ORG_DOMAIN));
String rdi;
for (int i = 0; i < domain.segmentCount(); ++i)
{
rdi = rdi.concatenateMember(domain.reverseSegment(i).toString());
}
return rdi.concatenateMember(unixEtcFolderName());
}
void App::setTerminateFunc(void (*func)(char const *))
{
d->terminateFunc = func;
}
void App::handleUncaughtException(const String& message)
{
LOG_CRITICAL(message);
EscapeParser esc;
esc.parse(message);
if (d->terminateFunc) d->terminateFunc(esc.plainText());
}
bool App::processEvent(Event const &ev)
{
for (System *sys : d->systems)
{
if (sys->behavior() & System::ReceivesInputEvents)
{
if (sys->processEvent(ev))
return true;
}
}
return false;
}
void App::timeChanged(Clock const &clock)
{
for (System *sys : d->systems)
{
if (sys->behavior() & System::ObservesTime)
{
sys->timeChanged(clock);
}
}
}
bool App::inMainThread()
{
if (!App::appExists())
{
// No app even created yet, must be main thread.
return true;
}
return DE_APP->d->mainThread == thrd_current();
}
#if 0
#if !defined (DE_STATIC_LINK)
NativePath App::nativePluginBinaryPath()
{
if (!d->cachedPluginBinaryPath.isEmpty()) return d->cachedPluginBinaryPath;
if (auto const opt = d->cmdLine.check("-libdir", 1))
{
d->cmdLine.makeAbsolutePath(opt.pos + 1);
return (d->cachedPluginBinaryPath = d->cmdLine.at(opt.pos + 1));
}
NativePath path;
#if defined (WIN32)
{
path = d->appPath.fileNamePath() / "plugins";
return (d->cachedPluginBinaryPath = path);
}
#else
{
#if defined (MACOSX)
{
path = d->appPath.fileNamePath() / "../PlugIns/Doomsday";
}
#else
{
path = d->appPath.fileNamePath() / DE_LIBRARY_DIR;
if (!path.exists())
{
// Try a fallback relative to the executable.
path = d->appPath.fileNamePath() / "../lib/doomsday";
}
}
#endif
// Also check the system config files.
d->unixInfo->path("libdir", path);
return (d->cachedPluginBinaryPath = path);
}
#endif
}
#endif
#endif
NativePath App::nativeHomePath()
{
if (!d->cachedHomePath.isEmpty()) return d->cachedHomePath;
if (auto const opt = d->cmdLine.check("-userdir", 1))
{
d->cmdLine.makeAbsolutePath(opt.pos + 1);
return (d->cachedHomePath = d->cmdLine.at(opt.pos + 1));
}
NativePath nativeHome;
#if defined (DE_IOS)
{
nativeHome = NativePath::homePath();
nativeHome = nativeHome / "Documents/runtime";
}
#elif defined (MACOSX)
{
nativeHome = NativePath::homePath();
nativeHome = nativeHome / "Library/Application Support" / d->metadata.gets(APP_NAME) / "runtime";
}
#elif defined (WIN32)
{
nativeHome = appDataPath();
nativeHome = nativeHome / "runtime";
}
#else // UNIX
{
nativeHome = NativePath::homePath();
nativeHome = nativeHome / d->unixHomeFolder / "runtime";
}
#endif
return (d->cachedHomePath = nativeHome);
}
const Archive &App::persistentData()
{
const Impl *d = DE_APP->d;
if (d->initFlags & DisablePersistentData)
{
throw PersistentDataNotAvailable("App::persistentData", "Persistent data is disabled");
}
return d->persistPackFolder().archive();
}
Archive &App::mutablePersistentData()
{
const Impl *d = DE_APP->d;
if (d->initFlags & DisablePersistentData)
{
throw PersistentDataNotAvailable("App::mutablePersistentData", "Persistent data is disabled");
}
return d->persistPackFolder().archive();
}
bool App::hasPersistentData()
{
return !(DE_APP->d->initFlags & DisablePersistentData);
}
ArchiveFolder &App::persistPackFolder()
{
return DE_APP->d->persistPackFolder();
}
NativePath App::currentWorkPath()
{
return NativePath::workPath();
}
NativePath App::tempPath()
{
NativePath sysTemp;
#if defined (WIN32)
{
sysTemp = NativePath::homePath() / "AppData\\Local\\Temp";
}
#else
{
sysTemp = "/tmp";
}
#endif
return sysTemp / Stringf("%s-%i", app().reverseDomainIdentifier().c_str(), pid_Process(nullptr));
}
NativePath App::cachePath()
{
NativePath dir;
#if defined (MACOSX)
{
dir = NativePath::homePath() / "Library/Caches" / app().reverseDomainIdentifier();
}
#else
{
DE_ASSERT_FAIL("App::cachePath() not implemented");
return NativePath();
}
#endif
// Make sure the directory actually exists.
if (!dir.exists())
{
dir.create();
}
return dir;
}
bool App::setCurrentWorkPath(NativePath const &cwd)
{
return NativePath::setWorkPath(cwd);
}
NativePath App::nativeBasePath()
{
if (!d->cachedBasePath.isEmpty()) return d->cachedBasePath;
int i;
if ((i = d->cmdLine.check("-basedir", 1)))
{
d->cmdLine.makeAbsolutePath(i + 1);
return (d->cachedBasePath = d->cmdLine.at(i + 1));
}
NativePath path;
#ifdef WIN32
{
path = d->appPath.fileNamePath() / "..";
}
#else
{
#ifdef MACOSX
{
path = d->appPath.fileNamePath() / "../Resources";
if (!path.exists())
{
// Try the built-in base directory (unbundled apps).
path = d->appPath.fileNamePath() / DE_BASE_DIR;
}
}
#else
{
path = d->appPath.fileNamePath() / DE_BASE_DIR;
}
#endif
if (!path.exists())
{
// Fall back to using the application binary path, which always exists.
// We use this instead of the working directory because the basedir is
// meant for storing read-only data files that may be deployed with
// the application binary.
path = d->appPath.fileNamePath();
}
// Also check the system config files.
d->unixInfo->path("basedir", path);
}
#endif
return (d->cachedBasePath = path);
}
void App::initSubsystems(SubsystemInitFlags flags)
{
d->initFlags = flags;
d->initFileSystem();
// Load the init packages.
for (const String &pkg : d->packagesToLoadAtInit)
{
d->packageLoader.load(pkg);
}
if (!(flags & DisablePersistentData))
{
// Recreate the persistent state data package, if necessary.
if (!homeFolder().has("persist.pack") || commandLine().has("-reset"))
{
ZipArchive arch;
arch.add("Info", Stringf("# Package for %s's persistent state.\n",
d->metadata.gets(APP_NAME).c_str()));
File &persistPack = homeFolder().replaceFile("persist.pack");
Writer(persistPack) << arch;
persistPack.reinterpret()->as<ArchiveFolder>().populate();
}
}
// The configuration.
d->config = new Config(d->metadata.gets(CONFIG_PATH));
d->scriptSys.addNativeModule("Config", d->config->objectNamespace());
// Whenever the version changes, reset the cached metadata so any updates will be applied.
if (d->config->read() == Config::DifferentVersion)
{
LOG_RES_NOTE("Clearing cached metadata due to version change");
d->metaBank->clear();
// Immediately after upgrading, OLD_VERSION is also present in the Version module.
Version oldVer = d->config->upgradedFromVersion();
if (oldVer != Version::currentBuild())
{
ArrayValue *old = new ArrayValue;
*old << NumberValue(oldVer.major) << NumberValue(oldVer.minor)
<< NumberValue(oldVer.patch) << NumberValue(oldVer.build);
d->scriptSys["Version"].addArray("OLD_VERSION", old).setReadOnly();
}
}
// Set up the log buffer.
LogBuffer &logBuf = LogBuffer::get();
// Update the log buffer max entry count: number of items to hold in memory.
logBuf.setMaxEntryCount(d->config->getui("log.bufferSize", 1000));
try
{
// The -out option can be used to override the configured output file.
if (CommandLine::ArgWithParams outArg = commandLine().check("-out", 1))
{
logBuf.setOutputFile(String("/home") / outArg.params.at(0));
}
else if (d->config->has("log"))
{
// Set the log output file.
logBuf.setOutputFile(d->config->gets("log.file"));
}
}
catch (Error const &er)
{
LOG_WARNING("Failed to set log output file:\n" + er.asText());
}
// Check if a separate error output file is requested.
d->checkForErrorDumpFile();
try
{
if (d->config->has("log.filter"))
{
// The level of enabled messages.
d->logFilter.read(d->config->subrecord("log.filter"));
}
}
catch (Error const &er)
{
LOG_WARNING("Failed to apply log filter:\n" + er.asText());
}
// Command line options may override the saved config.
d->setLogLevelAccordingToOptions();
LOGDEV_NOTE("Developer log entries enabled");
// We can start flushing now when the destination is known.
logBuf.enableFlushing(true);
// Update the wall clock time.
Time::updateCurrentHighPerformanceTime();
d->clock.setTime(Time::currentHighPerformanceTime());
// Now we can start observing progress of time.
d->clock.audienceForTimeChange() += this;
LOG_VERBOSE("%s %s subsystems initialized")
<< metadata().gets(APP_NAME) << Version::currentBuild().asHumanReadableText();
}
void App::addSystem(System &system)
{
d->systems.removeAll(&system);
d->systems.append(&system);
}
void App::removeSystem(System &system)
{
d->systems.removeAll(&system);
}
void App::notifyStartupComplete()
{
DE_FOR_AUDIENCE2(StartupComplete, i)
{
i->appStartupCompleted();
}
}
bool App::appExists()
{
return singletonApp != nullptr;
}
App &App::app()
{
DE_ASSERT(appExists());
return *singletonApp;
}
LogFilter &App::logFilter()
{
return DE_APP->d->logFilter;
}
CommandLine &App::commandLine()
{
return DE_APP->d->cmdLine;
}
NativePath App::executableFile()
{
return DE_APP->d->appPath;
}
NativePath de::App::executableDir()
{
return DE_APP->d->appPath.fileNamePath();
}
#ifdef MACOSX
NativePath App::nativeAppContentsPath()
{
return DE_APP->d->appPath/"../..";
}
#endif
FileSystem &App::fileSystem()
{
return DE_APP->d->fs;
}
MetadataBank &App::metadataBank()
{
DE_ASSERT(DE_APP->d->metaBank);
return *DE_APP->d->metaBank;
}
PackageLoader &App::packageLoader()
{
return DE_APP->d->packageLoader;
}
int App::findInPackages(const String &partialPath, FS::FoundFiles &files)
{
return App::fileSystem().nameIndex().findPartialPathInPackageOrder(partialPath, files);
}
bool App::assetExists(const String &identifier)
{
return DE_APP->d->findAsset(identifier) != 0;
}
Package::Asset App::asset(const String &identifier)
{
Record const *info = DE_APP->d->findAsset(identifier);
if (!info)
{
throw AssetNotFoundError("App::asset", "Asset \"" + identifier + "\" does not exist");
}
return *info;
}
ScriptSystem &App::scriptSystem()
{
return DE_APP->d->scriptSys;
}
bool App::configExists()
{
return DE_APP->d->config != nullptr;
}
Folder &App::rootFolder()
{
return fileSystem().root();
}
Folder &App::homeFolder()
{
return rootFolder().locate<Folder>("home");
}
filesys::RemoteFeedRelay &App::remoteFeedRelay()
{
return DE_APP->d->remoteFeedRelay;
}
Config &App::config()
{
DE_ASSERT(DE_APP->d->config != nullptr);
return *DE_APP->d->config;
}
Variable &App::config(const String &name)
{
return config()[name];
}
String App::apiUrl() // static
{
String u = Config::get().gets("apiUrl");
if (!u.beginsWith("http")) u = "http://" + u;
if (!u.endsWith("/")) u += "/";