Repository navigation
Expand file tree
/
Copy pathindex.js
More file actions
513 lines (438 loc) · 19 KB
/
Copy pathindex.js
File metadata and controls
513 lines (438 loc) · 19 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
const { actions, fs, util, selectors, log, Toggle } = require('vortex-api');
const React = require('react');
const { connect } = require('react-redux');
const Promise = require("bluebird");
const winapi = require('winapi-bindings');
const path = require('path');
const semver = require('semver');
const IniParser = require('vortex-parse-ini');
const parser = new IniParser.default(new IniParser.WinapiFormat());
const GAME_ID = 'fallout76';
const STEAM_APP_ID = '1151340';
const XBOX_ID = 'BethesdaSoftworks.Fallout76-PC';
const ARCHIVE_EXT = '.ba2';
// Subfolders of Data/ whose files must keep their subfolder structure
const STANDARD_DATA_DIRS = [
'interface', 'meshes', 'music', 'scripts', 'sound',
'strings', 'textures', 'materials', 'programs', 'video', 'vis'
];
const fallout76CustomINI = 'Fallout76Custom.ini';
const iniPath = path.join(util.getVortexPath('documents'), 'My Games', 'Fallout 76');
const SETTING_REMOVE_DISABLED = 'removeDisabledArchives';
const tools = [
{
id: 'FO76Edit',
name: 'FO76Edit',
logo: path.join('assets', 'fo76edit.png'),
executable: () => 'FO76Edit.exe',
requiredFiles: []
}
]
// ============ Settings Reducer ============
// Vortex expects an IReducerSpec ({ reducers, defaults }), not a classic
// (state, action) reducer function - a plain function is silently ignored,
// which made the settings toggle appear dead.
const settingsReducer = {
reducers: {
'FO76_SET_REMOVE_DISABLED_ARCHIVES': (state, payload) =>
util.setSafe(state, [SETTING_REMOVE_DISABLED], payload),
},
defaults: { [SETTING_REMOVE_DISABLED]: true },
};
// ============ Settings UI Component ============
function SettingsBase({ removeDisabledArchives, onToggle }) {
return React.createElement('div', { style: { overflow: 'auto', padding: '15px 0' } },
React.createElement(Toggle, {
checked: removeDisabledArchives,
onToggle: onToggle,
}, 'Remove disabled mod archives from INI'),
React.createElement('p', { style: { marginTop: '5px' } },
'When enabled, .ba2 archives from disabled or uninstalled mods are removed from ',
React.createElement('code', null, 'sResourceArchive2List'),
' in Fallout76Custom.ini. When disabled, only archives from enabled mods are added, ',
'but existing entries in the INI are preserved.'
)
);
}
function mapStateToProps(state) {
return {
removeDisabledArchives: util.getSafe(state,
['settings', GAME_ID, SETTING_REMOVE_DISABLED], true),
};
}
function mapDispatchToProps(dispatch) {
return {
onToggle: (enabled) => dispatch({
type: 'FO76_SET_REMOVE_DISABLED_ARCHIVES', payload: enabled
}),
};
}
const Settings = connect(mapStateToProps, mapDispatchToProps)(SettingsBase);
async function findGame() {
return util.GameStoreHelper.findByAppId([STEAM_APP_ID, XBOX_ID])
.then((game) => {
return game.gamePath;
// return (game.gameStoreId === 'xbox') ? path.join(game.gamePath, 'Content') : game.gamePath;
})
.catch((err) => {
// Try finding the game on Bethesda.net if the Steam detection fails.
const bethNetPath = winapi.RegGetValue('HKEY_LOCAL_MACHINE',
'SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\Fallout 76',
'Path');
if (!bethNetPath) throw new Error('empty registry key');
return Promise.resolve(instPath.value);
});
}
function onGameModeActivated(gameId, api) {
// Exit if we aren't managing Fallout 76
if (gameId !== GAME_ID) return;
const ini = path.join(iniPath, fallout76CustomINI)
const refreshArchives = () => {
const state = api.store.getState();
const profileId = selectors.activeProfileId(state);
const profile = state.persistent.profiles[profileId];
if (profile && profile.gameId === GAME_ID) {
updateArchiveList(profile, api);
}
};
// Make sure the folder in My Documents exists, create it if not.
return fs.ensureDirAsync(iniPath)
.then(() => {
// See if our INI exists
return fs.statAsync(ini)
.then(() => {
refreshArchives();
return ini;
})
.catch(err => {
// If the INI doesn't exist, make one.
if (err.code === 'ENOENT') {
return createINI(ini, api).then((createdIni) => {
if (createdIni) refreshArchives();
return createdIni;
});
}
// report any other errors.
else api.sendNotification({ id: 'fallout76-ini-error', type: 'error', title: 'Error reading Fallout76Custom.ini', message: `${err.code} - ${err.message}` });
})
})
.catch((err) => console.log('Error checking INI folder', err))
}
function createINI(iniLocation, api) {
// Creates a new Fallout76Custom.ini with the default settings
const defaultData =
'[Archive]\n' +
'sResourceArchive2List=\n' +
'sResourceDataDirsFinal=STRINGS\\\n' +
'bInvalidateOlderFiles=1\n';
return fs.writeFileAsync(iniLocation, defaultData).then(() => iniLocation)
.catch((err) => {
api.sendNotification({ id: 'fallout76-ini-create-error', type: 'error', title: 'Could not create Fallout76Custom.ini', message: `${err.code} - ${err.message}` });
return '';
});
}
function sanitizeDestination(file) {
// Normalize leading slashes/backslashes
let clean = file.replace(/^[\\/]+/, '');
// Strip leading "Data/" or "Data\\" folders (case-insensitive), repeating if nested (e.g. Data/Data/)
while (/^data[\\/]/i.test(clean)) {
clean = clean.replace(/^data[\\/]/i, '');
}
// Handle case where a wrapper folder wraps Data/, e.g. "ModFolder/Data/..."
const wrapperMatch = clean.match(/^([^\\/]+)[\\/]data[\\/](.*)$/i);
if (wrapperMatch) {
const topFolder = wrapperMatch[1].toLowerCase();
if (!STANDARD_DATA_DIRS.includes(topFolder)) {
clean = wrapperMatch[2];
while (/^data[\\/]/i.test(clean)) {
clean = clean.replace(/^data[\\/]/i, '');
}
}
}
return clean;
}
/**
* Detects a single top-level wrapper folder (e.g. "SmootherFishing/SmootherFishing.ba2"),
* where the whole mod lives inside one folder that is neither "Data" nor a standard
* Data subfolder (interface, meshes, ...). Returns the normalized folder name to strip,
* or undefined if the archive doesn't match this layout.
*
* A top-level folder is only treated as a removable wrapper when its root level
* looks like a mod root: a content file (.ba2/.esm/.cdx/.ini) directly inside it
* or a standard Data subfolder under it. Folders that only contain non-standard
* subfolders are functional runtime directories (e.g. XSCAL/Plugins/... which the
* XSCAL loader expects at Data\\XSCAL\\Plugins) and must be kept.
*/
function detectWrapperFolder(files) {
const isDir = (f) => f.endsWith('/') || f.endsWith('\\');
const MOD_ROOT_EXTENSIONS = ['.ba2', '.esm', '.cdx', '.ini'];
const topLevel = new Set();
for (const f of files) {
if (isDir(f)) continue;
const normalized = f.replace(/\\/g, '/');
const sepIdx = normalized.indexOf('/');
if (sepIdx === -1) continue; // files at the archive root stay at the root
topLevel.add(normalized.slice(0, sepIdx).toLowerCase());
}
if (topLevel.size !== 1) return undefined;
const wrapper = [...topLevel][0];
if (wrapper === 'data' || STANDARD_DATA_DIRS.includes(wrapper)) return undefined;
for (const f of files) {
if (isDir(f)) continue;
const parts = f.replace(/\\/g, '/').split('/');
if (parts[0].toLowerCase() !== wrapper) continue;
if (parts.length === 2 && MOD_ROOT_EXTENSIONS.includes(path.extname(parts[1]).toLowerCase())) {
return wrapper;
}
if (parts.length > 2 && STANDARD_DATA_DIRS.includes(parts[1].toLowerCase())) {
return wrapper;
}
}
return undefined;
}
// Strips a leading "<wrapper>/" or "<wrapper>\\" segment, if present
function stripWrapperFolder(file, wrapper) {
if (!wrapper) return file;
const normalized = file.replace(/\\/g, '/');
if (!normalized.toLowerCase().startsWith(wrapper + '/')) return file;
return normalized.slice(wrapper.length + 1);
}
function testForArchives(files, gameId) {
// Supported for Fallout 76 mods
const supported = (gameId === GAME_ID);
return Promise.resolve({
supported,
requiredFiles: []
});
}
function installAndRegisterArchives(files) {
let instructions = [];
// Get an array of the file names of the ba2 files (in case they're nested for some reason)
const ba2Files = [...new Set(files.filter(f => path.extname(f).toLowerCase() === ARCHIVE_EXT).map(a => path.basename(a)))];
// Add this attribute to the mod when we install it.
if (ba2Files.length) instructions.push({ type: 'attribute', key: 'ba2archives', value: ba2Files });
// Handle archives whose content lives inside a single wrapper folder with no Data/
// folder in it (e.g. "SmootherFishing/SmootherFishing.ba2"): treat that folder as
// the mod root so its contents land directly in the game's Data/ folder.
const wrapper = detectWrapperFolder(files);
// Map file copy instructions, stripping any top-level Data/ folder so files land directly in Data/
const fileInstructions = files.reduce((accum, f) => {
// Skip directory entries
if (f.endsWith('/') || f.endsWith('\\')) return accum;
const destination = sanitizeDestination(stripWrapperFolder(f, wrapper));
// If destination is empty or just 'data', skip
if (!destination || destination.toLowerCase() === 'data') return accum;
accum.push({ type: 'copy', source: f, destination });
return accum;
}, []);
// Combine the attributes and instructions, then return.
instructions = instructions.concat(fileInstructions);
return Promise.resolve({ instructions });
}
// NOTE: `const mod` can be undefined when the profile still has data for a modId, but the mod might've been uninstalled
function getBA2Mods(payload, excludeModCondition) {
const { profile, state, gameId } = payload;
const BA2Mods = Object.keys(profile.modState).map(modId => {
if (!excludeModCondition(profile, modId)) return;
const mod = state.persistent.mods[gameId][modId];
if (mod && mod?.attributes && mod?.attributes.ba2archives) return mod;
else return;
}).filter(m => m !== undefined);
// Join up all the BA2s into a single array.
return BA2Mods.map((mod) => mod.attributes.ba2archives.join(',')).join(',').split(',');
}
function updateArchiveList(profile, api) {
const state = api.store.getState();
const gameId = profile.gameId;
const payload = { profile, state, gameId };
const removeDisabledArchives = util.getSafe(state,
['settings', GAME_ID, SETTING_REMOVE_DISABLED], true);
// 1. Get all BA2s from currently ENABLED mods
const enabledBA2s = getBA2Mods(payload, (profile, modId) => profile.modState[modId].enabled);
const gamePath = state.settings?.gameMode?.discovered?.[GAME_ID]?.path;
if (!gamePath) return;
const fallout76Custom = path.join(iniPath, fallout76CustomINI);
return parser.read(fallout76Custom)
.then((ini) => {
if (!ini.data || !ini.data.Archive) {
if (!ini.data) ini.data = {};
ini.data.Archive = {};
}
// 2. Read what's currently in the INI string
const originalsResourceArchive2List = (ini.data.Archive.sResourceArchive2List || '')
.split(',')
.map(s => s.trim())
.filter(Boolean);
let cleanedArchivesList;
if (removeDisabledArchives) {
// 3a. Strict mode: Filter the current INI entries against enabled mods only.
// This removes disabled mods, uninstalled mods, and any manual entries not from enabled mods.
const filteredOriginals = originalsResourceArchive2List.filter(archive => {
return enabledBA2s.includes(archive);
});
cleanedArchivesList = [...new Set([...enabledBA2s, ...filteredOriginals])].filter(Boolean);
} else {
// 3b. Permissive mode: Only remove BA2s from explicitly disabled mods,
// preserving any other manual entries in the INI.
const disabledBA2s = getBA2Mods(payload, (profile, modId) => !profile.modState[modId].enabled);
const filteredOriginals = originalsResourceArchive2List.filter(e => !disabledBA2s.includes(e));
cleanedArchivesList = [...new Set([...enabledBA2s, ...filteredOriginals])].filter(Boolean);
}
ini.data.Archive.sResourceArchive2List = cleanedArchivesList.join(',');
return parser.write(fallout76Custom, ini).then(() => Promise.resolve())
.catch(err => log('error', 'Error updating Fallout76Custom.ini', err));
})
.catch(err => log('error', 'Error parsing Fallout76Custom.ini', err));
}
/**
* Using the onStateChange props, this function checks for the profile that has changed and returns it
* @param {*} previous
* @param {*} current
* @returns the changed profile
*/
function getChangedProfile(previous, current) {
if ((previous === undefined) || (current === undefined)) {
return;
}
const profileIds = Object.keys(previous)
for (let i = 0; i < profileIds.length; i++) {
const profileId = profileIds[i];
if ((previous[profileId] !== current[profileId]) && (current[profileId] !== undefined)) {
return current[profileId]
}
}
}
let debounceUpdate = setTimeout(() => { }, 0);
function debouncedUpdateArchiveList(previous, current, api) {
const changedProfile = getChangedProfile(previous, current)
// Ensure that the profile, the modstate and the gameid are correct
if (!changedProfile || !changedProfile.modState || changedProfile.gameId !== GAME_ID) {
// Return if no profile, or the profile is not for FO76
return
}
updateArchiveList(changedProfile, api)
}
function findExecutable(discoveryPath) {
const steamExe = 'Fallout76.exe';
const xboxExe = 'Project76_GamePass.exe';
if (!discoveryPath) return steamExe;
try {
// Steam version
fs.statSync(path.join(discoveryPath, steamExe));
return steamExe;
}
catch (err) {
// Could not stat to Steam path
}
try {
//Xbox version
fs.statSync(path.join(discoveryPath, xboxExe));
return xboxExe;
}
catch (err) {
// Could not stat the Xbox path
}
log('error', 'Neither the Steam or Xbox EXE paths exist for Fallout 76');
return steamExe;
// throw new Error('Neither the Steam or Xbox EXE paths exist for Fallout 76');
}
function main(context) {
context.requireVersion('>=1.2.0');
// Register reducer FIRST for settings persistence
context.registerReducer(['settings', GAME_ID], settingsReducer);
context.registerGame({
id: GAME_ID,
name: 'Fallout 76',
mergeMods: true,
queryPath: findGame,
supportedTools: tools,
queryModPath: () => 'data',
setup: () => onGameModeActivated(GAME_ID, context.api),
logo: path.join('assets', 'gameart.jpg'),
executable: findExecutable,
requiredFiles: ['Data'],
environment: {
SteamAPPId: STEAM_APP_ID,
},
details: {
steamAppId: STEAM_APP_ID,
}
});
// We'll use an installer to save a list of included BA2 files to the mod.
context.registerInstaller('fallout76-installer', 25, testForArchives, installAndRegisterArchives);
// Migrate from a version below 2.0.0 - not tested but it should work.
context.registerMigration(old => migrate200(context.api, old));
// Register settings panel (visible only when FO76 is the active game)
context.registerSettings('Mods', Settings, undefined, () => {
const state = context.api.getState();
return selectors.activeGameId(state) === GAME_ID;
}, 150);
context.once(() => {
const state = context.api.store.getState();
const activeGameId = selectors.activeGameId(state);
if (activeGameId === GAME_ID) {
onGameModeActivated(activeGameId, context.api);
}
// When we activate Fallout 76, make sure the custom INI exists.
context.api.events.on('gamemode-activated', (gameId) => onGameModeActivated(gameId, context.api));
// On profile state change update the list of BA2s
context.api.onStateChange(['persistent', 'profiles'],
(previous, current) => {
clearTimeout(debounceUpdate)
debounceUpdate = setTimeout(() => {
debouncedUpdateArchiveList(previous, current, context.api)
}, 500);
});
// Deployments (manual "Apply" or automatic) don't change the profile, so the
// onStateChange handler above never fires for them. Vortex emits "did-deploy"
// (via emitAndAwait) once deployment has finished, which is our cue to refresh
// sResourceArchive2List so it always matches the enabled mods.
context.api.onAsync('did-deploy', async (profileId) => {
const state = context.api.store.getState();
const profile = state.persistent.profiles[profileId];
if (profile && (profile.gameId === GAME_ID)) {
await updateArchiveList(profile, context.api);
}
});
});
return true;
}
function migrate200(api, oldVersion) {
// If the oldVersion is greater than or equal to 2.0.0, do nothing.
if (semver.gte(oldVersion || '0.0.1', '2.0.0')) return Promise.resolve();
const state = api.store.getState();
const activatorId = selectors.activatorForGame(state, GAME_ID);
const activator = util.getActivator(activatorId);
const discovery = util.getSafe(state, ['settings', 'gameMode', 'discovered', GAME_ID], undefined);
const mods = util.getSafe(state, ['persistent', 'mods', GAME_ID], undefined);
// If we're not managed Fallout 76 yet, do nothing.
if (!discovery || !discovery.path || !activator) return Promise.resolve();
// If we're not managing mods for Fallout 76, do nothing.
if (mods === undefined || Object.keys(mods).length === 0) return Promise.resolve();
const stagingFolder = selectors.installPath(api.getState());
// Wait for the UI to load.
return api.awaitUI()
.then(() => {
const modArray = Object.keys(mods).map(k => mods[k]);
// Interate through each mod to check for BA2 archives.
return Promise.all(modArray.map(mod => {
return new Promise((resolve, reject) => {
const modPath = path.join(stagingFolder, mod.installationPath);
let ba2archives = [];
// Walk through all files for this mod, adding BA2s to the array.
util.walk(modPath, (iterPath, stats) => {
if (path.extname(iterPath) === ARCHIVE_EXT) {
return ba2archives.push(path.basename(iterPath));
}
})
// If we collected some BA2s, set the mod attribute.
.then(() => ba2archives.length ? api.store.dispatch(actions.setModAttribute(GAME_ID, mod.id, 'ba2archives', ba2archives)) : undefined)
});
}))
})
}
module.exports = {
default: main,
// Exposed for the automated install-layout tests (test/); not used by Vortex.
_installPaths: { sanitizeDestination, detectWrapperFolder, stripWrapperFolder },
};