-
-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathPackInitiator.cs
358 lines (279 loc) · 13.3 KB
/
PackInitiator.cs
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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using BhModule.Community.Pathing.Behavior.Modifier;
using BhModule.Community.Pathing.MarkerPackRepo;
using BhModule.Community.Pathing.State;
using BhModule.Community.Pathing.UI.Controls;
using Blish_HUD;
using Blish_HUD.Controls;
using Blish_HUD.Settings;
using Microsoft.Xna.Framework;
using TmfLib;
using TmfLib.Reader;
namespace BhModule.Community.Pathing {
public class PackInitiator : IUpdatable {
private static readonly Logger Logger = Logger.GetLogger<PackInitiator>();
private readonly string _watchPath;
private readonly PathingModule _module;
private readonly IProgress<string> _loadingIndicator;
private readonly IRootPackState _packState;
private readonly SafeList<PackWrapper> _packs = new();
private SharedPackCollection _sharedPackCollection;
private readonly PackReaderSettings _packReaderSettings;
private SettingCollection _packToggleSettings;
public bool IsLoading { get; private set; }
public IRootPackState PackState => _packState;
private int _lastMap = -1;
public PackInitiator(string watchPath, PathingModule module, IProgress<string> loadingIndicator) {
_watchPath = watchPath;
_module = module;
_loadingIndicator = loadingIndicator;
_packToggleSettings = _module.SettingsManager.ModuleSettings.AddSubCollection("PackToggleSettings");
_packReaderSettings = new PackReaderSettings();
_packReaderSettings.VenderPrefixes.Add("bh-"); // Support Blish HUD specific categories/markers/trails/attributes.
_packState = new SharedPackState(_module);
}
public void ReloadPacks() {
if (_packState.CurrentMapId < 0 || this.IsLoading) return;
_lastMap = -1;
LoadMapFromEachPackInBackground(_packState.CurrentMapId);
}
private IEnumerable<ContextMenuStripItem> GetPackLoadSettings(PackWrapper pack) {
// Always Load
yield return new SimpleContextMenuStripItem("Always Load", (e) => pack.AlwaysLoad.Value = e, pack.AlwaysLoad.Value);
// Load Manually
if (pack.IsLoaded) {
yield return new ContextMenuStripItem() {
Text = $"Loaded in {pack.LoadTime} milliseconds",
Enabled = false
};
} else {
yield return new SimpleContextMenuStripItem("Load Marker Pack", () => {
pack.ForceLoad = true;
ReloadPacks();
});
}
// Delete Pack
yield return new SimpleContextMenuStripItem("Delete Pack", () => {
if (pack.Package != null) {
Utility.PackHandlingUtil.DeletePack(_module, pack.Package);
}
}) {
Enabled = pack.Package != null
};
}
private IEnumerable<ContextMenuStripItem> GetPackToggles() {
var packs = _packs.ToArray();
foreach (var pack in packs.OrderBy(p => p.Package?.Name ?? p.Pack.Name)) {
if (pack.Pack.Name == "markers") {
// Skip unpacked.
continue;
}
string packName = pack.Package?.Name ?? pack.Pack.Name;
yield return new ContextMenuStripItem() {
Text = packName,
Submenu = new ContextMenuStrip(() => GetPackLoadSettings(pack))
};
}
yield return new ContextMenuStripDivider();
// Reload Markers
yield return new SimpleContextMenuStripItem("Reload Marker Packs", ReloadPacks) {
Enabled = !this.IsLoading && _packState.CurrentMapId > 0,
BasicTooltipText = _module.Settings.KeyBindReloadMarkerPacks.Value.PrimaryKey != Microsoft.Xna.Framework.Input.Keys.None ? $"Keybind: {_module.Settings.KeyBindReloadMarkerPacks.Value.GetBindingDisplayText()}" : null
};
// Unload Markers
yield return new SimpleContextMenuStripItem("Unload Marker Packs", async () => {
if (_packState.CurrentMapId < 0) return;
await UnloadStateAndCollection();
}) {
Enabled = !this.IsLoading && _packState.CurrentMapId > 0
};
// Download Marker Packs
yield return new SimpleContextMenuStripItem("Download Marker Packs", () => {
_module.SettingsWindow.SelectedTab = _module.MarkerRepoTab;
_module.SettingsWindow.Show();
}); ;
}
public IEnumerable<ContextMenuStripItem> GetPackMenuItems() {
// All Markers
bool isAnyMarkers = !this.IsLoading
&& _sharedPackCollection != null
&& _sharedPackCollection.Categories != null
&& _sharedPackCollection.Categories.Any(category => !string.IsNullOrWhiteSpace(category.DisplayName));
var allMarkers = new ContextMenuStripItem() {
Text = "All Markers", // TODO: Localize "All Markers"
CanCheck = true,
Checked = _module.Settings.GlobalPathablesEnabled.Value,
Submenu = isAnyMarkers
? new CategoryContextMenuStrip(_packState, _sharedPackCollection.Categories, false)
: null
};
allMarkers.CheckedChanged += (_, e) => {
_module.Settings.GlobalPathablesEnabled.Value = e.Checked;
};
// Manage Packs
var packs = new ContextMenuStripItem() {
Text = "Manage Marker Packs",
Submenu = new ContextMenuStrip(GetPackToggles)
};
// Scripts
if (_module.Settings.ScriptsEnabled.Value && _module.ScriptEngine.Global != null && _module.ScriptEngine.Global.Menu.Menus.Any()) {
yield return _module.ScriptEngine.Global.Menu.BuildMenu();
}
yield return allMarkers;
yield return packs;
}
public async Task Init() {
await _packState.Load();
await LoadAllPacks();
}
private PackWrapper GetPackWrapper(Pack pack) {
var alwaysLoad = _packToggleSettings.DefineSetting($"{pack.Name}_AlwaysLoad", true);
return new PackWrapper(_module, pack, alwaysLoad);
}
public async Task LoadUnpackedPackFiles(string unpackedDir) {
try {
var newPack = Pack.FromDirectoryMarkerPack(unpackedDir);
_packs.Add(GetPackWrapper(newPack));
} catch (Exception ex) {
Logger.Warn(ex, $"Unpacked markers failed to load.");
}
}
public async Task LoadPackedPackFiles(IEnumerable<string> zipPackFiles) {
foreach (string packArchive in zipPackFiles) {
try {
var newPack = Pack.FromArchivedMarkerPack(packArchive);
_packs.Add(GetPackWrapper(newPack));
} catch (InvalidDataException) {
Logger.Warn($"Pack {packArchive} appears to be corrupt. Please remove it and download it again.");
} catch (Exception ex) {
Logger.Warn(ex, $"Pack {packArchive} failed to load.");
}
}
}
public async Task LoadPack(Pack pack) {
if (pack != null) {
_packs.Add(GetPackWrapper(pack));
}
}
public void UnloadPackByName(string packName) {
foreach (var pack in _packs.ToArray()) {
if (string.Equals(packName, pack.Pack.Name, StringComparison.OrdinalIgnoreCase)) {
_packs.Remove(pack);
break;
}
}
}
private async Task UnloadStateAndCollection() {
_sharedPackCollection?.Unload();
await _packState.Unload();
}
private async Task LoadAllPacks() {
// Load from base and advanced markers paths
foreach (string markerDir in (_packState.UserResourceStates.Advanced.MarkerLoadPaths ?? Array.Empty<string>()).Concat(new [] {_watchPath})) {
await LoadPackedPackFiles(Directory.GetFiles(markerDir, "*.zip", SearchOption.AllDirectories));
await LoadPackedPackFiles(Directory.GetFiles(markerDir, "*.taco", SearchOption.AllDirectories));
await LoadUnpackedPackFiles(markerDir);
}
// If the module loads at launch, this can end up firing twice.
// If the module loads after launch (manually enabled), we need this to populate the current map.
if (GameService.Gw2Mumble.CurrentMap.Id != default) {
LoadMapFromEachPackInBackground(_packState.CurrentMapId = GameService.Gw2Mumble.CurrentMap.Id);
}
GameService.Gw2Mumble.CurrentMap.MapChanged += OnMapChanged;
}
private async Task PrepareState(int mapId) {
await UnloadStateAndCollection();
_sharedPackCollection = new SharedPackCollection();
}
private void LoadMapFromEachPackInBackground(int mapId) {
lock (this) {
if (mapId == _lastMap) {
return;
};
_lastMap = mapId;
}
var thread = new Thread(async () => await LoadMapFromEachPack(mapId)) {
IsBackground = true
};
thread.Start();
}
private async Task LoadMapFromEachPack(int mapId) {
this.IsLoading = true;
var loadTimer = Stopwatch.StartNew();
_packState.Module.ScriptEngine.Reset();
var packTimings = new List<(Pack Pack, long LoadDuration)>();
// TODO: Localize the loading messages.
_loadingIndicator.Report("Loading marker packs...");
await PrepareState(mapId);
var packs = _packs.ToArray();
foreach (var pack in packs) {
pack.IsLoaded = false;
if (!pack.AlwaysLoad.Value && !pack.ForceLoad) {
// Skip loading.
continue;
}
try {
var packTimer = Stopwatch.StartNew();
_loadingIndicator.Report($"Loading {pack.Pack.Name}...");
await pack.Pack.LoadMapAsync(mapId, _sharedPackCollection, _packReaderSettings);
pack.IsLoaded = true;
pack.LoadTime = packTimer.ElapsedMilliseconds;
packTimings.Add((pack.Pack, pack.LoadTime));
} catch (FileNotFoundException e) {
Logger.Warn("Pack file '{packPath}' failed to load because it could not be found.", e.FileName);
_packs.Remove(pack);
} catch (Exception e) {
Logger.Warn(e, $"Loading pack '{pack.Pack.Name}' failed.");
}
}
_loadingIndicator.Report("Finalizing marker collection...");
try {
await _packState.LoadPackCollection(_sharedPackCollection);
} catch (Exception e) {
Logger.Warn(e, $"Finalizing packs failed.");
_packState?.Unload();
}
// We only load scripts if they're enabled.
if (_packState.Module.Settings.ScriptsEnabled.Value) {
_loadingIndicator.Report("Loading scripts...");
foreach (var pack in packs) {
if (!pack.AlwaysLoad.Value && !pack.ForceLoad) {
// Skip loading.
continue;
}
var scriptTimer = Stopwatch.StartNew();
await _packState.Module.ScriptEngine.LoadScript("pack.lua", pack.Pack.ResourceManager, pack.Pack.Name);
pack.LoadTime += scriptTimer.ElapsedMilliseconds;
}
}
foreach (var pack in packs) {
pack.Pack.ReleaseLocks();
}
_loadingIndicator.Report(null);
this.IsLoading = false;
Logger.Info($"Finished loading packs {string.Join(", ", packTimings.Select(p => $"{(p.Pack.ManifestedPack ? "+" : "-")}{p.Pack.Name}[{p.LoadDuration}ms]"))} in {loadTimer.ElapsedMilliseconds}ms for map {mapId}.");
}
private void OnMapChanged(object sender, ValueEventArgs<int> e) {
if (e.Value == _packState.CurrentMapId) return;
_packState.CurrentMapId = e.Value;
foreach (var pack in _packs) {
// Reset the force load after map change.
pack.ForceLoad = false;
}
LoadMapFromEachPackInBackground(e.Value);
}
public void Update(GameTime gameTime) {
_packState.Update(gameTime);
}
public void Unload() {
GameService.Gw2Mumble.CurrentMap.MapChanged -= OnMapChanged;
_packState.Unload();
}
}
}