1#![deny(missing_docs)]
17
18use crate::ecosystem::{Ecosystem, GameProfile, InstanceType, LoaderKind};
19use crate::error::{Error, Result};
20use std::path::{Path, PathBuf};
21
22mod prepare;
23
24pub use prepare::{LaunchNotice, prepare_plan_from};
25#[cfg(feature = "io")]
26pub use prepare::{PreparedLaunch, prepare_launch};
27
28#[derive(Debug, Clone, Copy, PartialEq, Eq)]
30#[non_exhaustive]
31pub enum HostOs {
32 Windows,
34 Linux,
37 MacOs,
41}
42
43impl HostOs {
44 pub fn detect() -> Option<Self> {
50 if cfg!(target_os = "windows") {
51 Some(Self::Windows)
52 } else if cfg!(target_os = "linux") {
53 Some(Self::Linux)
54 } else if cfg!(target_os = "macos") {
55 Some(Self::MacOs)
56 } else {
57 None
58 }
59 }
60}
61
62#[derive(Debug, Clone, Copy, PartialEq, Eq)]
64#[non_exhaustive]
65pub enum StorePlatform {
66 Steam,
68 SteamDirect,
70 Other,
72}
73
74impl std::str::FromStr for StorePlatform {
75 type Err = Error;
76
77 fn from_str(value: &str) -> Result<Self> {
79 match value {
80 "steam" => Ok(Self::Steam),
81 "steam-direct" => Ok(Self::SteamDirect),
82 "other" => Ok(Self::Other),
83 other => Err(Error::Profile(format!(
84 "{other:?} is not a known store platform; expected steam, steam-direct, \
85 or other"
86 ))),
87 }
88 }
89}
90
91#[derive(Debug, Clone, Copy, PartialEq, Eq)]
93#[non_exhaustive]
94pub enum Runtime {
95 Native,
97 Proton,
100}
101
102impl std::str::FromStr for Runtime {
103 type Err = Error;
104
105 fn from_str(value: &str) -> Result<Self> {
107 match value {
108 "native" => Ok(Self::Native),
109 "proton" => Ok(Self::Proton),
110 other => Err(Error::Profile(format!(
111 "{other:?} is not a known runtime; expected native or proton"
112 ))),
113 }
114 }
115}
116
117#[derive(Debug, Clone, Copy, PartialEq, Eq)]
119#[non_exhaustive]
120pub enum LaunchMode {
121 Modded,
123 Vanilla,
131}
132
133#[derive(Debug, Clone, PartialEq, Eq)]
135#[non_exhaustive]
136pub enum LaunchProgram {
137 GameExe {
140 exe_names: Vec<String>,
142 },
143 Steam {
145 steam_app_id: u32,
147 },
148 ProfileScript {
153 path: PathBuf,
155 exe_names: Vec<String>,
158 },
159}
160
161#[derive(Debug, Clone, PartialEq, Eq)]
177#[non_exhaustive]
178pub struct SteamWrapper {
179 pub target_dir: PathBuf,
183 pub loader: LoaderKind,
189}
190
191#[derive(Debug, Clone, PartialEq, Eq)]
195#[non_exhaustive]
196pub struct LaunchPlan {
197 pub program: LaunchProgram,
199 pub args: Vec<String>,
201 pub env: Vec<(String, String)>,
214 pub working_dir: Option<PathBuf>,
216 pub steam_wrapper: Option<SteamWrapper>,
221}
222
223#[derive(Debug, Clone, PartialEq, Eq)]
225#[non_exhaustive]
226pub struct LaunchContext {
227 pub os: HostOs,
230 pub store: StorePlatform,
233 pub runtime: Runtime,
236 pub mode: LaunchMode,
238 pub extra_args: Vec<String>,
240}
241
242impl LaunchContext {
243 pub fn new(os: HostOs, store: StorePlatform, runtime: Runtime, mode: LaunchMode) -> Self {
252 Self {
253 os,
254 store,
255 runtime,
256 mode,
257 extra_args: Vec::new(),
258 }
259 }
260
261 pub fn with_extra_args(self, extra_args: Vec<String>) -> Self {
263 Self { extra_args, ..self }
264 }
265}
266
267pub const PRELOADER_CANDIDATES: [&str; 5] = [
270 "BepInEx.Unity.Mono.Preloader.dll",
271 "BepInEx.Unity.IL2CPP.dll",
272 "BepInEx.Preloader.dll",
273 "BepInEx.IL2CPP.dll",
274 "BepInEx.NET.CoreCLR.dll",
275];
276
277pub const LOADER_SCRIPTS: [&str; 3] = [
287 "start_server_bepinex.sh",
288 "run_bepinex.sh",
289 "start_game_bepinex.sh",
290];
291
292const SERVER_SCRIPT: &str = LOADER_SCRIPTS[0];
294
295const MACOS_UNSUPPORTED: &str =
298 "macOS launch is not supported: the injection chain requires r2modman's closed-source proxy";
299
300#[derive(Debug, Clone, PartialEq, Eq)]
321#[non_exhaustive]
322pub struct LaunchFacts {
323 pub doorstop_version: u32,
327 pub preloader: Option<String>,
330 pub has_corlibs: bool,
333 pub loader_scripts: Vec<String>,
335 pub melonloader_assemblies: bool,
339 pub loaders: Vec<LoaderKind>,
342 pub recorded: Vec<String>,
345}
346
347impl Default for LaunchFacts {
348 fn default() -> Self {
349 Self {
350 doorstop_version: 3,
351 preloader: None,
352 has_corlibs: false,
353 loader_scripts: Vec::new(),
354 melonloader_assemblies: false,
355 loaders: Vec::new(),
356 recorded: Vec::new(),
357 }
358 }
359}
360
361const MELONLOADER_FILES: [&str; 4] = [
363 "MelonLoader/MelonLoader.dll",
364 "MelonLoader/net35/MelonLoader.dll",
365 "MelonLoader/net472/MelonLoader.dll",
366 "MelonLoader/net6/MelonLoader.dll",
367];
368
369pub const LOADER_FILES: [(LoaderKind, &[&str]); 7] = [
376 (LoaderKind::Umm, &["UMM/Core/UnityModManager.dll"]),
377 (LoaderKind::MelonLoader, &MELONLOADER_FILES),
378 (LoaderKind::RecursiveMelonLoader, &MELONLOADER_FILES),
379 (
380 LoaderKind::GdWeave,
381 &["GDWeave/core/GDWeave.dll", "winmm.dll"],
382 ),
383 (
384 LoaderKind::Northstar,
385 &["R2Northstar/Northstar.dll", "NorthstarLauncher.exe"],
386 ),
387 (LoaderKind::Rivet, &["Rivet/Loader.dll"]),
388 (LoaderKind::Shimloader, &["dwmapi.dll", "ue4ss.dll"]),
389];
390
391#[cfg(feature = "io")]
392impl LaunchFacts {
393 pub fn read(target_dir: &Path) -> Self {
396 let loader_scripts = LOADER_SCRIPTS
397 .iter()
398 .filter(|name| target_dir.join(name).is_file())
399 .map(|name| name.to_string())
400 .collect();
401 let melonloader_assemblies = target_dir
402 .join("MelonLoader/Managed/Assembly-CSharp.dll")
403 .is_file()
404 || target_dir
405 .join("MelonLoader/Il2CppAssemblies/Assembly-CSharp.dll")
406 .is_file();
407 let loaders = LOADER_FILES
408 .iter()
409 .filter(|(_, files)| files.iter().any(|file| target_dir.join(file).is_file()))
410 .map(|(loader, _)| *loader)
411 .collect();
412 let recorded = crate::profile::modlist::read(target_dir)
413 .map(|mods| mods.into_iter().map(|entry| entry.name).collect())
414 .unwrap_or_default();
415
416 Self {
417 doorstop_version: doorstop_version(target_dir),
418 preloader: find_preloader(target_dir),
419 has_corlibs: has_corlibs(target_dir),
420 loader_scripts,
421 melonloader_assemblies,
422 loaders,
423 recorded,
424 }
425 }
426}
427
428#[cfg(feature = "io")]
435pub fn doorstop_version(target_dir: &Path) -> u32 {
436 let path = target_dir.join(".doorstop_version");
437
438 let text = match std::fs::read_to_string(&path) {
439 Ok(text) => text,
440 Err(_) => return 3,
441 };
442
443 let major = text
444 .trim()
445 .split('.')
446 .next()
447 .and_then(|part| part.parse::<u32>().ok());
448
449 match major {
450 Some(version) if version >= 3 => version,
451 _ => 3,
452 }
453}
454
455fn wine_path(path: &Path) -> String {
457 format!("Z:{}", path.to_string_lossy().replace('\\', "/"))
458}
459
460#[cfg(feature = "io")]
465pub fn bepinex_preloader(target_dir: &Path, runtime: Runtime) -> Result<String> {
466 render_preloader(target_dir, find_preloader(target_dir).as_deref(), runtime)
467}
468
469#[cfg(feature = "io")]
471fn find_preloader(target_dir: &Path) -> Option<String> {
472 let core = target_dir.join("BepInEx").join("core");
473
474 PRELOADER_CANDIDATES
475 .iter()
476 .find(|name| core.join(name).is_file())
477 .map(|name| name.to_string())
478}
479
480fn render_preloader(
483 target_dir: &Path,
484 preloader: Option<&str>,
485 runtime: Runtime,
486) -> Result<String> {
487 let core = target_dir.join("BepInEx").join("core");
488
489 let found = preloader
490 .map(|name| core.join(name))
491 .ok_or_else(|| Error::Profile(format!("no BepInEx preloader found in {}", core.display())))?;
492
493 let rendered = match runtime {
494 Runtime::Proton => wine_path(&found),
495 Runtime::Native => found.to_string_lossy().replace('\\', "/"),
496 };
497
498 Ok(rendered)
499}
500
501#[cfg(feature = "io")]
504pub fn has_corlibs(target_dir: &Path) -> bool {
505 target_dir.join("unstripped_corlib").is_dir()
506}
507
508fn arg_path(target_dir: &Path, relative: &str) -> String {
511 target_dir
512 .join(relative)
513 .to_string_lossy()
514 .replace('\\', "/")
515}
516
517#[cfg(feature = "io")]
523pub fn loader_args(
524 target_dir: &Path,
525 profile: &GameProfile,
526 ctx: &LaunchContext,
527) -> Result<Vec<String>> {
528 loader_args_from(target_dir, &LaunchFacts::read(target_dir), profile, ctx)
529}
530
531pub fn loader_args_from(
546 target_dir: &Path,
547 facts: &LaunchFacts,
548 profile: &GameProfile,
549 ctx: &LaunchContext,
550) -> Result<Vec<String>> {
551 let target = target_dir.to_string_lossy().replace('\\', "/");
552
553 let args = match profile.package_loader {
554 LoaderKind::BepInEx => {
555 let script_injected = is_script_injected(target_dir, facts, profile, ctx);
556
557 doorstop_args(
558 target_dir,
559 facts,
560 profile,
561 ctx,
562 DoorstopTarget::BepInEx,
563 script_injected,
564 )?
565 }
566 LoaderKind::BepisLoader => bepis_args(target_dir, facts, profile, ctx)?,
567 LoaderKind::Umm => {
568 let script_injected = is_script_injected(target_dir, facts, profile, ctx);
569
570 doorstop_args(
571 target_dir,
572 facts,
573 profile,
574 ctx,
575 DoorstopTarget::Umm,
576 script_injected,
577 )?
578 }
579 LoaderKind::MelonLoader | LoaderKind::RecursiveMelonLoader => {
580 melonloader_args(facts, ctx, &target)
581 }
582 LoaderKind::GdWeave => match ctx.mode {
583 LaunchMode::Modded => vec![format!(
584 "--gdweave-folder-override={}",
585 arg_path(target_dir, "GDWeave")
586 )],
587 LaunchMode::Vanilla => vec!["--gdweave-disable".to_string()],
588 },
589 LoaderKind::Lovely => match ctx.mode {
590 LaunchMode::Modded => vec!["--mod-dir".to_string(), arg_path(target_dir, "mods")],
591 LaunchMode::Vanilla => vec!["--vanilla".to_string()],
592 },
593 LoaderKind::Northstar => match ctx.mode {
594 LaunchMode::Modded => vec![
595 "-northstar".to_string(),
596 format!("-profile={}", arg_path(target_dir, "R2Northstar")),
597 ],
598 LaunchMode::Vanilla => vec!["-vanilla".to_string()],
599 },
600 LoaderKind::GodotMl => match ctx.mode {
601 LaunchMode::Modded => vec![
602 "--script".to_string(),
603 "res://addons/mod_loader/mod_loader_setup.gd".to_string(),
604 "--enable-mods".to_string(),
605 "--mods-path".to_string(),
606 arg_path(target_dir, "mods"),
607 ],
608 LaunchMode::Vanilla => Vec::new(),
609 },
610 LoaderKind::Shimloader => match ctx.mode {
611 LaunchMode::Modded => vec![
612 "--mod-dir".to_string(),
613 arg_path(target_dir, "shimloader/mod"),
614 "--pak-dir".to_string(),
615 arg_path(target_dir, "shimloader/pak"),
616 "--cfg-dir".to_string(),
617 arg_path(target_dir, "shimloader/cfg"),
618 "--overlay-dir".to_string(),
619 arg_path(target_dir, "shimloader/overlay"),
620 ],
621 LaunchMode::Vanilla => Vec::new(),
622 },
623 LoaderKind::ReturnOfModding => match ctx.mode {
624 LaunchMode::Modded => vec!["--rom_modding_root_folder".to_string(), target.clone()],
625 LaunchMode::Vanilla => vec!["--rom_enabled".to_string(), "false".to_string()],
626 },
627 LoaderKind::Rivet => match ctx.mode {
628 LaunchMode::Modded => vec![
629 "-rivetEnable".to_string(),
630 "true".to_string(),
631 "-rivetTarget".to_string(),
632 arg_path(target_dir, "Rivet/Loader.dll"),
633 "-rivetDirectory".to_string(),
634 arg_path(target_dir, "Rivet/Mods"),
635 ],
636 LaunchMode::Vanilla => vec!["-rivetEnable".to_string(), "false".to_string()],
637 },
638 _ => Vec::new(),
641 };
642
643 Ok(args)
644}
645
646#[derive(Debug, Clone, Copy, PartialEq, Eq)]
648enum DoorstopTarget {
649 BepInEx,
650 Umm,
651}
652
653fn doorstop_args(
677 target_dir: &Path,
678 facts: &LaunchFacts,
679 profile: &GameProfile,
680 ctx: &LaunchContext,
681 target: DoorstopTarget,
682 script_injected: bool,
683) -> Result<Vec<String>> {
684 let v4 = script_injected || facts.doorstop_version >= 4;
685
686 let (enable_flag, target_flag, search_flag) = if v4 {
687 (
688 "--doorstop-enabled",
689 "--doorstop-target-assembly",
690 "--doorstop-mono-dll-search-path-override",
691 )
692 } else {
693 (
694 "--doorstop-enable",
695 "--doorstop-target",
696 "--doorstop-dll-search-override",
697 )
698 };
699
700 if ctx.mode == LaunchMode::Vanilla {
701 return Ok(vec![enable_flag.to_string(), "false".to_string()]);
702 }
703
704 let assembly = match target {
705 DoorstopTarget::BepInEx => {
706 render_preloader(target_dir, facts.preloader.as_deref(), ctx.runtime)?
707 }
708 DoorstopTarget::Umm => arg_path(target_dir, "UMM/Core/UnityModManager.dll"),
709 };
710
711 let mut args = vec![
712 enable_flag.to_string(),
713 "true".to_string(),
714 target_flag.to_string(),
715 assembly,
716 ];
717
718 if target == DoorstopTarget::BepInEx && profile.instance_type == InstanceType::Server {
719 args.push("--server".to_string());
720 }
721
722 if facts.has_corlibs {
723 args.push(search_flag.to_string());
724 args.push(arg_path(target_dir, "unstripped_corlib"));
725 }
726
727 Ok(args)
728}
729
730fn bepis_args(
732 target_dir: &Path,
733 facts: &LaunchFacts,
734 profile: &GameProfile,
735 ctx: &LaunchContext,
736) -> Result<Vec<String>> {
737 if ctx.mode == LaunchMode::Vanilla {
738 return Ok(vec![
739 "--hookfxr-disable".to_string(),
740 "--doorstop-enabled".to_string(),
741 "false".to_string(),
742 ]);
743 }
744
745 let mut args = vec![
746 "--hookfxr-enable".to_string(),
747 "--bepinex-target".to_string(),
748 arg_path(target_dir, "BepInEx"),
749 "--doorstop-enabled".to_string(),
750 "true".to_string(),
751 "--doorstop-target-assembly".to_string(),
752 render_preloader(target_dir, facts.preloader.as_deref(), ctx.runtime)?,
753 ];
754
755 if profile.instance_type == InstanceType::Server {
756 args.push("--server".to_string());
757 }
758
759 if facts.has_corlibs {
760 args.push("--doorstop-mono-dll-search-path-override".to_string());
761 args.push(arg_path(target_dir, "unstripped_corlib"));
762 }
763
764 Ok(args)
765}
766
767fn melonloader_args(facts: &LaunchFacts, ctx: &LaunchContext, target: &str) -> Vec<String> {
770 if ctx.mode == LaunchMode::Vanilla {
771 return vec!["--no-mods".to_string()];
772 }
773
774 let mut args = vec!["--melonloader.basedir".to_string(), target.to_string()];
775
776 if !facts.melonloader_assemblies {
777 args.push("--melonloader.agfregenerate".to_string());
778 }
779
780 args
781}
782
783pub fn proxy_dll(loader: LoaderKind) -> &'static str {
785 match loader {
786 LoaderKind::GdWeave => "winmm",
787 _ => "winhttp",
788 }
789}
790
791#[derive(Debug, Clone, PartialEq, Eq)]
797enum ScriptInjection {
798 NotApplicable,
801 Found(PathBuf),
803 Missing,
805}
806
807impl ScriptInjection {
808 fn applies(&self) -> bool {
813 !matches!(self, Self::NotApplicable)
814 }
815}
816
817fn script_candidates(profile: &GameProfile) -> Vec<&'static str> {
819 match profile.instance_type {
820 InstanceType::Server => LOADER_SCRIPTS.to_vec(),
821 _ => LOADER_SCRIPTS
822 .iter()
823 .copied()
824 .filter(|name| *name != SERVER_SCRIPT)
825 .collect(),
826 }
827}
828
829fn script_injection(
837 target_dir: &Path,
838 facts: &LaunchFacts,
839 profile: &GameProfile,
840 ctx: &LaunchContext,
841) -> ScriptInjection {
842 if !script_injection_applies(profile, ctx) {
843 return ScriptInjection::NotApplicable;
844 }
845
846 let found = script_candidates(profile)
847 .into_iter()
848 .find(|name| facts.loader_scripts.iter().any(|present| present == name));
849
850 match found {
851 Some(name) => ScriptInjection::Found(target_dir.join(name)),
852 None => ScriptInjection::Missing,
853 }
854}
855
856fn script_injection_applies(profile: &GameProfile, ctx: &LaunchContext) -> bool {
859 let script_loader = matches!(
860 profile.package_loader,
861 LoaderKind::BepInEx | LoaderKind::BepisLoader
862 );
863
864 script_loader && ctx.os == HostOs::Linux && ctx.runtime == Runtime::Native
865}
866
867fn is_script_injected(
877 target_dir: &Path,
878 facts: &LaunchFacts,
879 profile: &GameProfile,
880 ctx: &LaunchContext,
881) -> bool {
882 matches!(
883 script_injection(target_dir, facts, profile, ctx),
884 ScriptInjection::Found(_)
885 )
886}
887
888#[cfg(feature = "io")]
947pub fn launch_plan_in(
948 target_dir: &Path,
949 eco: &Ecosystem,
950 game: &str,
951 ctx: &LaunchContext,
952) -> Result<LaunchPlan> {
953 launch_plan_from(target_dir, &LaunchFacts::read(target_dir), eco, game, ctx)
954}
955
956pub fn launch_plan_from(
991 target_dir: &Path,
992 facts: &LaunchFacts,
993 eco: &Ecosystem,
994 game: &str,
995 ctx: &LaunchContext,
996) -> Result<LaunchPlan> {
997 if ctx.os == HostOs::MacOs {
998 return Err(Error::Profile(MACOS_UNSUPPORTED.to_string()));
999 }
1000
1001 let profile = eco.require_profile(game)?;
1002
1003 let injection = script_injection(target_dir, facts, profile, ctx);
1007 let mut args = loader_args_from(target_dir, facts, profile, ctx)?;
1008
1009 args.extend(ctx.extra_args.iter().cloned());
1010
1011 let program = resolve_program(&injection, target_dir, profile, ctx)?;
1012 let needs_wrapper = injection.applies() && ctx.store == StorePlatform::Steam;
1013
1014 if needs_wrapper {
1019 args.extend(wrapper_target_args(target_dir));
1020 }
1021
1022 let steam_wrapper = needs_wrapper.then(|| SteamWrapper {
1023 target_dir: target_dir.to_path_buf(),
1024 loader: profile.package_loader,
1025 });
1026
1027 let mut env = Vec::new();
1028
1029 if ctx.runtime == Runtime::Proton {
1030 env.push((
1031 "WINEDLLOVERRIDES".to_string(),
1032 format!("{}=n,b", proxy_dll(profile.package_loader)),
1033 ));
1034 }
1035
1036 Ok(LaunchPlan {
1037 program,
1038 args,
1039 env,
1040 working_dir: None,
1041 steam_wrapper,
1042 })
1043}
1044
1045fn resolve_program(
1051 injection: &ScriptInjection,
1052 target_dir: &Path,
1053 profile: &GameProfile,
1054 ctx: &LaunchContext,
1055) -> Result<LaunchProgram> {
1056 if *injection == ScriptInjection::Missing && ctx.mode == LaunchMode::Modded {
1057 return Err(Error::Profile(format!(
1058 "modded launch injects through a loader script, but none of {} exist in {}",
1059 script_candidates(profile).join(", "),
1060 target_dir.display(),
1061 )));
1062 }
1063
1064 if let ScriptInjection::Found(path) = injection
1065 && ctx.store != StorePlatform::Steam
1066 {
1067 return Ok(LaunchProgram::ProfileScript {
1068 path: path.clone(),
1069 exe_names: profile.exe_names.clone(),
1070 });
1071 }
1072
1073 if ctx.store == StorePlatform::Steam {
1074 let steam_app_id = profile.steam_app_id().ok_or_else(|| {
1075 Error::Profile("Steam launch requested but the game has no Steam app id".to_string())
1076 })?;
1077
1078 return Ok(LaunchProgram::Steam { steam_app_id });
1079 }
1080
1081 Ok(LaunchProgram::GameExe {
1082 exe_names: profile.exe_names.clone(),
1083 })
1084}
1085
1086#[cfg(feature = "io")]
1089pub fn launch_plan(
1090 base: &Path,
1091 game: &str,
1092 profile_name: &str,
1093 eco: &Ecosystem,
1094 ctx: &LaunchContext,
1095) -> Result<LaunchPlan> {
1096 launch_plan_in(
1097 &crate::profile::layout::profile_dir(base, game, profile_name),
1098 eco,
1099 game,
1100 ctx,
1101 )
1102}
1103
1104pub const WRAPPER_TARGET_FLAG: &str = "--ts-target";
1110
1111pub fn wrapper_target_args(target_dir: &Path) -> Vec<String> {
1118 vec![
1119 WRAPPER_TARGET_FLAG.to_string(),
1120 target_dir.to_string_lossy().replace('\\', "/"),
1121 ]
1122}
1123
1124pub fn wrapper_script_contents() -> String {
1158 let mut branches = String::new();
1159
1160 for (index, name) in LOADER_SCRIPTS.iter().enumerate() {
1161 let keyword = if index == 0 { "if" } else { "elif" };
1162 let server_gate = if *name == SERVER_SCRIPT {
1165 r#" && [ -n "$TS_START_SERVER" ]"#
1166 } else {
1167 ""
1168 };
1169
1170 branches.push_str(&format!(
1171 "{keyword} [ -f \"$TARGET/{name}\" ]{server_gate}; then\n exec \"$TARGET/{name}\" \"$@\"\n"
1172 ));
1173 }
1174
1175 format!(
1182 r#"#!/bin/sh
1183# Generated by thunderstore-engine. Chainloads the mod loader for a target.
1184#
1185# Paste this into Steam's launch options once; it never needs regenerating, and
1186# it names no profile. The target directory is read from
1187# `{WRAPPER_TARGET_FLAG} <dir>` when a manager appends it to the launch
1188# arguments. Without it — launching straight from Steam — the game starts
1189# unmodded. The flag is consumed here and never reaches the game.
1190TARGET=""
1191
1192remaining=$#
1193
1194while [ "$remaining" -gt 0 ]; do
1195 argument="$1"
1196 shift
1197 remaining=$((remaining - 1))
1198
1199 if [ "$argument" = "{WRAPPER_TARGET_FLAG}" ]; then
1200 if [ "$remaining" -gt 0 ]; then
1201 candidate="$1"
1202 shift
1203 remaining=$((remaining - 1))
1204
1205 if [ -d "$candidate" ]; then
1206 TARGET="$candidate"
1207 fi
1208 fi
1209
1210 continue
1211 fi
1212
1213 set -- "$@" "$argument"
1214done
1215
1216if [ -z "$TARGET" ]; then
1217 exec "$@"
1218fi
1219
1220{branches}else
1221 exec "$@"
1222fi
1223"#
1224 )
1225}
1226
1227#[cfg(feature = "io")]
1233pub fn write_wrapper_script(script_path: &Path) -> Result<()> {
1234 if let Some(parent) = script_path.parent() {
1235 std::fs::create_dir_all(parent)
1236 .map_err(|e| Error::Profile(format!("creating {}: {}", parent.display(), e)))?;
1237 }
1238
1239 std::fs::write(script_path, wrapper_script_contents())
1240 .map_err(|e| Error::Profile(format!("writing {}: {}", script_path.display(), e)))?;
1241
1242 #[cfg(unix)]
1243 {
1244 use std::os::unix::fs::PermissionsExt;
1245
1246 let permissions = std::fs::Permissions::from_mode(0o755);
1247
1248 std::fs::set_permissions(script_path, permissions)
1249 .map_err(|e| Error::Profile(format!("chmod {}: {}", script_path.display(), e)))?;
1250 }
1251
1252 Ok(())
1253}
1254
1255#[cfg(feature = "io")]
1279pub fn ensure_loader_scripts_executable(target_dir: &Path) -> Result<Vec<PathBuf>> {
1280 let mut changed = Vec::new();
1281
1282 for name in LOADER_SCRIPTS {
1283 let path = target_dir.join(name);
1284
1285 if !path.is_file() {
1286 continue;
1287 }
1288
1289 if make_executable(&path)? {
1290 changed.push(path);
1291 }
1292 }
1293
1294 Ok(changed)
1295}
1296
1297#[cfg(feature = "io")]
1305fn make_executable(path: &Path) -> Result<bool> {
1306 #[cfg(unix)]
1307 {
1308 use std::os::unix::fs::PermissionsExt;
1309
1310 let metadata = std::fs::metadata(path)
1311 .map_err(|e| Error::Profile(format!("inspecting {}: {}", path.display(), e)))?;
1312 let mode = metadata.permissions().mode();
1313 let wanted = mode | ((mode & 0o444) >> 2);
1314
1315 if wanted == mode {
1316 return Ok(false);
1317 }
1318
1319 std::fs::set_permissions(path, std::fs::Permissions::from_mode(wanted))
1320 .map_err(|e| Error::Profile(format!("chmod {}: {}", path.display(), e)))?;
1321
1322 Ok(true)
1323 }
1324
1325 #[cfg(not(unix))]
1326 {
1327 let _ = path;
1328
1329 Ok(false)
1330 }
1331}
1332
1333const SHIMLOADER_STAGED: [&str; 3] = ["ue4ss.dll", "dwmapi.dll", "ue4ss-settings.ini"];
1335
1336pub fn stage_destination(
1339 loader: LoaderKind,
1340 file_name: &str,
1341 game_dir: &Path,
1342 data_folder: Option<&str>,
1343) -> Option<PathBuf> {
1344 let lowercased = file_name.to_ascii_lowercase();
1345
1346 if lowercased == "mods.yml" {
1347 return None;
1348 }
1349
1350 match loader {
1351 LoaderKind::Shimloader => {
1352 if !SHIMLOADER_STAGED.iter().any(|name| *name == lowercased) {
1353 return None;
1354 }
1355
1356 let data = data_folder?;
1357
1358 Some(
1359 game_dir
1360 .join(data)
1361 .join("Binaries")
1362 .join("Win64")
1363 .join(file_name),
1364 )
1365 }
1366 LoaderKind::Rivet => {
1367 if lowercased != "version.dll" {
1368 return None;
1369 }
1370
1371 Some(game_dir.join("Release").join(file_name))
1372 }
1373 _ => Some(game_dir.join(file_name)),
1374 }
1375}
1376
1377#[cfg(feature = "io")]
1420pub fn stage_for_launch_in(
1421 target_dir: &Path,
1422 eco: &Ecosystem,
1423 game: &str,
1424 game_dir: &Path,
1425 ctx: &LaunchContext,
1426) -> Result<Vec<PathBuf>> {
1427 let staged = stage_files_in(target_dir, eco, game, game_dir, ctx)?;
1428 let mut written = staged.created;
1429
1430 written.extend(staged.replaced);
1431 written.sort();
1432
1433 Ok(written)
1434}
1435
1436#[cfg(feature = "io")]
1443pub(crate) fn stage_files_in(
1444 target_dir: &Path,
1445 eco: &Ecosystem,
1446 game: &str,
1447 game_dir: &Path,
1448 ctx: &LaunchContext,
1449) -> Result<StagedFiles> {
1450 if ctx.os == HostOs::MacOs {
1451 return Err(Error::Profile(MACOS_UNSUPPORTED.to_string()));
1452 }
1453
1454 let profile = eco.require_profile(game)?;
1455
1456 if script_injection_applies(profile, ctx) {
1457 return Ok(StagedFiles::default());
1458 }
1459
1460 let mut copies = Vec::new();
1461
1462 for entry in std::fs::read_dir(target_dir)
1463 .map_err(|e| Error::Profile(format!("reading {}: {}", target_dir.display(), e)))?
1464 {
1465 let entry = entry.map_err(|e| Error::Profile(format!("reading an entry: {e}")))?;
1466 let metadata = std::fs::symlink_metadata(entry.path())
1467 .map_err(|e| Error::Profile(format!("inspecting {}: {}", entry.path().display(), e)))?;
1468
1469 if !metadata.is_file() {
1470 continue;
1471 }
1472
1473 let file_name = match entry.file_name().to_str() {
1474 Some(name) => name.to_string(),
1475 None => continue,
1476 };
1477
1478 let dest = match stage_destination(
1479 profile.package_loader,
1480 &file_name,
1481 game_dir,
1482 profile.data_folder_name.as_deref(),
1483 ) {
1484 Some(dest) => dest,
1485 None => continue,
1486 };
1487
1488 copies.push((entry.path(), dest));
1489 }
1490
1491 copies.sort();
1492
1493 let mut staged = StagedFiles::default();
1494
1495 for (source, dest) in copies {
1496 match stage_one_file(&source, &dest) {
1497 Ok(StagedFile::InPlace) => {}
1498 Ok(StagedFile::Created) => staged.created.push(dest),
1499 Ok(StagedFile::Replaced) => staged.replaced.push(dest),
1500 Err(error) => {
1501 for created in &staged.created {
1502 let _ = std::fs::remove_file(created);
1503 }
1504
1505 return Err(error);
1506 }
1507 }
1508 }
1509
1510 staged.created.sort();
1511 staged.replaced.sort();
1512
1513 Ok(staged)
1514}
1515
1516#[cfg(feature = "io")]
1519pub fn stage_for_launch(
1520 base: &Path,
1521 game: &str,
1522 profile_name: &str,
1523 eco: &Ecosystem,
1524 game_dir: &Path,
1525 ctx: &LaunchContext,
1526) -> Result<Vec<PathBuf>> {
1527 stage_for_launch_in(
1528 &crate::profile::layout::profile_dir(base, game, profile_name),
1529 eco,
1530 game,
1531 game_dir,
1532 ctx,
1533 )
1534}
1535
1536#[cfg(feature = "io")]
1550fn stage_one_file(source: &Path, dest: &Path) -> Result<StagedFile> {
1551 let existing = std::fs::symlink_metadata(dest).ok();
1552
1553 if existing
1554 .as_ref()
1555 .is_some_and(|metadata| metadata.file_type().is_symlink())
1556 {
1557 return Err(Error::Profile(format!(
1558 "refusing to stage through a symlink at {}",
1559 dest.display()
1560 )));
1561 }
1562
1563 if crate::util::same_file(source, dest) {
1564 return Ok(StagedFile::InPlace);
1565 }
1566
1567 if let Some(parent) = dest.parent() {
1568 std::fs::create_dir_all(parent)
1569 .map_err(|e| Error::Profile(format!("creating {}: {}", parent.display(), e)))?;
1570 }
1571
1572 std::fs::copy(source, dest)
1573 .map_err(|e| Error::Profile(format!("staging {}: {}", dest.display(), e)))?;
1574
1575 match existing {
1576 Some(_) => Ok(StagedFile::Replaced),
1577 None => Ok(StagedFile::Created),
1578 }
1579}
1580
1581#[cfg(feature = "io")]
1583enum StagedFile {
1584 InPlace,
1586 Created,
1588 Replaced,
1590}
1591
1592#[cfg(feature = "io")]
1595#[derive(Debug, Default)]
1596pub(crate) struct StagedFiles {
1597 pub(crate) created: Vec<PathBuf>,
1599 pub(crate) replaced: Vec<PathBuf>,
1601}
1602
1603pub fn steam_launch_options(script_path: &Path) -> String {
1624 format!(
1625 r#""{script}" %command%"#,
1626 script = script_path.to_string_lossy().replace('\\', "/"),
1627 )
1628}
1629
1630#[cfg(feature = "io")]
1632pub fn resolve_game_exe(game_dir: &Path, exe_names: &[String]) -> Result<PathBuf> {
1633 exe_names
1634 .iter()
1635 .map(|name| game_dir.join(name))
1636 .find(|candidate| candidate.is_file())
1637 .ok_or_else(|| {
1638 Error::Profile(format!(
1639 "no game executable found in {}: none of {} exist",
1640 game_dir.display(),
1641 exe_names.join(", ")
1642 ))
1643 })
1644}
1645
1646pub fn wrapper_path(base: &Path, game: &str) -> PathBuf {
1653 base.join(game).join("steam-wrapper.sh")
1654}
1655
1656#[cfg(feature = "io")]
1667fn steam_command(program: &Path, steam_app_id: u32) -> std::process::Command {
1668 let mut command = std::process::Command::new(program);
1669
1670 command.arg("-applaunch").arg(steam_app_id.to_string());
1671
1672 command
1673}
1674
1675#[cfg(feature = "io")]
1676impl LaunchPlan {
1677 pub fn to_command(&self, game_dir: &Path) -> Result<std::process::Command> {
1699 let mut command = match &self.program {
1700 LaunchProgram::GameExe { exe_names } => {
1701 std::process::Command::new(resolve_game_exe(game_dir, exe_names)?)
1702 }
1703 LaunchProgram::Steam { steam_app_id } => {
1704 steam_command(&crate::steam::steam_exe(), *steam_app_id)
1705 }
1706 LaunchProgram::ProfileScript { path, exe_names } => {
1707 let mut command = std::process::Command::new(path);
1708
1709 command.arg(resolve_game_exe(game_dir, exe_names)?);
1710
1711 command
1712 }
1713 };
1714
1715 command.args(&self.args);
1716
1717 for (key, value) in &self.env {
1718 command.env(key, value);
1719 }
1720
1721 if let Some(dir) = &self.working_dir {
1722 command.current_dir(dir);
1723 }
1724
1725 Ok(command)
1726 }
1727}
1728
1729#[cfg(all(test, feature = "io"))]
1730mod tests {
1731 use super::*;
1732
1733 pub(super) fn assert_options_name_script(options: &str, script: &Path) {
1736 let quoted = options
1737 .strip_suffix(" %command%")
1738 .and_then(|rest| rest.strip_prefix('"'))
1739 .and_then(|rest| rest.strip_suffix('"'))
1740 .unwrap_or_else(|| panic!("not a quoted path then %command%: {options}"));
1741
1742 #[cfg(unix)]
1743 assert_eq!(quoted, script.to_str().unwrap());
1744
1745 #[cfg(not(unix))]
1746 {
1747 assert!(!quoted.contains('\\'), "{quoted}");
1748 assert_eq!(
1749 std::fs::canonicalize(quoted).unwrap(),
1750 std::fs::canonicalize(script).unwrap()
1751 );
1752 }
1753 }
1754
1755 #[test]
1756 fn doorstop_version_reads_major_and_defaults_to_three() {
1757 let dir = tempfile::tempdir().unwrap();
1758 let root = dir.path();
1759
1760 assert_eq!(doorstop_version(root), 3);
1762
1763 std::fs::write(root.join(".doorstop_version"), "4.0.0").unwrap();
1764 assert_eq!(doorstop_version(root), 4);
1765
1766 std::fs::write(root.join(".doorstop_version"), "3.7.1").unwrap();
1767 assert_eq!(doorstop_version(root), 3);
1768
1769 std::fs::write(root.join(".doorstop_version"), "5.1.0").unwrap();
1771 assert_eq!(doorstop_version(root), 5);
1772
1773 std::fs::write(root.join(".doorstop_version"), "garbage").unwrap();
1775 assert_eq!(doorstop_version(root), 3);
1776 }
1777
1778 #[test]
1779 fn bepinex_preloader_finds_candidate_and_prefixes_under_proton() {
1780 let dir = tempfile::tempdir().unwrap();
1781 let root = dir.path();
1782 let core = root.join("BepInEx/core");
1783
1784 std::fs::create_dir_all(&core).unwrap();
1785 std::fs::write(core.join("BepInEx.Preloader.dll"), b"x").unwrap();
1786 std::fs::write(core.join("Unrelated.dll"), b"x").unwrap();
1787
1788 let native = bepinex_preloader(root, Runtime::Native).unwrap();
1789
1790 assert!(native.ends_with("BepInEx/core/BepInEx.Preloader.dll"));
1791 assert!(!native.starts_with("Z:"));
1792
1793 let proton = bepinex_preloader(root, Runtime::Proton).unwrap();
1794
1795 assert!(proton.starts_with("Z:"));
1796 assert!(proton.ends_with("BepInEx/core/BepInEx.Preloader.dll"));
1797 }
1798
1799 #[test]
1800 fn bepinex_preloader_errors_when_absent() {
1801 let dir = tempfile::tempdir().unwrap();
1802
1803 assert!(bepinex_preloader(dir.path(), Runtime::Native).is_err());
1804 }
1805
1806 #[test]
1807 fn has_corlibs_detects_the_directory() {
1808 let dir = tempfile::tempdir().unwrap();
1809 let root = dir.path();
1810
1811 assert!(!has_corlibs(root));
1812
1813 std::fs::create_dir_all(root.join("unstripped_corlib")).unwrap();
1814
1815 assert!(has_corlibs(root));
1816 }
1817
1818 fn ctx(mode: LaunchMode) -> LaunchContext {
1819 LaunchContext {
1820 os: HostOs::Windows,
1821 store: StorePlatform::Steam,
1822 runtime: Runtime::Native,
1823 mode,
1824 extra_args: Vec::new(),
1825 }
1826 }
1827
1828 fn profile_with(loader: LoaderKind) -> GameProfile {
1829 let eco = Ecosystem::bundled();
1830 let mut profile = eco.game("valheim").unwrap().profile().unwrap().clone();
1831 profile.package_loader = loader;
1832
1833 profile
1834 }
1835
1836 #[test]
1837 fn bepinex_v3_and_v4_use_the_right_flag_spellings() {
1838 let dir = tempfile::tempdir().unwrap();
1839 let root = dir.path();
1840 let core = root.join("BepInEx/core");
1841
1842 std::fs::create_dir_all(&core).unwrap();
1843 std::fs::write(core.join("BepInEx.Preloader.dll"), b"x").unwrap();
1844
1845 let profile = profile_with(LoaderKind::BepInEx);
1846
1847 let v3 = loader_args(root, &profile, &ctx(LaunchMode::Modded)).unwrap();
1848
1849 assert_eq!(v3[0], "--doorstop-enable");
1850 assert_eq!(v3[1], "true");
1851 assert_eq!(v3[2], "--doorstop-target");
1852
1853 std::fs::write(root.join(".doorstop_version"), "4.0.0").unwrap();
1854
1855 let v4 = loader_args(root, &profile, &ctx(LaunchMode::Modded)).unwrap();
1856
1857 assert_eq!(v4[0], "--doorstop-enabled");
1858 assert_eq!(v4[2], "--doorstop-target-assembly");
1859
1860 let vanilla = loader_args(root, &profile, &ctx(LaunchMode::Vanilla)).unwrap();
1863
1864 assert_eq!(
1865 vanilla,
1866 vec!["--doorstop-enabled".to_string(), "false".to_string()]
1867 );
1868 }
1869
1870 #[test]
1871 fn melonloader_adds_regenerate_only_when_assemblies_are_absent() {
1872 let dir = tempfile::tempdir().unwrap();
1873 let root = dir.path();
1874 let profile = profile_with(LoaderKind::MelonLoader);
1875
1876 let bare = loader_args(root, &profile, &ctx(LaunchMode::Modded)).unwrap();
1877
1878 assert_eq!(bare[0], "--melonloader.basedir");
1879 assert!(bare.contains(&"--melonloader.agfregenerate".to_string()));
1880
1881 let managed = root.join("MelonLoader/Managed");
1882 std::fs::create_dir_all(&managed).unwrap();
1883 std::fs::write(managed.join("Assembly-CSharp.dll"), b"x").unwrap();
1884
1885 let with_assembly = loader_args(root, &profile, &ctx(LaunchMode::Modded)).unwrap();
1886
1887 assert!(!with_assembly.contains(&"--melonloader.agfregenerate".to_string()));
1888 assert_eq!(
1889 loader_args(root, &profile, &ctx(LaunchMode::Vanilla)).unwrap(),
1890 vec!["--no-mods".to_string()]
1891 );
1892 }
1893
1894 #[test]
1895 fn single_element_flags_stay_single_elements() {
1896 let dir = tempfile::tempdir().unwrap();
1897 let root = dir.path();
1898
1899 let gdweave = loader_args(
1900 root,
1901 &profile_with(LoaderKind::GdWeave),
1902 &ctx(LaunchMode::Modded),
1903 )
1904 .unwrap();
1905
1906 assert_eq!(gdweave.len(), 1);
1907 assert!(gdweave[0].starts_with("--gdweave-folder-override="));
1908 assert!(gdweave[0].ends_with("/GDWeave"));
1909
1910 let northstar = loader_args(
1911 root,
1912 &profile_with(LoaderKind::Northstar),
1913 &ctx(LaunchMode::Modded),
1914 )
1915 .unwrap();
1916
1917 assert_eq!(northstar[0], "-northstar");
1918 assert!(northstar[1].starts_with("-profile="));
1919 }
1920
1921 #[test]
1922 fn shimloader_and_rivet_and_rom_shapes() {
1923 let dir = tempfile::tempdir().unwrap();
1924 let root = dir.path();
1925
1926 let shim = loader_args(
1927 root,
1928 &profile_with(LoaderKind::Shimloader),
1929 &ctx(LaunchMode::Modded),
1930 )
1931 .unwrap();
1932
1933 assert_eq!(shim.len(), 8);
1934 assert_eq!(shim[0], "--mod-dir");
1935 assert!(shim.contains(&"--overlay-dir".to_string()));
1936
1937 let rivet = loader_args(
1938 root,
1939 &profile_with(LoaderKind::Rivet),
1940 &ctx(LaunchMode::Modded),
1941 )
1942 .unwrap();
1943
1944 assert_eq!(rivet[0], "-rivetEnable");
1945 assert_eq!(rivet[1], "true");
1946 assert!(rivet.contains(&"-rivetDirectory".to_string()));
1947 assert_eq!(
1948 loader_args(
1949 root,
1950 &profile_with(LoaderKind::Rivet),
1951 &ctx(LaunchMode::Vanilla)
1952 )
1953 .unwrap(),
1954 vec!["-rivetEnable".to_string(), "false".to_string()]
1955 );
1956
1957 let rom = loader_args(
1958 root,
1959 &profile_with(LoaderKind::ReturnOfModding),
1960 &ctx(LaunchMode::Modded),
1961 )
1962 .unwrap();
1963
1964 assert_eq!(rom[0], "--rom_modding_root_folder");
1965 }
1966
1967 #[test]
1968 fn unknown_and_none_loaders_produce_no_args() {
1969 let dir = tempfile::tempdir().unwrap();
1970 let root = dir.path();
1971
1972 assert!(
1973 loader_args(
1974 root,
1975 &profile_with(LoaderKind::None),
1976 &ctx(LaunchMode::Modded)
1977 )
1978 .unwrap()
1979 .is_empty()
1980 );
1981 assert!(
1982 loader_args(
1983 root,
1984 &profile_with(LoaderKind::Other),
1985 &ctx(LaunchMode::Modded)
1986 )
1987 .unwrap()
1988 .is_empty()
1989 );
1990 }
1991
1992 #[test]
1993 fn server_instance_appends_server_flag_for_bepinex() {
1994 let dir = tempfile::tempdir().unwrap();
1995 let root = dir.path();
1996 let core = root.join("BepInEx/core");
1997
1998 std::fs::create_dir_all(&core).unwrap();
1999 std::fs::write(core.join("BepInEx.Preloader.dll"), b"x").unwrap();
2000
2001 let mut profile = profile_with(LoaderKind::BepInEx);
2002 profile.instance_type = InstanceType::Server;
2003
2004 let args = loader_args(root, &profile, &ctx(LaunchMode::Modded)).unwrap();
2005
2006 assert!(args.contains(&"--server".to_string()));
2007 }
2008
2009 #[test]
2010 fn umm_uses_doorstop_flags_and_never_gets_server_flag() {
2011 let dir = tempfile::tempdir().unwrap();
2012 let root = dir.path();
2013 let profile = profile_with(LoaderKind::Umm);
2014
2015 let v3 = loader_args(root, &profile, &ctx(LaunchMode::Modded)).unwrap();
2016
2017 assert_eq!(v3[0], "--doorstop-enable");
2018 assert_eq!(v3[1], "true");
2019 assert_eq!(v3[2], "--doorstop-target");
2020 assert!(v3[3].ends_with("UMM/Core/UnityModManager.dll"));
2021
2022 std::fs::write(root.join(".doorstop_version"), "4.0.0").unwrap();
2023
2024 let v4 = loader_args(root, &profile, &ctx(LaunchMode::Modded)).unwrap();
2025
2026 assert_eq!(v4[0], "--doorstop-enabled");
2027 assert_eq!(v4[2], "--doorstop-target-assembly");
2028 assert!(v4[3].ends_with("UMM/Core/UnityModManager.dll"));
2029
2030 let vanilla = loader_args(root, &profile, &ctx(LaunchMode::Vanilla)).unwrap();
2031
2032 assert_eq!(
2033 vanilla,
2034 vec!["--doorstop-enabled".to_string(), "false".to_string()]
2035 );
2036
2037 let mut server_profile = profile_with(LoaderKind::Umm);
2040 server_profile.instance_type = InstanceType::Server;
2041
2042 let server_args = loader_args(root, &server_profile, &ctx(LaunchMode::Modded)).unwrap();
2043
2044 assert!(!server_args.contains(&"--server".to_string()));
2045 }
2046
2047 #[test]
2048 fn bepis_loader_modded_and_vanilla_shapes() {
2049 let dir = tempfile::tempdir().unwrap();
2050 let root = dir.path();
2051 let core = root.join("BepInEx/core");
2052
2053 std::fs::create_dir_all(&core).unwrap();
2054 std::fs::write(core.join("BepInEx.Preloader.dll"), b"x").unwrap();
2055
2056 let profile = profile_with(LoaderKind::BepisLoader);
2057
2058 let modded = loader_args(root, &profile, &ctx(LaunchMode::Modded)).unwrap();
2059
2060 assert_eq!(modded[0], "--hookfxr-enable");
2061 assert_eq!(modded[1], "--bepinex-target");
2062 assert!(modded.contains(&"--doorstop-enabled".to_string()));
2063 assert!(modded.contains(&"--doorstop-target-assembly".to_string()));
2064
2065 let vanilla = loader_args(root, &profile, &ctx(LaunchMode::Vanilla)).unwrap();
2066
2067 assert_eq!(
2068 vanilla,
2069 vec![
2070 "--hookfxr-disable".to_string(),
2071 "--doorstop-enabled".to_string(),
2072 "false".to_string()
2073 ]
2074 );
2075 }
2076
2077 #[test]
2078 fn lovely_modded_and_vanilla_shapes() {
2079 let dir = tempfile::tempdir().unwrap();
2080 let root = dir.path();
2081
2082 let modded = loader_args(
2083 root,
2084 &profile_with(LoaderKind::Lovely),
2085 &ctx(LaunchMode::Modded),
2086 )
2087 .unwrap();
2088
2089 assert_eq!(modded[0], "--mod-dir");
2090 assert!(modded[1].ends_with("/mods"));
2091
2092 let vanilla = loader_args(
2093 root,
2094 &profile_with(LoaderKind::Lovely),
2095 &ctx(LaunchMode::Vanilla),
2096 )
2097 .unwrap();
2098
2099 assert_eq!(vanilla, vec!["--vanilla".to_string()]);
2100 }
2101
2102 #[test]
2103 fn godot_ml_modded_and_vanilla_shapes() {
2104 let dir = tempfile::tempdir().unwrap();
2105 let root = dir.path();
2106
2107 let modded = loader_args(
2108 root,
2109 &profile_with(LoaderKind::GodotMl),
2110 &ctx(LaunchMode::Modded),
2111 )
2112 .unwrap();
2113
2114 assert_eq!(modded[0], "--script");
2115 assert_eq!(modded[1], "res://addons/mod_loader/mod_loader_setup.gd");
2116 assert!(modded.contains(&"--mods-path".to_string()));
2117
2118 let vanilla = loader_args(
2119 root,
2120 &profile_with(LoaderKind::GodotMl),
2121 &ctx(LaunchMode::Vanilla),
2122 )
2123 .unwrap();
2124
2125 assert!(vanilla.is_empty());
2126 }
2127
2128 #[test]
2129 fn corlib_override_appends_search_flag_pair_matching_version() {
2130 let dir = tempfile::tempdir().unwrap();
2131 let root = dir.path();
2132 let core = root.join("BepInEx/core");
2133
2134 std::fs::create_dir_all(&core).unwrap();
2135 std::fs::write(core.join("BepInEx.Preloader.dll"), b"x").unwrap();
2136 std::fs::create_dir_all(root.join("unstripped_corlib")).unwrap();
2137
2138 let profile = profile_with(LoaderKind::BepInEx);
2139
2140 let v3 = loader_args(root, &profile, &ctx(LaunchMode::Modded)).unwrap();
2141 let v3_idx = v3
2142 .iter()
2143 .position(|a| a == "--doorstop-dll-search-override")
2144 .unwrap();
2145
2146 assert!(v3[v3_idx + 1].ends_with("/unstripped_corlib"));
2147
2148 std::fs::write(root.join(".doorstop_version"), "4.0.0").unwrap();
2149
2150 let v4 = loader_args(root, &profile, &ctx(LaunchMode::Modded)).unwrap();
2151 let v4_idx = v4
2152 .iter()
2153 .position(|a| a == "--doorstop-mono-dll-search-path-override")
2154 .unwrap();
2155
2156 assert!(v4[v4_idx + 1].ends_with("/unstripped_corlib"));
2157
2158 std::fs::remove_file(root.join(".doorstop_version")).unwrap();
2161
2162 let bepis = loader_args(
2163 root,
2164 &profile_with(LoaderKind::BepisLoader),
2165 &ctx(LaunchMode::Modded),
2166 )
2167 .unwrap();
2168 let bepis_idx = bepis
2169 .iter()
2170 .position(|a| a == "--doorstop-mono-dll-search-path-override")
2171 .unwrap();
2172
2173 assert!(bepis[bepis_idx + 1].ends_with("/unstripped_corlib"));
2174 }
2175
2176 #[test]
2177 fn windows_steam_plan_targets_steam_with_loader_args() {
2178 let dir = tempfile::tempdir().unwrap();
2179 let root = dir.path();
2180 let core = root.join("BepInEx/core");
2181
2182 std::fs::create_dir_all(&core).unwrap();
2183 std::fs::write(core.join("BepInEx.Preloader.dll"), b"x").unwrap();
2184
2185 let eco = Ecosystem::bundled();
2186 let mut context = ctx(LaunchMode::Modded);
2187 context.extra_args = vec!["-nolog".to_string()];
2188
2189 let plan = launch_plan_in(root, &eco, "valheim", &context).unwrap();
2190
2191 match &plan.program {
2192 LaunchProgram::Steam { steam_app_id } => assert_eq!(*steam_app_id, 892970),
2193 other => panic!("expected Steam, got {other:?}"),
2194 }
2195
2196 assert_eq!(plan.args[0], "--doorstop-enable");
2197 assert_eq!(plan.args.last().unwrap(), "-nolog");
2199 assert!(plan.env.is_empty());
2200 assert_eq!(plan.steam_wrapper, None);
2202 }
2203
2204 #[test]
2205 fn proton_sets_wine_dll_overrides_and_prefixes_the_preloader() {
2206 let dir = tempfile::tempdir().unwrap();
2207 let root = dir.path();
2208 let core = root.join("BepInEx/core");
2209
2210 std::fs::create_dir_all(&core).unwrap();
2211 std::fs::write(core.join("BepInEx.Preloader.dll"), b"x").unwrap();
2212
2213 let eco = Ecosystem::bundled();
2214 let mut context = ctx(LaunchMode::Modded);
2215 context.os = HostOs::Linux;
2216 context.runtime = Runtime::Proton;
2217
2218 let plan = launch_plan_in(root, &eco, "valheim", &context).unwrap();
2219
2220 assert_eq!(
2221 plan.env,
2222 vec![("WINEDLLOVERRIDES".to_string(), "winhttp=n,b".to_string())]
2223 );
2224 assert!(plan.args.iter().any(|a| a.starts_with("Z:")));
2225 assert_eq!(plan.steam_wrapper, None);
2227 }
2228
2229 #[test]
2230 fn linux_native_bepinex_runs_the_profile_script() {
2231 let dir = tempfile::tempdir().unwrap();
2232 let root = dir.path();
2233 let core = root.join("BepInEx/core");
2234
2235 std::fs::create_dir_all(&core).unwrap();
2236 std::fs::write(core.join("BepInEx.Preloader.dll"), b"x").unwrap();
2237 std::fs::write(root.join("run_bepinex.sh"), b"#!/bin/sh\n").unwrap();
2238
2239 let eco = Ecosystem::bundled();
2240 let mut context = ctx(LaunchMode::Modded);
2241 context.os = HostOs::Linux;
2242 context.store = StorePlatform::SteamDirect;
2243 context.runtime = Runtime::Native;
2244
2245 let plan = launch_plan_in(root, &eco, "valheim", &context).unwrap();
2246
2247 match &plan.program {
2248 LaunchProgram::ProfileScript { path, exe_names } => {
2251 assert!(path.ends_with("run_bepinex.sh"));
2252 assert_eq!(
2253 *exe_names,
2254 eco.game("valheim").unwrap().profile().unwrap().exe_names
2255 );
2256 assert!(!exe_names.is_empty());
2257 }
2258 other => panic!("expected ProfileScript, got {other:?}"),
2259 }
2260
2261 assert_eq!(plan.steam_wrapper, None);
2263 }
2264
2265 #[test]
2266 fn macos_is_rejected() {
2267 let dir = tempfile::tempdir().unwrap();
2268 let root = dir.path();
2269 let core = root.join("BepInEx/core");
2270
2271 std::fs::create_dir_all(&core).unwrap();
2272 std::fs::write(core.join("BepInEx.Preloader.dll"), b"x").unwrap();
2273
2274 let eco = Ecosystem::bundled();
2275 let mut context = ctx(LaunchMode::Modded);
2276 context.os = HostOs::MacOs;
2277
2278 let err = launch_plan_in(root, &eco, "valheim", &context).unwrap_err();
2279
2280 assert!(err.to_string().contains("macOS launch is not supported"));
2281
2282 context.os = HostOs::Windows;
2286
2287 assert!(launch_plan_in(root, &eco, "valheim", &context).is_ok());
2288 }
2289
2290 #[test]
2291 fn unknown_game_errors() {
2292 let dir = tempfile::tempdir().unwrap();
2293 let eco = Ecosystem::bundled();
2294
2295 let err = launch_plan_in(dir.path(), &eco, "not-a-game", &ctx(LaunchMode::Modded)).unwrap_err();
2296
2297 assert!(matches!(err, Error::UnknownGame { game } if game == "not-a-game"));
2298 }
2299
2300 #[test]
2301 fn proxy_dll_is_winmm_for_gdweave() {
2302 assert_eq!(proxy_dll(LoaderKind::GdWeave), "winmm");
2303 assert_eq!(proxy_dll(LoaderKind::BepInEx), "winhttp");
2304 }
2305
2306 #[test]
2307 fn wrapper_script_names_no_target_and_execs_the_loader() {
2308 let script = wrapper_script_contents();
2309
2310 assert!(script.starts_with("#!/bin/sh"));
2311
2312 assert!(script.contains(r#"TARGET="""#));
2316 assert!(script.contains(r#"[ -z "$TARGET" ]"#));
2317
2318 assert!(script.contains(&format!(r#"[ "$argument" = "{WRAPPER_TARGET_FLAG}" ]"#)));
2321 assert!(script.contains(r#"[ -d "$candidate" ]"#));
2322 assert!(!script.contains("eval"));
2323
2324 let pos_server = script
2326 .find("start_server_bepinex.sh")
2327 .expect("server branch missing");
2328 let pos_run = script.find("run_bepinex.sh").expect("run branch missing");
2329 let pos_game = script
2330 .find("start_game_bepinex.sh")
2331 .expect("game branch missing");
2332
2333 assert!(pos_server < pos_run, "server branch must come before run");
2334 assert!(pos_run < pos_game, "run branch must come before game");
2335
2336 assert!(script.contains("$TS_START_SERVER"));
2338
2339 assert!(script.contains("else"));
2341 assert!(script.contains("fi"));
2342
2343 assert!(script.contains("\"$@\""));
2345 }
2346
2347 #[test]
2348 fn write_wrapper_script_creates_an_executable_file() {
2349 let dir = tempfile::tempdir().unwrap();
2350 let root = dir.path();
2351 let script_path = root.join("launch_wrapper.sh");
2352
2353 write_wrapper_script(&script_path).unwrap();
2354
2355 assert!(script_path.is_file());
2356
2357 #[cfg(unix)]
2358 {
2359 use std::os::unix::fs::PermissionsExt;
2360
2361 let mode = std::fs::metadata(&script_path)
2362 .unwrap()
2363 .permissions()
2364 .mode();
2365
2366 assert_eq!(mode & 0o111, 0o111);
2367 }
2368 }
2369
2370 #[test]
2375 #[cfg(unix)]
2376 fn ensure_loader_scripts_executable_adds_the_bit_and_reports_what_changed() {
2377 use std::os::unix::fs::PermissionsExt;
2378
2379 let dir = tempfile::tempdir().unwrap();
2380 let root = dir.path();
2381
2382 let game = root.join("start_game_bepinex.sh");
2383 let server = root.join("start_server_bepinex.sh");
2384
2385 std::fs::write(&game, b"#!/bin/sh\n").unwrap();
2386 std::fs::write(&server, b"#!/bin/sh\n").unwrap();
2387
2388 std::fs::set_permissions(&game, std::fs::Permissions::from_mode(0o644)).unwrap();
2390 std::fs::set_permissions(&server, std::fs::Permissions::from_mode(0o644)).unwrap();
2391
2392 let changed = ensure_loader_scripts_executable(root).unwrap();
2393
2394 assert_eq!(changed.len(), 2, "got: {changed:?}");
2395
2396 for name in ["start_game_bepinex.sh", "start_server_bepinex.sh"] {
2397 let mode = std::fs::metadata(root.join(name))
2398 .unwrap()
2399 .permissions()
2400 .mode();
2401
2402 assert_eq!(mode & 0o777, 0o755, "{name} got mode {mode:o}");
2403 }
2404
2405 assert!(ensure_loader_scripts_executable(root).unwrap().is_empty());
2408 }
2409
2410 #[test]
2413 #[cfg(not(unix))]
2414 fn ensure_loader_scripts_executable_changes_nothing_off_unix() {
2415 let dir = tempfile::tempdir().unwrap();
2416 let root = dir.path();
2417
2418 std::fs::write(root.join("start_game_bepinex.sh"), b"#!/bin/sh\n").unwrap();
2419 std::fs::write(root.join("run_bepinex.sh"), b"#!/bin/sh\n").unwrap();
2420
2421 assert!(ensure_loader_scripts_executable(root).unwrap().is_empty());
2422 }
2423
2424 #[test]
2428 #[cfg(unix)]
2429 fn ensure_loader_scripts_executable_mirrors_read_access() {
2430 use std::os::unix::fs::PermissionsExt;
2431
2432 let dir = tempfile::tempdir().unwrap();
2433 let root = dir.path();
2434 let script = root.join("run_bepinex.sh");
2435
2436 std::fs::write(&script, b"#!/bin/sh\n").unwrap();
2437 std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o640)).unwrap();
2438
2439 ensure_loader_scripts_executable(root).unwrap();
2440
2441 let mode = std::fs::metadata(&script).unwrap().permissions().mode();
2442
2443 assert_eq!(mode & 0o777, 0o750, "got mode {mode:o}");
2444 }
2445
2446 #[test]
2449 fn ensure_loader_scripts_executable_ignores_a_target_with_no_scripts() {
2450 let dir = tempfile::tempdir().unwrap();
2451
2452 assert!(
2453 ensure_loader_scripts_executable(dir.path())
2454 .unwrap()
2455 .is_empty()
2456 );
2457 }
2458
2459 #[test]
2460 fn wrapper_target_args_name_the_flag_and_the_directory() {
2461 assert_eq!(
2462 wrapper_target_args(Path::new("/data/profiles/Main")),
2463 vec![
2464 WRAPPER_TARGET_FLAG.to_string(),
2465 "/data/profiles/Main".to_string()
2466 ]
2467 );
2468 }
2469
2470 #[cfg(unix)]
2481 fn make_executable(path: &Path) {
2482 use std::os::unix::fs::PermissionsExt;
2483
2484 std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755)).unwrap();
2485 }
2486
2487 #[cfg(unix)]
2494 fn recording_loader(path: &Path, log: &Path) {
2495 let contents = format!(
2496 "#!/bin/sh\nprintf '%s\\n' \"$0\" > \"{log}\"\nfor argument in \"$@\"; do\n printf '%s\\n' \"$argument\" >> \"{log}\"\ndone\n",
2497 log = log.display()
2498 );
2499
2500 std::fs::write(path, contents).unwrap();
2501 make_executable(path);
2502 }
2503
2504 #[cfg(unix)]
2507 fn recorded(log: &Path) -> Vec<String> {
2508 std::fs::read_to_string(log)
2509 .unwrap()
2510 .lines()
2511 .map(str::to_string)
2512 .collect()
2513 }
2514
2515 #[cfg(unix)]
2517 fn run_wrapper(wrapper: &Path, args: &[&str], server: bool) {
2518 let mut command = std::process::Command::new(wrapper);
2519
2520 command.args(args);
2521
2522 if server {
2523 command.env("TS_START_SERVER", "1");
2524 } else {
2525 command.env_remove("TS_START_SERVER");
2526 }
2527
2528 let output = command.output().unwrap();
2529
2530 assert!(
2531 output.status.success(),
2532 "wrapper failed: {}",
2533 String::from_utf8_lossy(&output.stderr)
2534 );
2535 }
2536
2537 #[cfg(unix)]
2538 #[test]
2539 fn wrapper_chainloads_the_target_given_at_run_time_and_consumes_only_the_flag() {
2540 let dir = tempfile::tempdir().unwrap();
2541 let fallback = dir.path().join("fallback");
2542 let selected = dir.path().join("My Profile 2");
2545 let log = dir.path().join("argv.log");
2546 let wrapper = dir.path().join("steam-wrapper.sh");
2547
2548 std::fs::create_dir_all(&fallback).unwrap();
2549 std::fs::create_dir_all(&selected).unwrap();
2550 recording_loader(&selected.join("run_bepinex.sh"), &log);
2551 write_wrapper_script(&wrapper).unwrap();
2552
2553 let target = selected.to_string_lossy().to_string();
2554
2555 run_wrapper(
2556 &wrapper,
2557 &[
2558 "/games/valheim/valheim.x86_64",
2559 "--doorstop-enabled",
2560 "true",
2561 WRAPPER_TARGET_FLAG,
2562 &target,
2563 "-name",
2564 "a server with spaces",
2565 ],
2566 false,
2567 );
2568
2569 let lines = recorded(&log);
2570
2571 assert_eq!(lines[0], selected.join("run_bepinex.sh").to_string_lossy());
2573 assert_eq!(
2576 &lines[1..],
2577 [
2578 "/games/valheim/valheim.x86_64",
2579 "--doorstop-enabled",
2580 "true",
2581 "-name",
2582 "a server with spaces",
2583 ]
2584 );
2585 }
2586
2587 #[cfg(unix)]
2588 #[test]
2589 fn wrapper_without_the_flag_launches_the_game_unmodded() {
2590 let dir = tempfile::tempdir().unwrap();
2591 let log = dir.path().join("argv.log");
2592 let wrapper = dir.path().join("steam-wrapper.sh");
2593 let game_exe = dir.path().join("valheim.x86_64");
2594 let unrequested = dir.path().join("profile");
2598 let unrequested_log = dir.path().join("must-not-run.log");
2599
2600 std::fs::create_dir_all(&unrequested).unwrap();
2601 recording_loader(&unrequested.join("run_bepinex.sh"), &unrequested_log);
2602 recording_loader(&game_exe, &log);
2603 write_wrapper_script(&wrapper).unwrap();
2604
2605 run_wrapper(&wrapper, &[&game_exe.to_string_lossy()], false);
2608
2609 assert!(
2610 !unrequested_log.exists(),
2611 "a bare launch must not load any profile's mods"
2612 );
2613
2614 let lines = recorded(&log);
2615
2616 assert_eq!(lines[0], game_exe.to_string_lossy());
2617 assert_eq!(lines.len(), 1, "the game got extra arguments: {lines:?}");
2618 }
2619
2620 #[cfg(unix)]
2621 #[test]
2622 fn wrapper_launches_unmodded_when_the_flags_value_is_not_a_directory() {
2623 let dir = tempfile::tempdir().unwrap();
2624 let log = dir.path().join("argv.log");
2625 let wrapper = dir.path().join("steam-wrapper.sh");
2626 let game_exe = dir.path().join("valheim.x86_64");
2627
2628 recording_loader(&game_exe, &log);
2629 write_wrapper_script(&wrapper).unwrap();
2630
2631 let missing = dir.path().join("deleted-profile");
2634
2635 run_wrapper(
2636 &wrapper,
2637 &[
2638 &game_exe.to_string_lossy(),
2639 WRAPPER_TARGET_FLAG,
2640 &missing.to_string_lossy(),
2641 ],
2642 false,
2643 );
2644
2645 let lines = recorded(&log);
2646
2647 assert_eq!(lines[0], game_exe.to_string_lossy());
2650 assert_eq!(lines.len(), 1, "the game got extra arguments: {lines:?}");
2651 }
2652
2653 #[cfg(unix)]
2654 #[test]
2655 fn wrapper_consumes_a_trailing_flag_that_has_no_value() {
2656 let dir = tempfile::tempdir().unwrap();
2657 let log = dir.path().join("argv.log");
2658 let wrapper = dir.path().join("steam-wrapper.sh");
2659 let game_exe = dir.path().join("valheim.x86_64");
2660
2661 recording_loader(&game_exe, &log);
2662 write_wrapper_script(&wrapper).unwrap();
2663
2664 run_wrapper(
2665 &wrapper,
2666 &[&game_exe.to_string_lossy(), WRAPPER_TARGET_FLAG],
2667 false,
2668 );
2669
2670 let lines = recorded(&log);
2671
2672 assert_eq!(lines[0], game_exe.to_string_lossy());
2675 assert_eq!(lines.len(), 1, "the game got extra arguments: {lines:?}");
2676 }
2677
2678 #[cfg(unix)]
2679 #[test]
2680 fn wrapper_execs_the_game_directly_when_the_target_ships_no_loader_script() {
2681 let dir = tempfile::tempdir().unwrap();
2682 let selected = dir.path().join("profile");
2683 let log = dir.path().join("argv.log");
2684 let wrapper = dir.path().join("steam-wrapper.sh");
2685 let game_exe = dir.path().join("valheim.x86_64");
2687
2688 std::fs::create_dir_all(&selected).unwrap();
2689 recording_loader(&game_exe, &log);
2690 write_wrapper_script(&wrapper).unwrap();
2691
2692 run_wrapper(
2693 &wrapper,
2694 &[
2695 &game_exe.to_string_lossy(),
2696 WRAPPER_TARGET_FLAG,
2697 &selected.to_string_lossy(),
2698 "-window-mode",
2699 ],
2700 false,
2701 );
2702
2703 let lines = recorded(&log);
2704
2705 assert_eq!(lines[0], game_exe.to_string_lossy());
2708 assert_eq!(&lines[1..], ["-window-mode"]);
2709 }
2710
2711 #[cfg(unix)]
2712 #[test]
2713 fn wrapper_selects_the_server_script_only_when_ts_start_server_is_set() {
2714 let dir = tempfile::tempdir().unwrap();
2715 let target = dir.path().join("target");
2716 let server_log = dir.path().join("server.log");
2717 let game_log = dir.path().join("game.log");
2718 let wrapper = dir.path().join("steam-wrapper.sh");
2719
2720 std::fs::create_dir_all(&target).unwrap();
2721 recording_loader(&target.join(SERVER_SCRIPT), &server_log);
2725 recording_loader(&target.join("run_bepinex.sh"), &game_log);
2726 write_wrapper_script(&wrapper).unwrap();
2727
2728 let selected = target.to_string_lossy().to_string();
2729 let argv = [
2730 "/games/valheim/valheim.x86_64",
2731 WRAPPER_TARGET_FLAG,
2732 &selected,
2733 ];
2734
2735 run_wrapper(&wrapper, &argv, false);
2736
2737 assert!(
2738 !server_log.exists(),
2739 "the server script must not run for a game instance"
2740 );
2741 assert_eq!(
2742 recorded(&game_log)[0],
2743 target.join("run_bepinex.sh").to_string_lossy()
2744 );
2745
2746 run_wrapper(&wrapper, &argv, true);
2747
2748 assert_eq!(
2749 recorded(&server_log)[0],
2750 target.join(SERVER_SCRIPT).to_string_lossy()
2751 );
2752 }
2753
2754 #[test]
2755 fn steam_launch_options_are_only_the_wrapper_and_command_placeholder() {
2756 let options = steam_launch_options(Path::new("/data/launch_wrapper.sh"));
2757
2758 assert_eq!(options, r#""/data/launch_wrapper.sh" %command%"#);
2761
2762 assert!(!options.contains("WINEDLLOVERRIDES"));
2766 assert!(!options.contains("winhttp"));
2767
2768 assert_eq!(
2770 steam_launch_options(Path::new("/data/My Games/wrapper.sh")),
2771 r#""/data/My Games/wrapper.sh" %command%"#
2772 );
2773
2774 assert_eq!(
2776 steam_launch_options(Path::new(r"C:\Users\me\launch_wrapper.sh")),
2777 r#""C:/Users/me/launch_wrapper.sh" %command%"#
2778 );
2779 }
2780
2781 #[test]
2782 fn stage_destination_routes_per_loader() {
2783 let game = Path::new("/game");
2784
2785 assert_eq!(
2786 stage_destination(LoaderKind::BepInEx, "winhttp.dll", game, None),
2787 Some(PathBuf::from("/game/winhttp.dll"))
2788 );
2789 assert_eq!(
2791 stage_destination(LoaderKind::BepInEx, "mods.yml", game, None),
2792 None
2793 );
2794
2795 assert_eq!(
2797 stage_destination(LoaderKind::Shimloader, "ue4ss.dll", game, Some("Palworld")),
2798 Some(PathBuf::from("/game/Palworld/Binaries/Win64/ue4ss.dll"))
2799 );
2800 assert_eq!(
2801 stage_destination(LoaderKind::Shimloader, "other.dll", game, Some("Palworld")),
2802 None
2803 );
2804 assert_eq!(
2806 stage_destination(LoaderKind::Shimloader, "ue4ss.dll", game, None),
2807 None
2808 );
2809
2810 assert_eq!(
2812 stage_destination(LoaderKind::Rivet, "version.dll", game, None),
2813 Some(PathBuf::from("/game/Release/version.dll"))
2814 );
2815 assert_eq!(
2816 stage_destination(LoaderKind::Rivet, "winhttp.dll", game, None),
2817 None
2818 );
2819 }
2820
2821 #[test]
2822 fn stage_for_launch_copies_root_files_only() {
2823 let dir = tempfile::tempdir().unwrap();
2824 let target = dir.path().join("target");
2825 let game_dir = dir.path().join("game");
2826
2827 std::fs::create_dir_all(target.join("BepInEx/core")).unwrap();
2828 std::fs::create_dir_all(&game_dir).unwrap();
2829 std::fs::write(target.join("winhttp.dll"), b"proxy").unwrap();
2830 std::fs::write(target.join("doorstop_config.ini"), b"[UnityDoorstop]").unwrap();
2831 std::fs::write(target.join("mods.yml"), b"[]").unwrap();
2832 std::fs::write(target.join("BepInEx/core/BepInEx.Preloader.dll"), b"x").unwrap();
2833
2834 let eco = Ecosystem::bundled();
2835 let written = stage_for_launch_in(
2836 &target,
2837 &eco,
2838 "valheim",
2839 &game_dir,
2840 &ctx(LaunchMode::Modded),
2841 )
2842 .unwrap();
2843
2844 assert!(game_dir.join("winhttp.dll").exists());
2845 assert!(game_dir.join("doorstop_config.ini").exists());
2846 assert!(!game_dir.join("mods.yml").exists());
2848 assert!(!game_dir.join("BepInEx").exists());
2849 assert_eq!(written.len(), 2);
2850
2851 assert!(written.contains(&game_dir.join("winhttp.dll")));
2853 assert!(written.contains(&game_dir.join("doorstop_config.ini")));
2854
2855 let mut sorted = written.clone();
2856 sorted.sort();
2857
2858 assert_eq!(written, sorted);
2859 }
2860
2861 #[test]
2862 fn stage_for_launch_stages_shimloader_files_into_nested_binaries_dir() {
2863 let dir = tempfile::tempdir().unwrap();
2867 let target = dir.path().join("target");
2868 let game_dir = dir.path().join("game");
2869
2870 std::fs::create_dir_all(&target).unwrap();
2871 std::fs::create_dir_all(&game_dir).unwrap();
2872 std::fs::write(target.join("ue4ss.dll"), b"loader").unwrap();
2873 std::fs::write(target.join("dwmapi.dll"), b"proxy").unwrap();
2874 std::fs::write(target.join("ue4ss-settings.ini"), b"[UE4SS]").unwrap();
2875 std::fs::write(target.join("other.dll"), b"unrelated").unwrap();
2876
2877 let eco = Ecosystem::bundled();
2878 let written = stage_for_launch_in(
2879 &target,
2880 &eco,
2881 "palworld",
2882 &game_dir,
2883 &ctx(LaunchMode::Modded),
2884 )
2885 .unwrap();
2886
2887 let nested = game_dir.join("Pal").join("Binaries").join("Win64");
2888
2889 assert_eq!(std::fs::read(nested.join("ue4ss.dll")).unwrap(), b"loader");
2890 assert!(nested.join("dwmapi.dll").exists());
2891 assert!(nested.join("ue4ss-settings.ini").exists());
2892 assert!(!game_dir.join("other.dll").exists());
2894 assert!(!nested.join("other.dll").exists());
2895
2896 assert_eq!(written.len(), 3);
2897 assert!(written.contains(&nested.join("ue4ss.dll")));
2898 assert!(written.contains(&nested.join("dwmapi.dll")));
2899 assert!(written.contains(&nested.join("ue4ss-settings.ini")));
2900
2901 let mut sorted = written.clone();
2902 sorted.sort();
2903
2904 assert_eq!(written, sorted);
2905 }
2906
2907 #[test]
2908 fn stage_for_launch_stages_rivet_version_dll_into_release_dir() {
2909 let dir = tempfile::tempdir().unwrap();
2913 let target = dir.path().join("target");
2914 let game_dir = dir.path().join("game");
2915
2916 std::fs::create_dir_all(&target).unwrap();
2917 std::fs::create_dir_all(&game_dir).unwrap();
2918 std::fs::write(target.join("version.dll"), b"rivet-loader").unwrap();
2919 std::fs::write(target.join("other.dll"), b"unrelated").unwrap();
2920
2921 let eco = Ecosystem::bundled();
2922 let written = stage_for_launch_in(
2923 &target,
2924 &eco,
2925 "scrap-mechanic",
2926 &game_dir,
2927 &ctx(LaunchMode::Modded),
2928 )
2929 .unwrap();
2930
2931 let dest = game_dir.join("Release").join("version.dll");
2932
2933 assert_eq!(std::fs::read(&dest).unwrap(), b"rivet-loader");
2934 assert!(!game_dir.join("other.dll").exists());
2936 assert!(!game_dir.join("Release").join("other.dll").exists());
2937
2938 assert_eq!(written, vec![dest]);
2939 }
2940
2941 #[test]
2942 fn stage_for_launch_skips_linux_native_bepinex() {
2943 let dir = tempfile::tempdir().unwrap();
2944 let target = dir.path().join("target");
2945 let game_dir = dir.path().join("game");
2946
2947 std::fs::create_dir_all(&target).unwrap();
2948 std::fs::create_dir_all(&game_dir).unwrap();
2949 std::fs::write(target.join("winhttp.dll"), b"proxy").unwrap();
2950
2951 let eco = Ecosystem::bundled();
2952 let mut context = ctx(LaunchMode::Modded);
2953 context.os = HostOs::Linux;
2954 context.runtime = Runtime::Native;
2955
2956 let written = stage_for_launch_in(&target, &eco, "valheim", &game_dir, &context).unwrap();
2957
2958 assert!(written.is_empty());
2959 assert!(!game_dir.join("winhttp.dll").exists());
2960 }
2961
2962 #[cfg(unix)]
2963 #[test]
2964 fn stage_for_launch_refuses_to_write_through_a_symlink() {
2965 use std::os::unix::fs::symlink;
2966
2967 let dir = tempfile::tempdir().unwrap();
2968 let target = dir.path().join("target");
2969 let game_dir = dir.path().join("game");
2970 let outside = dir.path().join("secret.dll");
2971
2972 std::fs::create_dir_all(&target).unwrap();
2973 std::fs::create_dir_all(&game_dir).unwrap();
2974 std::fs::write(&outside, b"original").unwrap();
2975 std::fs::write(target.join("winhttp.dll"), b"proxy").unwrap();
2976 symlink(&outside, game_dir.join("winhttp.dll")).unwrap();
2977
2978 let eco = Ecosystem::bundled();
2979
2980 assert!(
2981 stage_for_launch_in(
2982 &target,
2983 &eco,
2984 "valheim",
2985 &game_dir,
2986 &ctx(LaunchMode::Modded)
2987 )
2988 .is_err()
2989 );
2990 assert_eq!(std::fs::read(&outside).unwrap(), b"original");
2991 }
2992
2993 #[test]
2994 fn stage_for_launch_in_place_leaves_root_files_byte_for_byte_untouched() {
2995 let dir = tempfile::tempdir().unwrap();
3002 let root = dir.path().join("game");
3003
3004 std::fs::create_dir_all(root.join("BepInEx/core")).unwrap();
3005
3006 let winhttp_contents = b"MZ-fake-proxy-dll-18b";
3007 let ini_contents = b"[UnityDoorstop]\nenabled=true\n";
3008
3009 std::fs::write(root.join("winhttp.dll"), winhttp_contents).unwrap();
3010 std::fs::write(root.join("doorstop_config.ini"), ini_contents).unwrap();
3011 std::fs::write(root.join("mods.yml"), b"[]").unwrap();
3012 std::fs::write(root.join("BepInEx/core/BepInEx.Preloader.dll"), b"x").unwrap();
3013
3014 let eco = Ecosystem::bundled();
3015 let written =
3016 stage_for_launch_in(&root, &eco, "valheim", &root, &ctx(LaunchMode::Modded)).unwrap();
3017
3018 assert_eq!(
3021 std::fs::read(root.join("winhttp.dll")).unwrap(),
3022 winhttp_contents
3023 );
3024 assert_eq!(
3025 std::fs::read(root.join("doorstop_config.ini")).unwrap(),
3026 ini_contents
3027 );
3028
3029 assert!(written.is_empty());
3035 }
3036
3037 #[test]
3038 fn stage_for_launch_in_place_survives_a_dot_dot_aliased_game_dir() {
3039 let dir = tempfile::tempdir().unwrap();
3044 let target = dir.path().join("target");
3045
3046 std::fs::create_dir_all(target.join("BepInEx/core")).unwrap();
3047
3048 let contents = b"proxy-bytes-not-truncated";
3049
3050 std::fs::write(target.join("winhttp.dll"), contents).unwrap();
3051
3052 let aliased_game_dir = target.join("BepInEx").join("..");
3053 let eco = Ecosystem::bundled();
3054
3055 let written = stage_for_launch_in(
3056 &target,
3057 &eco,
3058 "valheim",
3059 &aliased_game_dir,
3060 &ctx(LaunchMode::Modded),
3061 )
3062 .unwrap();
3063
3064 assert_eq!(std::fs::read(target.join("winhttp.dll")).unwrap(), contents);
3065 assert!(written.is_empty());
3066 }
3067
3068 #[cfg(unix)]
3069 #[test]
3070 fn stage_for_launch_in_place_survives_a_symlinked_game_dir() {
3071 use std::os::unix::fs::symlink;
3072
3073 let dir = tempfile::tempdir().unwrap();
3077 let target = dir.path().join("target");
3078 let link = dir.path().join("game-link");
3079
3080 std::fs::create_dir_all(target.join("BepInEx/core")).unwrap();
3081
3082 let contents = b"proxy-bytes-via-symlink";
3083
3084 std::fs::write(target.join("winhttp.dll"), contents).unwrap();
3085 symlink(&target, &link).unwrap();
3086
3087 let eco = Ecosystem::bundled();
3088 let written =
3089 stage_for_launch_in(&target, &eco, "valheim", &link, &ctx(LaunchMode::Modded)).unwrap();
3090
3091 assert_eq!(std::fs::read(target.join("winhttp.dll")).unwrap(), contents);
3092 assert!(written.is_empty());
3093 }
3094
3095 #[test]
3096 fn stage_for_launch_in_place_still_copies_shimloader_files_to_a_distinct_destination() {
3097 let dir = tempfile::tempdir().unwrap();
3103 let root = dir.path().join("game");
3104
3105 std::fs::create_dir_all(&root).unwrap();
3106 std::fs::write(root.join("ue4ss.dll"), b"loader").unwrap();
3107 std::fs::write(root.join("dwmapi.dll"), b"proxy").unwrap();
3108 std::fs::write(root.join("ue4ss-settings.ini"), b"[UE4SS]").unwrap();
3109
3110 let eco = Ecosystem::bundled();
3111 let written =
3112 stage_for_launch_in(&root, &eco, "palworld", &root, &ctx(LaunchMode::Modded)).unwrap();
3113
3114 let nested = root.join("Pal").join("Binaries").join("Win64");
3115
3116 assert_eq!(std::fs::read(nested.join("ue4ss.dll")).unwrap(), b"loader");
3117 assert_eq!(std::fs::read(nested.join("dwmapi.dll")).unwrap(), b"proxy");
3118 assert_eq!(std::fs::read(root.join("ue4ss.dll")).unwrap(), b"loader");
3121
3122 assert_eq!(written.len(), 3);
3123 assert!(written.contains(&nested.join("ue4ss.dll")));
3124 assert!(written.contains(&nested.join("dwmapi.dll")));
3125 assert!(written.contains(&nested.join("ue4ss-settings.ini")));
3126 }
3127
3128 #[test]
3129 fn stage_for_launch_in_place_still_copies_rivet_version_dll_to_a_distinct_destination() {
3130 let dir = tempfile::tempdir().unwrap();
3134 let root = dir.path().join("game");
3135
3136 std::fs::create_dir_all(&root).unwrap();
3137 std::fs::write(root.join("version.dll"), b"rivet-loader").unwrap();
3138
3139 let eco = Ecosystem::bundled();
3140 let written = stage_for_launch_in(
3141 &root,
3142 &eco,
3143 "scrap-mechanic",
3144 &root,
3145 &ctx(LaunchMode::Modded),
3146 )
3147 .unwrap();
3148
3149 let dest = root.join("Release").join("version.dll");
3150
3151 assert_eq!(std::fs::read(&dest).unwrap(), b"rivet-loader");
3152 assert_eq!(
3153 std::fs::read(root.join("version.dll")).unwrap(),
3154 b"rivet-loader"
3155 );
3156 assert_eq!(written, vec![dest]);
3157 }
3158
3159 #[test]
3160 fn stage_for_launch_wraps_stage_for_launch_in_over_a_layout_profile() {
3161 let dir = tempfile::tempdir().unwrap();
3162 let base = dir.path().join("base");
3163 let game_dir = dir.path().join("game");
3164
3165 let profile_dir = crate::profile::layout::create(&base, "valheim", "Main").unwrap();
3166 let core = profile_dir.join("BepInEx/core");
3167
3168 std::fs::create_dir_all(&core).unwrap();
3169 std::fs::create_dir_all(&game_dir).unwrap();
3170 std::fs::write(core.join("BepInEx.Preloader.dll"), b"x").unwrap();
3171 std::fs::write(profile_dir.join("winhttp.dll"), b"proxy").unwrap();
3172 std::fs::write(profile_dir.join("mods.yml"), b"[]").unwrap();
3173
3174 let eco = Ecosystem::bundled();
3175 let written = stage_for_launch(
3176 &base,
3177 "valheim",
3178 "Main",
3179 &eco,
3180 &game_dir,
3181 &ctx(LaunchMode::Modded),
3182 )
3183 .unwrap();
3184
3185 assert!(game_dir.join("winhttp.dll").exists());
3186 assert!(!game_dir.join("mods.yml").exists());
3187 assert_eq!(written, vec![game_dir.join("winhttp.dll")]);
3188 }
3189
3190 fn linux_native(mode: LaunchMode) -> LaunchContext {
3192 let mut context = ctx(mode);
3193
3194 context.os = HostOs::Linux;
3195 context.store = StorePlatform::SteamDirect;
3196 context.runtime = Runtime::Native;
3197
3198 context
3199 }
3200
3201 fn linux_bepinex_target(root: &Path) {
3204 let core = root.join("BepInEx/core");
3205
3206 std::fs::create_dir_all(&core).unwrap();
3207 std::fs::write(core.join("BepInEx.Preloader.dll"), b"x").unwrap();
3208 std::fs::write(root.join("winhttp.dll"), b"proxy").unwrap();
3209 std::fs::write(root.join("doorstop_config.ini"), b"[UnityDoorstop]").unwrap();
3210 }
3211
3212 #[test]
3213 fn linux_native_modded_selects_any_shipped_script_not_only_run_bepinex() {
3214 let dir = tempfile::tempdir().unwrap();
3215 let target = dir.path().join("target");
3216 let game_dir = dir.path().join("game");
3217
3218 linux_bepinex_target(&target);
3219 std::fs::create_dir_all(&game_dir).unwrap();
3220 std::fs::write(target.join("start_game_bepinex.sh"), b"#!/bin/sh\n").unwrap();
3222
3223 let eco = Ecosystem::bundled();
3224 let context = linux_native(LaunchMode::Modded);
3225
3226 let plan = launch_plan_in(&target, &eco, "valheim", &context).unwrap();
3227
3228 match &plan.program {
3229 LaunchProgram::ProfileScript { path, .. } => {
3230 assert!(path.ends_with("start_game_bepinex.sh"))
3231 }
3232 other => panic!("expected ProfileScript, got {other:?}"),
3235 }
3236
3237 let written = stage_for_launch_in(&target, &eco, "valheim", &game_dir, &context).unwrap();
3239
3240 assert!(written.is_empty());
3241 assert!(!game_dir.join("winhttp.dll").exists());
3242 }
3243
3244 #[test]
3245 fn server_instance_prefers_the_server_script_and_a_game_instance_ignores_it() {
3246 let dir = tempfile::tempdir().unwrap();
3247 let all_three = dir.path().join("all-three");
3248 let server_only = dir.path().join("server-only");
3249
3250 linux_bepinex_target(&all_three);
3251 linux_bepinex_target(&server_only);
3252
3253 for name in LOADER_SCRIPTS {
3254 std::fs::write(all_three.join(name), b"#!/bin/sh\n").unwrap();
3255 }
3256
3257 std::fs::write(server_only.join(SERVER_SCRIPT), b"#!/bin/sh\n").unwrap();
3258
3259 let context = linux_native(LaunchMode::Modded);
3260 let game_profile = profile_with(LoaderKind::BepInEx);
3261 let mut server_profile = profile_with(LoaderKind::BepInEx);
3262
3263 server_profile.instance_type = InstanceType::Server;
3264
3265 let server = resolve_program(
3266 &script_injection(
3267 &all_three,
3268 &LaunchFacts::read(&all_three),
3269 &server_profile,
3270 &context,
3271 ),
3272 &all_three,
3273 &server_profile,
3274 &context,
3275 )
3276 .unwrap();
3277
3278 match &server {
3279 LaunchProgram::ProfileScript { path, .. } => {
3280 assert!(path.ends_with("start_server_bepinex.sh"))
3281 }
3282 other => panic!("expected ProfileScript, got {other:?}"),
3283 }
3284
3285 let game = resolve_program(
3288 &script_injection(
3289 &all_three,
3290 &LaunchFacts::read(&all_three),
3291 &game_profile,
3292 &context,
3293 ),
3294 &all_three,
3295 &game_profile,
3296 &context,
3297 )
3298 .unwrap();
3299
3300 match &game {
3301 LaunchProgram::ProfileScript { path, .. } => assert!(path.ends_with("run_bepinex.sh")),
3302 other => panic!("expected ProfileScript, got {other:?}"),
3303 }
3304
3305 let err = resolve_program(
3307 &script_injection(
3308 &server_only,
3309 &LaunchFacts::read(&server_only),
3310 &game_profile,
3311 &context,
3312 ),
3313 &server_only,
3314 &game_profile,
3315 &context,
3316 )
3317 .unwrap_err();
3318
3319 assert!(err.to_string().contains("run_bepinex.sh"));
3320 }
3321
3322 #[test]
3323 fn modded_script_injection_without_a_script_errors_but_vanilla_falls_through() {
3324 let dir = tempfile::tempdir().unwrap();
3325 let target = dir.path().join("target");
3326
3327 linux_bepinex_target(&target);
3328
3329 let eco = Ecosystem::bundled();
3330 let modded = linux_native(LaunchMode::Modded);
3331
3332 let err = launch_plan_in(&target, &eco, "valheim", &modded).unwrap_err();
3333 let message = err.to_string();
3334
3335 assert!(message.contains("run_bepinex.sh"), "{message}");
3336 assert!(message.contains("start_game_bepinex.sh"), "{message}");
3337 assert!(message.contains(&target.display().to_string()), "{message}");
3338
3339 let vanilla =
3342 launch_plan_in(&target, &eco, "valheim", &linux_native(LaunchMode::Vanilla)).unwrap();
3343
3344 assert!(matches!(vanilla.program, LaunchProgram::GameExe { .. }));
3345 assert_eq!(
3346 vanilla.args,
3347 vec!["--doorstop-enable".to_string(), "false".to_string()]
3348 );
3349 }
3350
3351 #[test]
3352 fn linux_native_steam_launches_steam_and_reports_the_wrapper_requirement() {
3353 let dir = tempfile::tempdir().unwrap();
3354 let target = dir.path().join("target");
3355 let game_dir = dir.path().join("game");
3356 let script_path = dir.path().join("launch_wrapper.sh");
3357
3358 linux_bepinex_target(&target);
3359 std::fs::create_dir_all(&game_dir).unwrap();
3360 std::fs::write(target.join("run_bepinex.sh"), b"#!/bin/sh\n").unwrap();
3361
3362 let eco = Ecosystem::bundled();
3363 let mut context = linux_native(LaunchMode::Modded);
3364
3365 context.store = StorePlatform::Steam;
3366
3367 let plan = launch_plan_in(&target, &eco, "valheim", &context).unwrap();
3368
3369 match &plan.program {
3371 LaunchProgram::Steam { steam_app_id } => assert_eq!(*steam_app_id, 892970),
3372 other => panic!("expected Steam, got {other:?}"),
3373 }
3374
3375 let wrapper = plan.steam_wrapper.clone().expect("wrapper requirement");
3379
3380 assert_eq!(wrapper.target_dir, target);
3381 assert_eq!(wrapper.loader, LoaderKind::BepInEx);
3382
3383 write_wrapper_script(&script_path).unwrap();
3384
3385 let options = steam_launch_options(&script_path);
3386
3387 assert_options_name_script(&options, &script_path);
3388 assert!(!options.contains("WINEDLLOVERRIDES"));
3389 assert!(
3390 std::fs::read_to_string(&script_path)
3391 .unwrap()
3392 .contains("run_bepinex.sh")
3393 );
3394
3395 assert!(
3398 plan
3399 .args
3400 .windows(2)
3401 .any(|pair| pair == wrapper_target_args(&target).as_slice()),
3402 "plan args must carry the wrapper target flag: {:?}",
3403 plan.args
3404 );
3405
3406 let written = stage_for_launch_in(&target, &eco, "valheim", &game_dir, &context).unwrap();
3408
3409 assert!(written.is_empty());
3410 assert!(!game_dir.join("winhttp.dll").exists());
3411 }
3412
3413 #[test]
3414 fn stage_for_launch_rejects_macos() {
3415 let dir = tempfile::tempdir().unwrap();
3416 let target = dir.path().join("target");
3417 let game_dir = dir.path().join("game");
3418
3419 linux_bepinex_target(&target);
3420 std::fs::create_dir_all(&game_dir).unwrap();
3421
3422 let eco = Ecosystem::bundled();
3423 let mut context = ctx(LaunchMode::Modded);
3424
3425 context.os = HostOs::MacOs;
3426
3427 let err = stage_for_launch_in(&target, &eco, "valheim", &game_dir, &context).unwrap_err();
3428
3429 assert!(err.to_string().contains("macOS launch is not supported"));
3430 assert_eq!(std::fs::read_dir(&game_dir).unwrap().count(), 0);
3433
3434 context.os = HostOs::Windows;
3437
3438 let written = stage_for_launch_in(&target, &eco, "valheim", &game_dir, &context).unwrap();
3439
3440 assert_eq!(written.len(), 2);
3441 assert!(game_dir.join("winhttp.dll").exists());
3442 }
3443
3444 #[test]
3445 fn only_a_wrapper_bound_plan_carries_the_target_flag() {
3446 let dir = tempfile::tempdir().unwrap();
3447 let target = dir.path().join("target");
3448
3449 linux_bepinex_target(&target);
3450 std::fs::write(target.join("run_bepinex.sh"), b"#!/bin/sh\n").unwrap();
3451
3452 let eco = Ecosystem::bundled();
3453
3454 let direct =
3458 launch_plan_in(&target, &eco, "valheim", &linux_native(LaunchMode::Modded)).unwrap();
3459
3460 assert_eq!(direct.steam_wrapper, None);
3461 assert!(!direct.args.contains(&WRAPPER_TARGET_FLAG.to_string()));
3462
3463 let mut proton = linux_native(LaunchMode::Modded);
3466
3467 proton.store = StorePlatform::Steam;
3468 proton.runtime = Runtime::Proton;
3469
3470 let proton_plan = launch_plan_in(&target, &eco, "valheim", &proton).unwrap();
3471
3472 assert_eq!(proton_plan.steam_wrapper, None);
3473 assert!(!proton_plan.args.contains(&WRAPPER_TARGET_FLAG.to_string()));
3474 }
3475
3476 #[test]
3477 fn wrapper_branches_are_generated_from_the_shared_script_list() {
3478 let script = wrapper_script_contents();
3479
3480 let mut previous = 0;
3481
3482 for name in LOADER_SCRIPTS {
3483 let position = script
3484 .find(&format!("[ -f \"$TARGET/{name}\" ]"))
3485 .unwrap_or_else(|| panic!("wrapper is missing a branch for {name}"));
3486
3487 assert!(position >= previous, "{name} is out of precedence order");
3488
3489 previous = position;
3490 }
3491 }
3492
3493 #[test]
3498 fn linux_native_script_present_vanilla_runs_the_script_with_v4_enabled_spelling() {
3499 let dir = tempfile::tempdir().unwrap();
3500 let target = dir.path().join("target");
3501
3502 linux_bepinex_target(&target);
3503 std::fs::write(target.join("run_bepinex.sh"), b"#!/bin/sh\n").unwrap();
3504 let eco = Ecosystem::bundled();
3508 let plan =
3509 launch_plan_in(&target, &eco, "valheim", &linux_native(LaunchMode::Vanilla)).unwrap();
3510
3511 match &plan.program {
3514 LaunchProgram::ProfileScript { path, .. } => assert!(path.ends_with("run_bepinex.sh")),
3515 other => panic!("expected ProfileScript, got {other:?}"),
3516 }
3517
3518 assert_eq!(
3519 plan.args,
3520 vec!["--doorstop-enabled".to_string(), "false".to_string()]
3521 );
3522 }
3523
3524 #[test]
3525 fn linux_native_script_present_modded_uses_v4_target_assembly_spelling() {
3526 let dir = tempfile::tempdir().unwrap();
3527 let target = dir.path().join("target");
3528
3529 linux_bepinex_target(&target);
3530 std::fs::write(target.join("run_bepinex.sh"), b"#!/bin/sh\n").unwrap();
3531 let eco = Ecosystem::bundled();
3535 let plan = launch_plan_in(&target, &eco, "valheim", &linux_native(LaunchMode::Modded)).unwrap();
3536
3537 assert!(matches!(plan.program, LaunchProgram::ProfileScript { .. }));
3538 assert_eq!(plan.args[0], "--doorstop-enabled");
3539 assert_eq!(plan.args[1], "true");
3540 assert_eq!(plan.args[2], "--doorstop-target-assembly");
3541 assert!(plan.args[3].ends_with("BepInEx/core/BepInEx.Preloader.dll"));
3542 }
3543
3544 #[test]
3545 fn linux_native_script_present_v3_detected_corlib_override_uses_v4_search_flag_spelling() {
3546 let dir = tempfile::tempdir().unwrap();
3552 let target = dir.path().join("target");
3553
3554 linux_bepinex_target(&target);
3555 std::fs::write(target.join("run_bepinex.sh"), b"#!/bin/sh\n").unwrap();
3556 std::fs::create_dir_all(target.join("unstripped_corlib")).unwrap();
3557 let eco = Ecosystem::bundled();
3561 let plan = launch_plan_in(&target, &eco, "valheim", &linux_native(LaunchMode::Modded)).unwrap();
3562
3563 assert!(matches!(plan.program, LaunchProgram::ProfileScript { .. }));
3564
3565 let idx = plan
3566 .args
3567 .iter()
3568 .position(|a| a == "--doorstop-mono-dll-search-path-override")
3569 .expect("v4 corlib search-path flag missing");
3570
3571 assert!(plan.args[idx + 1].ends_with("/unstripped_corlib"));
3572 assert!(
3573 !plan
3574 .args
3575 .iter()
3576 .any(|a| a == "--doorstop-dll-search-override"),
3577 "v3 corlib search-path spelling must not appear on the script-injected path: {:?}",
3578 plan.args
3579 );
3580 }
3581
3582 #[test]
3583 fn linux_native_script_present_v4_detected_target_is_unchanged() {
3584 let dir = tempfile::tempdir().unwrap();
3585 let target = dir.path().join("target");
3586
3587 linux_bepinex_target(&target);
3588 std::fs::write(target.join("run_bepinex.sh"), b"#!/bin/sh\n").unwrap();
3589 std::fs::write(target.join(".doorstop_version"), "4.0.0").unwrap();
3590
3591 let eco = Ecosystem::bundled();
3592
3593 let vanilla =
3594 launch_plan_in(&target, &eco, "valheim", &linux_native(LaunchMode::Vanilla)).unwrap();
3595
3596 assert_eq!(
3597 vanilla.args,
3598 vec!["--doorstop-enabled".to_string(), "false".to_string()]
3599 );
3600
3601 let modded =
3602 launch_plan_in(&target, &eco, "valheim", &linux_native(LaunchMode::Modded)).unwrap();
3603
3604 assert_eq!(modded.args[0], "--doorstop-enabled");
3605 assert_eq!(modded.args[2], "--doorstop-target-assembly");
3606 }
3607
3608 #[test]
3609 fn proton_v3_detected_target_still_uses_v3_spellings_even_with_a_script_on_disk() {
3610 let dir = tempfile::tempdir().unwrap();
3619 let target = dir.path().join("target");
3620
3621 linux_bepinex_target(&target);
3622 std::fs::write(target.join("run_bepinex.sh"), b"#!/bin/sh\n").unwrap();
3623
3624 let eco = Ecosystem::bundled();
3625 let mut context = linux_native(LaunchMode::Modded);
3626
3627 context.runtime = Runtime::Proton;
3628
3629 let plan = launch_plan_in(&target, &eco, "valheim", &context).unwrap();
3630
3631 assert_eq!(plan.args[0], "--doorstop-enable");
3632 assert_eq!(plan.args[2], "--doorstop-target");
3633
3634 let mut vanilla_context = linux_native(LaunchMode::Vanilla);
3635
3636 vanilla_context.runtime = Runtime::Proton;
3637
3638 let vanilla = launch_plan_in(&target, &eco, "valheim", &vanilla_context).unwrap();
3639
3640 assert_eq!(
3641 vanilla.args,
3642 vec!["--doorstop-enable".to_string(), "false".to_string()]
3643 );
3644 }
3645
3646 #[test]
3647 fn windows_v3_detected_target_still_uses_v3_spellings_regression_guard() {
3648 let dir = tempfile::tempdir().unwrap();
3652 let root = dir.path();
3653 let core = root.join("BepInEx/core");
3654
3655 std::fs::create_dir_all(&core).unwrap();
3656 std::fs::write(core.join("BepInEx.Preloader.dll"), b"x").unwrap();
3657
3658 let eco = Ecosystem::bundled();
3659 let plan = launch_plan_in(root, &eco, "valheim", &ctx(LaunchMode::Modded)).unwrap();
3660
3661 assert_eq!(plan.args[0], "--doorstop-enable");
3662 assert_eq!(plan.args[2], "--doorstop-target");
3663
3664 let vanilla = launch_plan_in(root, &eco, "valheim", &ctx(LaunchMode::Vanilla)).unwrap();
3665
3666 assert_eq!(
3667 vanilla.args,
3668 vec!["--doorstop-enable".to_string(), "false".to_string()]
3669 );
3670 }
3671
3672 #[test]
3673 fn store_and_runtime_parse_from_their_config_spellings() {
3674 assert_eq!(
3675 "steam".parse::<StorePlatform>().unwrap(),
3676 StorePlatform::Steam
3677 );
3678 assert_eq!(
3679 "steam-direct".parse::<StorePlatform>().unwrap(),
3680 StorePlatform::SteamDirect
3681 );
3682 assert_eq!(
3683 "other".parse::<StorePlatform>().unwrap(),
3684 StorePlatform::Other
3685 );
3686 assert_eq!("native".parse::<Runtime>().unwrap(), Runtime::Native);
3687 assert_eq!("proton".parse::<Runtime>().unwrap(), Runtime::Proton);
3688
3689 let error = "wat".parse::<StorePlatform>().unwrap_err().to_string();
3691
3692 assert!(error.contains("wat"), "got: {error}");
3693 }
3694
3695 #[test]
3696 fn resolve_game_exe_returns_the_first_present_candidate() {
3697 let dir = tempfile::tempdir().unwrap();
3698 let game_dir = dir.path();
3699
3700 std::fs::write(game_dir.join("second.x86_64"), b"elf").unwrap();
3701
3702 let names = vec!["first.exe".to_string(), "second.x86_64".to_string()];
3703 let found = resolve_game_exe(game_dir, &names).unwrap();
3704
3705 assert_eq!(found, game_dir.join("second.x86_64"));
3706
3707 let error = resolve_game_exe(game_dir, &["absent.exe".to_string()])
3709 .unwrap_err()
3710 .to_string();
3711
3712 assert!(error.contains("absent.exe"), "got: {error}");
3713 }
3714
3715 #[test]
3716 fn a_plan_becomes_a_spawnable_command() {
3717 let dir = tempfile::tempdir().unwrap();
3718 let game_dir = dir.path();
3719
3720 std::fs::write(game_dir.join("valheim.x86_64"), b"elf").unwrap();
3721
3722 let plan = LaunchPlan {
3726 program: LaunchProgram::GameExe {
3727 exe_names: vec!["valheim.x86_64".to_string()],
3728 },
3729 args: vec!["-console".to_string()],
3730 env: vec![("KEY".to_string(), "VALUE".to_string())],
3731 working_dir: Some(game_dir.to_path_buf()),
3732 steam_wrapper: None,
3733 };
3734
3735 let command = plan.to_command(game_dir).unwrap();
3736
3737 assert_eq!(command.get_program(), game_dir.join("valheim.x86_64"));
3738 assert_eq!(
3739 command.get_args().collect::<Vec<_>>(),
3740 vec![std::ffi::OsStr::new("-console")]
3741 );
3742 assert_eq!(command.get_current_dir(), Some(game_dir));
3743 assert!(
3744 command
3745 .get_envs()
3746 .any(|(key, value)| key == std::ffi::OsStr::new("KEY")
3747 && value == Some(std::ffi::OsStr::new("VALUE")))
3748 );
3749 }
3750
3751 #[test]
3755 fn a_steam_command_leads_with_applaunch_and_keeps_the_plan_argv_after_it() {
3756 let program = Path::new(r"C:\Program Files (x86)\Steam\steam.exe");
3757 let mut command = steam_command(program, 892970);
3758
3759 command.args(["-console".to_string(), "--ts-target".to_string()]);
3760
3761 assert_eq!(command.get_program(), program.as_os_str());
3762 assert_eq!(
3763 command.get_args().collect::<Vec<_>>(),
3764 vec![
3765 std::ffi::OsStr::new("-applaunch"),
3766 std::ffi::OsStr::new("892970"),
3767 std::ffi::OsStr::new("-console"),
3768 std::ffi::OsStr::new("--ts-target"),
3769 ]
3770 );
3771 }
3772
3773 #[test]
3781 fn a_steam_plan_spawns_the_resolved_steam_executable() {
3782 let dir = tempfile::tempdir().unwrap();
3783 let game_dir = dir.path();
3784
3785 let plan = LaunchPlan {
3786 program: LaunchProgram::Steam {
3787 steam_app_id: 892970,
3788 },
3789 args: vec!["-console".to_string()],
3790 env: vec![("KEY".to_string(), "VALUE".to_string())],
3791 working_dir: None,
3792 steam_wrapper: None,
3793 };
3794
3795 let command = plan.to_command(game_dir).unwrap();
3796
3797 assert_eq!(
3798 command.get_program(),
3799 crate::steam::steam_exe().as_os_str(),
3800 "the Steam arm must use the resolved executable"
3801 );
3802 assert_eq!(
3803 command.get_args().collect::<Vec<_>>(),
3804 vec![
3805 std::ffi::OsStr::new("-applaunch"),
3806 std::ffi::OsStr::new("892970"),
3807 std::ffi::OsStr::new("-console"),
3808 ]
3809 );
3810
3811 let envs = command.get_envs().collect::<Vec<_>>();
3812
3813 assert_eq!(
3814 envs,
3815 vec![(
3816 std::ffi::OsStr::new("KEY"),
3817 Some(std::ffi::OsStr::new("VALUE"))
3818 )],
3819 "the plan's env must reach the command unchanged, with nothing added"
3820 );
3821 }
3822}
3823
3824#[cfg(test)]
3825mod planning_tests {
3826 use super::*;
3827
3828 const TARGET: &str = "/profiles/main";
3829
3830 fn ctx(os: HostOs, store: StorePlatform, runtime: Runtime, mode: LaunchMode) -> LaunchContext {
3831 LaunchContext::new(os, store, runtime, mode)
3832 }
3833
3834 fn with_preloader() -> LaunchFacts {
3835 LaunchFacts {
3836 preloader: Some("BepInEx.Preloader.dll".to_string()),
3837 ..LaunchFacts::default()
3838 }
3839 }
3840
3841 fn plan(facts: &LaunchFacts, context: &LaunchContext) -> Result<LaunchPlan> {
3842 launch_plan_from(
3843 Path::new(TARGET),
3844 facts,
3845 &Ecosystem::bundled(),
3846 "valheim",
3847 context,
3848 )
3849 }
3850
3851 #[test]
3852 fn doorstop_flags_follow_the_recorded_version() {
3853 let windows = ctx(
3854 HostOs::Windows,
3855 StorePlatform::SteamDirect,
3856 Runtime::Native,
3857 LaunchMode::Modded,
3858 );
3859 let mut facts = with_preloader();
3860
3861 let v3 = plan(&facts, &windows).unwrap();
3862
3863 facts.doorstop_version = 4;
3864
3865 let v4 = plan(&facts, &windows).unwrap();
3866
3867 assert_eq!(v3.args[0], "--doorstop-enable");
3868 assert_eq!(v4.args[0], "--doorstop-enabled");
3869 assert!(
3870 v3.args
3871 .contains(&format!("{TARGET}/BepInEx/core/BepInEx.Preloader.dll"))
3872 );
3873 }
3874
3875 #[test]
3876 fn a_modded_bepinex_launch_needs_a_preloader() {
3877 let windows = ctx(
3878 HostOs::Windows,
3879 StorePlatform::SteamDirect,
3880 Runtime::Native,
3881 LaunchMode::Modded,
3882 );
3883
3884 let result = plan(&LaunchFacts::default(), &windows);
3885
3886 assert!(
3887 matches!(result, Err(Error::Profile(message)) if message.contains("no BepInEx preloader"))
3888 );
3889 }
3890
3891 #[test]
3892 fn corlibs_add_the_search_path_override() {
3893 let windows = ctx(
3894 HostOs::Windows,
3895 StorePlatform::SteamDirect,
3896 Runtime::Native,
3897 LaunchMode::Modded,
3898 );
3899 let mut facts = with_preloader();
3900
3901 facts.has_corlibs = true;
3902
3903 let plan = plan(&facts, &windows).unwrap();
3904
3905 assert!(
3906 plan
3907 .args
3908 .contains(&"--doorstop-dll-search-override".to_string())
3909 );
3910 assert!(plan.args.contains(&format!("{TARGET}/unstripped_corlib")));
3911 }
3912
3913 #[test]
3914 fn a_listed_loader_script_is_run_on_linux_native() {
3915 let linux = ctx(
3916 HostOs::Linux,
3917 StorePlatform::SteamDirect,
3918 Runtime::Native,
3919 LaunchMode::Modded,
3920 );
3921 let mut facts = with_preloader();
3922
3923 facts.loader_scripts = vec!["start_game_bepinex.sh".to_string()];
3924
3925 let plan = plan(&facts, &linux).unwrap();
3926
3927 assert!(matches!(
3928 plan.program,
3929 LaunchProgram::ProfileScript { ref path, .. }
3930 if path == &Path::new(TARGET).join("start_game_bepinex.sh")
3931 ));
3932 assert_eq!(plan.args[0], "--doorstop-enabled");
3933 }
3934
3935 #[test]
3936 fn linux_native_modded_without_a_loader_script_is_refused() {
3937 let linux = ctx(
3938 HostOs::Linux,
3939 StorePlatform::SteamDirect,
3940 Runtime::Native,
3941 LaunchMode::Modded,
3942 );
3943
3944 let result = plan(&with_preloader(), &linux);
3945
3946 assert!(matches!(result, Err(Error::Profile(message)) if message.contains("loader script")));
3947 }
3948
3949 #[test]
3950 fn the_server_script_is_ignored_for_a_game_instance() {
3951 let linux = ctx(
3952 HostOs::Linux,
3953 StorePlatform::SteamDirect,
3954 Runtime::Native,
3955 LaunchMode::Modded,
3956 );
3957 let mut facts = with_preloader();
3958
3959 facts.loader_scripts = vec!["start_server_bepinex.sh".to_string()];
3960
3961 assert!(plan(&facts, &linux).is_err());
3962 }
3963
3964 #[test]
3965 fn melonloader_regenerates_only_without_its_assemblies() {
3966 let eco = Ecosystem::bundled();
3967 let profile = eco
3968 .games()
3969 .filter_map(|game| game.profile())
3970 .find(|profile| profile.package_loader == LoaderKind::MelonLoader)
3971 .unwrap();
3972 let windows = ctx(
3973 HostOs::Windows,
3974 StorePlatform::SteamDirect,
3975 Runtime::Native,
3976 LaunchMode::Modded,
3977 );
3978 let mut facts = LaunchFacts::default();
3979
3980 let bare = loader_args_from(Path::new(TARGET), &facts, profile, &windows).unwrap();
3981
3982 facts.melonloader_assemblies = true;
3983
3984 let built = loader_args_from(Path::new(TARGET), &facts, profile, &windows).unwrap();
3985
3986 assert!(bare.contains(&"--melonloader.agfregenerate".to_string()));
3987 assert!(!built.contains(&"--melonloader.agfregenerate".to_string()));
3988 }
3989
3990 #[test]
3991 fn macos_is_refused_whatever_the_facts() {
3992 let mac = ctx(
3993 HostOs::MacOs,
3994 StorePlatform::SteamDirect,
3995 Runtime::Native,
3996 LaunchMode::Modded,
3997 );
3998
3999 assert!(plan(&with_preloader(), &mac).is_err());
4000 }
4001
4002 #[test]
4003 #[cfg(feature = "io")]
4004 fn launch_facts_read_what_the_target_holds() {
4005 let dir = tempfile::tempdir().unwrap();
4006 let root = dir.path();
4007
4008 std::fs::create_dir_all(root.join("BepInEx/core")).unwrap();
4009 std::fs::create_dir_all(root.join("unstripped_corlib")).unwrap();
4010 std::fs::create_dir_all(root.join("MelonLoader/Il2CppAssemblies")).unwrap();
4011 std::fs::write(root.join("BepInEx/core/BepInEx.Preloader.dll"), b"").unwrap();
4012 std::fs::write(root.join("run_bepinex.sh"), b"").unwrap();
4013 std::fs::write(root.join(".doorstop_version"), b"4.0.0").unwrap();
4014 std::fs::write(
4015 root.join("MelonLoader/Il2CppAssemblies/Assembly-CSharp.dll"),
4016 b"",
4017 )
4018 .unwrap();
4019
4020 let facts = LaunchFacts::read(root);
4021
4022 assert_eq!(facts.doorstop_version, 4);
4023 assert_eq!(facts.preloader.as_deref(), Some("BepInEx.Preloader.dll"));
4024 assert!(facts.has_corlibs);
4025 assert_eq!(facts.loader_scripts, vec!["run_bepinex.sh".to_string()]);
4026 assert!(facts.melonloader_assemblies);
4027 assert_eq!(
4028 LaunchFacts::read(&root.join("missing")),
4029 LaunchFacts::default()
4030 );
4031 }
4032
4033 #[test]
4034 #[cfg(feature = "io")]
4035 fn launch_facts_read_the_loader_files_and_recorded_packages() {
4036 let dir = tempfile::tempdir().unwrap();
4037 let root = dir.path();
4038 let version: crate::models::Version = serde_json::from_str(
4039 r#"{"name":"GDWeave","full_name":"NotNet-GDWeave","description":"d","icon":"i",
4040 "version_number":"2.0.0","dependencies":[],"download_url":"u","downloads":1,
4041 "date_created":"2024-01-01T12:00:00Z","website_url":"w","is_active":true,
4042 "uuid4":"u","file_size":1}"#,
4043 )
4044 .unwrap();
4045
4046 std::fs::create_dir_all(root.join("GDWeave/core")).unwrap();
4047 std::fs::write(root.join("GDWeave/core/GDWeave.dll"), b"").unwrap();
4048 std::fs::create_dir_all(root.join("R2Northstar")).unwrap();
4049 std::fs::write(root.join("R2Northstar/Northstar.dll"), b"").unwrap();
4050 crate::profile::modlist::write(
4051 root,
4052 &[crate::profile::mod_entry_from_version(
4053 "NotNet-GDWeave",
4054 "NotNet",
4055 &version,
4056 1,
4057 )],
4058 )
4059 .unwrap();
4060
4061 let facts = LaunchFacts::read(root);
4062
4063 assert_eq!(
4064 facts.loaders,
4065 vec![LoaderKind::GdWeave, LoaderKind::Northstar]
4066 );
4067 assert_eq!(facts.recorded, vec!["NotNet-GDWeave".to_string()]);
4068 }
4069}