1use super::{
5 HostOs, LOADER_FILES, LaunchContext, LaunchFacts, LaunchMode, LaunchPlan, launch_plan_from,
6};
7#[cfg(feature = "io")]
8use super::{
9 StagedFiles, ensure_loader_scripts_executable, stage_files_in, wrapper_path, write_wrapper_script,
10};
11use crate::ecosystem::{Ecosystem, LoaderKind};
12use crate::error::{Error, Result};
13#[cfg(feature = "io")]
14use crate::profile::target::InstallTarget;
15use std::path::{Path, PathBuf};
16
17#[derive(Debug, Clone, PartialEq, Eq)]
19#[non_exhaustive]
20pub enum LaunchNotice {
21 SteamWrapper {
25 script: PathBuf,
27 launch_options: String,
29 },
30 ProtonDllOverride {
35 dll: String,
37 launch_options: String,
39 },
40 MadeExecutable {
42 path: PathBuf,
44 },
45}
46
47#[cfg(feature = "io")]
49#[derive(Debug)]
50#[non_exhaustive]
51pub struct PreparedLaunch {
52 pub command: std::process::Command,
54 pub plan: LaunchPlan,
56 pub staged: Vec<PathBuf>,
59 pub replaced: Vec<PathBuf>,
63 pub notices: Vec<LaunchNotice>,
65}
66
67pub fn prepare_plan_from(
112 target_dir: &Path,
113 facts: &LaunchFacts,
114 eco: &Ecosystem,
115 game: &str,
116 ctx: &LaunchContext,
117) -> Result<LaunchPlan> {
118 if ctx.mode == LaunchMode::Modded && ctx.os != HostOs::MacOs {
119 let loader = eco.require_profile(game)?.package_loader;
120
121 if !loader_installed(facts, eco, loader) {
122 return Err(Error::NoModLoader { loader });
123 }
124 }
125
126 launch_plan_from(target_dir, facts, eco, game, ctx)
127}
128
129#[cfg(feature = "io")]
152pub fn prepare_launch(
153 target: &InstallTarget,
154 eco: &Ecosystem,
155 ctx: &LaunchContext,
156) -> Result<PreparedLaunch> {
157 if !target.game_dir.is_dir() {
158 return Err(Error::MissingGameDir {
159 path: target.game_dir.clone(),
160 });
161 }
162
163 let facts = LaunchFacts::read(&target.dir);
164 let plan = prepare_plan_from(&target.dir, &facts, eco, &target.game, ctx)?;
165 let command = plan.to_command(&target.game_dir)?;
166 let mut notices = Vec::new();
167
168 let script = wrapper_path(&target.base, &target.game);
169
170 if let Some(launch_options) = plan.steam_launch_options(&script) {
171 if plan.steam_wrapper.is_some() {
172 write_wrapper_script(&script)?;
173 notices.push(LaunchNotice::SteamWrapper {
174 launch_options,
175 script,
176 });
177 } else if let Some(dll) = plan.steam_dll_override() {
178 notices.push(LaunchNotice::ProtonDllOverride {
179 dll: dll.to_string(),
180 launch_options,
181 });
182 }
183 }
184
185 for path in ensure_loader_scripts_executable(&target.dir)? {
186 notices.push(LaunchNotice::MadeExecutable { path });
187 }
188
189 let staged = match ctx.mode {
190 LaunchMode::Modded => stage_files_in(&target.dir, eco, &target.game, &target.game_dir, ctx)?,
191 LaunchMode::Vanilla => StagedFiles::default(),
192 };
193
194 Ok(PreparedLaunch {
195 command,
196 plan,
197 staged: staged.created,
198 replaced: staged.replaced,
199 notices,
200 })
201}
202
203fn loader_installed(facts: &LaunchFacts, eco: &Ecosystem, loader: LoaderKind) -> bool {
208 match loader {
209 LoaderKind::None | LoaderKind::Other => true,
210 LoaderKind::BepInEx | LoaderKind::BepisLoader => facts.preloader.is_some(),
211 _ if LOADER_FILES.iter().any(|(kind, _)| *kind == loader) => facts.loaders.contains(&loader),
212 _ => {
213 facts.loaders.contains(&loader)
214 || facts.recorded.iter().any(|name| {
215 eco
216 .modloader_package(name)
217 .is_some_and(|pack| pack.loader == loader)
218 })
219 }
220 }
221}
222
223#[cfg(test)]
224mod tests {
225 use super::*;
226 use crate::ecosystem::{LoaderKind, ModloaderPackage};
227 use crate::error::Error;
228 use crate::profile::launch::{HostOs, LaunchMode, Runtime, StorePlatform};
229
230 const TARGET: &str = "/profiles/main";
231
232 const LOADERS: [LoaderKind; 12] = [
234 LoaderKind::BepInEx,
235 LoaderKind::BepisLoader,
236 LoaderKind::GdWeave,
237 LoaderKind::GodotMl,
238 LoaderKind::Lovely,
239 LoaderKind::MelonLoader,
240 LoaderKind::RecursiveMelonLoader,
241 LoaderKind::Northstar,
242 LoaderKind::ReturnOfModding,
243 LoaderKind::Rivet,
244 LoaderKind::Shimloader,
245 LoaderKind::Umm,
246 ];
247
248 fn windows(mode: LaunchMode) -> LaunchContext {
249 LaunchContext::new(
250 HostOs::Windows,
251 StorePlatform::SteamDirect,
252 Runtime::Native,
253 mode,
254 )
255 }
256
257 fn valheim_with(loader: LoaderKind) -> Ecosystem {
259 let mut eco = Ecosystem::bundled();
260
261 for profile in &mut eco.games.get_mut("valheim").unwrap().profiles {
262 profile.package_loader = loader;
263 }
264
265 eco
266 }
267
268 fn prepare(facts: &LaunchFacts, eco: &Ecosystem, mode: LaunchMode) -> Result<LaunchPlan> {
269 prepare_plan_from(Path::new(TARGET), facts, eco, "valheim", &windows(mode))
270 }
271
272 #[test]
273 fn a_modded_launch_with_no_loader_names_the_missing_loader_for_every_kind() {
274 for kind in LOADERS {
275 let err = prepare(
276 &LaunchFacts::default(),
277 &valheim_with(kind),
278 LaunchMode::Modded,
279 )
280 .unwrap_err();
281
282 assert!(
283 matches!(err, Error::NoModLoader { loader } if loader == kind),
284 "{kind:?}: {err:?}"
285 );
286 }
287 }
288
289 #[test]
290 fn a_loader_found_in_the_target_satisfies_a_modded_launch() {
291 for kind in LOADERS {
292 let mut facts = LaunchFacts::default();
293
294 match kind {
295 LoaderKind::BepInEx | LoaderKind::BepisLoader => {
296 facts.preloader = Some("BepInEx.Preloader.dll".to_string());
297 }
298 _ => facts.loaders = vec![kind],
299 }
300
301 let plan = prepare(&facts, &valheim_with(kind), LaunchMode::Modded);
302
303 assert!(plan.is_ok(), "{kind:?}: {plan:?}");
304 }
305 }
306
307 #[test]
308 fn a_recorded_pack_stands_in_only_for_a_loader_whose_files_are_unknown() {
309 for kind in [LoaderKind::BepInEx, LoaderKind::Umm, LoaderKind::Shimloader] {
310 let mut eco = valheim_with(kind);
311 let mut facts = LaunchFacts::default();
312
313 eco.modloader_packages = vec![ModloaderPackage {
314 package_id: "Someone-Loader".to_string(),
315 root_folder: String::new(),
316 loader: kind,
317 }];
318 facts.recorded = vec!["Someone-Loader".to_string()];
319
320 let deleted = prepare(&facts, &eco, LaunchMode::Modded);
321
322 assert!(
323 matches!(deleted, Err(Error::NoModLoader { .. })),
324 "{kind:?}: {deleted:?}"
325 );
326 }
327 }
328
329 #[test]
330 fn a_recorded_loader_pack_of_the_games_kind_satisfies_a_modded_launch() {
331 for kind in [
332 LoaderKind::GodotMl,
333 LoaderKind::Lovely,
334 LoaderKind::ReturnOfModding,
335 ] {
336 let mut eco = valheim_with(kind);
337 let mut facts = LaunchFacts::default();
338
339 eco.modloader_packages = vec![
340 ModloaderPackage {
341 package_id: "Someone-RightLoader".to_string(),
342 root_folder: String::new(),
343 loader: kind,
344 },
345 ModloaderPackage {
346 package_id: "Someone-WrongLoader".to_string(),
347 root_folder: String::new(),
348 loader: LoaderKind::Other,
349 },
350 ];
351 facts.recorded = vec!["Someone-WrongLoader".to_string()];
352
353 let wrong = prepare(&facts, &eco, LaunchMode::Modded);
354
355 facts.recorded.push("Someone-RightLoader".to_string());
356
357 let right = prepare(&facts, &eco, LaunchMode::Modded);
358
359 assert!(
360 matches!(wrong, Err(Error::NoModLoader { .. })),
361 "{kind:?}: {wrong:?}"
362 );
363 assert!(
364 !matches!(right, Err(Error::NoModLoader { .. })),
365 "{kind:?}: {right:?}"
366 );
367 }
368 }
369
370 #[test]
371 fn a_vanilla_launch_needs_no_loader() {
372 for kind in LOADERS {
373 let plan = prepare(
374 &LaunchFacts::default(),
375 &valheim_with(kind),
376 LaunchMode::Vanilla,
377 );
378
379 assert!(plan.is_ok(), "{kind:?}: {plan:?}");
380 }
381 }
382
383 #[test]
384 fn a_game_without_a_known_loader_launches_modded_with_none_installed() {
385 for kind in [LoaderKind::None, LoaderKind::Other] {
386 let plan = prepare(
387 &LaunchFacts::default(),
388 &valheim_with(kind),
389 LaunchMode::Modded,
390 );
391
392 assert!(plan.is_ok(), "{kind:?}: {plan:?}");
393 }
394 }
395
396 #[test]
397 fn macos_is_refused_before_the_loader_is_checked() {
398 let mac = LaunchContext::new(
399 HostOs::MacOs,
400 StorePlatform::SteamDirect,
401 Runtime::Native,
402 LaunchMode::Modded,
403 );
404
405 let err = prepare_plan_from(
406 Path::new(TARGET),
407 &LaunchFacts::default(),
408 &Ecosystem::bundled(),
409 "valheim",
410 &mac,
411 )
412 .unwrap_err();
413
414 assert!(err.to_string().contains("macOS launch is not supported"));
415 }
416}
417
418#[cfg(all(test, feature = "io"))]
419mod io_tests {
420 use super::*;
421 use crate::profile::launch::tests::assert_options_name_script;
422 use crate::profile::launch::{Runtime, StorePlatform};
423 use crate::profile::layout;
424 use crate::profile::target::InstallTarget;
425 use std::path::PathBuf;
426 use tempfile::TempDir;
427
428 struct Fixture {
430 _dir: TempDir,
431 base: PathBuf,
432 game_dir: PathBuf,
433 profile_dir: PathBuf,
434 }
435
436 impl Fixture {
437 fn new() -> Self {
438 let dir = tempfile::tempdir().unwrap();
439 let base = dir.path().join("base");
440 let game_dir = dir.path().join("game");
441 let profile_dir = layout::create(&base, "valheim", "Main").unwrap();
442 let exe = Ecosystem::bundled()
443 .require_profile("valheim")
444 .unwrap()
445 .exe_names[0]
446 .clone();
447
448 std::fs::create_dir_all(profile_dir.join("BepInEx/core")).unwrap();
449 std::fs::write(profile_dir.join("BepInEx/core/BepInEx.Preloader.dll"), b"x").unwrap();
450 std::fs::write(profile_dir.join("winhttp.dll"), b"proxy").unwrap();
451 std::fs::create_dir_all(&game_dir).unwrap();
452 std::fs::write(game_dir.join(exe), b"game").unwrap();
453
454 Self {
455 _dir: dir,
456 base,
457 game_dir,
458 profile_dir,
459 }
460 }
461
462 fn target(&self) -> InstallTarget {
463 InstallTarget::resolve(
464 self.base.clone(),
465 self.game_dir.clone(),
466 "valheim",
467 Some("Main"),
468 )
469 .unwrap()
470 }
471 }
472
473 fn context(os: HostOs, store: StorePlatform, mode: LaunchMode) -> LaunchContext {
474 LaunchContext::new(os, store, Runtime::Native, mode)
475 }
476
477 #[test]
478 fn a_missing_game_folder_is_refused() {
479 let fixture = Fixture::new();
480 let target = fixture.target();
481
482 std::fs::remove_dir_all(&fixture.game_dir).unwrap();
483
484 let err = prepare_launch(
485 &target,
486 &Ecosystem::bundled(),
487 &context(
488 HostOs::Windows,
489 StorePlatform::SteamDirect,
490 LaunchMode::Modded,
491 ),
492 )
493 .unwrap_err();
494
495 assert!(
496 matches!(&err, Error::MissingGameDir { path } if *path == fixture.game_dir),
497 "{err:?}"
498 );
499 }
500
501 #[test]
502 fn a_windows_launch_stages_the_proxy_and_returns_the_game_command() {
503 let fixture = Fixture::new();
504 let exe = Ecosystem::bundled()
505 .require_profile("valheim")
506 .unwrap()
507 .exe_names[0]
508 .clone();
509
510 let prepared = prepare_launch(
511 &fixture.target(),
512 &Ecosystem::bundled(),
513 &context(
514 HostOs::Windows,
515 StorePlatform::SteamDirect,
516 LaunchMode::Modded,
517 ),
518 )
519 .unwrap();
520 let args: Vec<_> = prepared.command.get_args().collect();
521
522 assert_eq!(prepared.command.get_program(), fixture.game_dir.join(exe));
523 assert_eq!(args[0], "--doorstop-enable");
524 assert_eq!(prepared.staged, vec![fixture.game_dir.join("winhttp.dll")]);
525 assert_eq!(
526 std::fs::read(fixture.game_dir.join("winhttp.dll")).unwrap(),
527 b"proxy"
528 );
529 assert!(prepared.notices.is_empty());
530 }
531
532 #[test]
533 #[cfg(unix)]
534 fn a_linux_native_launch_makes_the_loader_script_executable_and_runs_it() {
535 use std::os::unix::fs::PermissionsExt;
536
537 let fixture = Fixture::new();
538 let script = fixture.profile_dir.join("start_game_bepinex.sh");
539
540 std::fs::write(&script, b"#!/bin/sh\n").unwrap();
541 std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o644)).unwrap();
542
543 let prepared = prepare_launch(
544 &fixture.target(),
545 &Ecosystem::bundled(),
546 &context(
547 HostOs::Linux,
548 StorePlatform::SteamDirect,
549 LaunchMode::Modded,
550 ),
551 )
552 .unwrap();
553 let mode = std::fs::metadata(&script).unwrap().permissions().mode();
554
555 assert_eq!(prepared.command.get_program(), script);
556 assert_eq!(mode & 0o777, 0o755);
557 assert_eq!(
558 prepared.notices,
559 vec![LaunchNotice::MadeExecutable {
560 path: script.clone()
561 }]
562 );
563 assert!(prepared.staged.is_empty());
564 assert!(!fixture.game_dir.join("winhttp.dll").exists());
565 }
566
567 #[test]
568 fn a_linux_native_steam_launch_writes_the_wrapper_and_gives_the_line_to_paste() {
569 let fixture = Fixture::new();
570
571 std::fs::write(fixture.profile_dir.join("run_bepinex.sh"), b"#!/bin/sh\n").unwrap();
572
573 let prepared = prepare_launch(
574 &fixture.target(),
575 &Ecosystem::bundled(),
576 &context(HostOs::Linux, StorePlatform::Steam, LaunchMode::Modded),
577 )
578 .unwrap();
579 let script = fixture.base.join("valheim").join("steam-wrapper.sh");
580
581 match &prepared.notices[0] {
582 LaunchNotice::SteamWrapper {
583 script: written,
584 launch_options,
585 } => {
586 assert_eq!(written, &script);
587 assert_options_name_script(launch_options, &script);
588 }
589 other => panic!("expected the Steam wrapper notice, got {other:?}"),
590 }
591
592 assert!(script.is_file());
593 assert!(prepared.command.get_args().any(|arg| arg == "-applaunch"));
594 }
595
596 #[test]
597 fn a_profile_with_no_loader_is_refused_before_the_game_folder_is_touched() {
598 let fixture = Fixture::new();
599
600 std::fs::remove_dir_all(fixture.profile_dir.join("BepInEx")).unwrap();
601
602 let err = prepare_launch(
603 &fixture.target(),
604 &Ecosystem::bundled(),
605 &context(
606 HostOs::Windows,
607 StorePlatform::SteamDirect,
608 LaunchMode::Modded,
609 ),
610 )
611 .unwrap_err();
612
613 assert!(
614 matches!(
615 err,
616 Error::NoModLoader {
617 loader: LoaderKind::BepInEx
618 }
619 ),
620 "{err:?}"
621 );
622 assert!(!fixture.game_dir.join("winhttp.dll").exists());
623 }
624
625 #[test]
626 fn a_missing_game_executable_is_refused_before_the_game_folder_is_touched() {
627 let fixture = Fixture::new();
628 let exe = Ecosystem::bundled()
629 .require_profile("valheim")
630 .unwrap()
631 .exe_names[0]
632 .clone();
633
634 std::fs::remove_file(fixture.game_dir.join(exe)).unwrap();
635
636 let result = prepare_launch(
637 &fixture.target(),
638 &Ecosystem::bundled(),
639 &context(
640 HostOs::Windows,
641 StorePlatform::SteamDirect,
642 LaunchMode::Modded,
643 ),
644 );
645
646 assert!(result.is_err());
647 assert!(!fixture.game_dir.join("winhttp.dll").exists());
648 }
649
650 #[test]
651 fn a_launch_from_the_game_folder_itself_stages_nothing() {
652 let fixture = Fixture::new();
653 let core = fixture.game_dir.join("BepInEx/core");
654
655 std::fs::create_dir_all(&core).unwrap();
656 std::fs::write(core.join("BepInEx.Preloader.dll"), b"x").unwrap();
657 std::fs::write(fixture.game_dir.join("winhttp.dll"), b"proxy").unwrap();
658
659 let target = InstallTarget::resolve(
660 fixture.base.clone(),
661 fixture.game_dir.clone(),
662 "valheim",
663 None,
664 )
665 .unwrap();
666
667 let prepared = prepare_launch(
668 &target,
669 &Ecosystem::bundled(),
670 &context(
671 HostOs::Windows,
672 StorePlatform::SteamDirect,
673 LaunchMode::Modded,
674 ),
675 )
676 .unwrap();
677
678 assert!(prepared.staged.is_empty());
679 }
680
681 #[test]
682 fn a_shimloader_launch_from_the_game_folder_still_stages_its_files() {
683 let eco = Ecosystem::bundled();
684 let dir = tempfile::tempdir().unwrap();
685 let game_dir = dir.path().join("game");
686 let exe = eco.require_profile("palworld").unwrap().exe_names[0].clone();
687
688 std::fs::create_dir_all(&game_dir).unwrap();
689 std::fs::write(game_dir.join(exe), b"game").unwrap();
690 std::fs::write(game_dir.join("ue4ss.dll"), b"loader").unwrap();
691 std::fs::write(game_dir.join("dwmapi.dll"), b"proxy").unwrap();
692
693 let target =
694 InstallTarget::resolve(dir.path().join("base"), game_dir.clone(), "palworld", None).unwrap();
695 let prepared = prepare_launch(
696 &target,
697 &eco,
698 &context(
699 HostOs::Windows,
700 StorePlatform::SteamDirect,
701 LaunchMode::Modded,
702 ),
703 )
704 .unwrap();
705 let binaries = game_dir.join("Pal/Binaries/Win64");
706
707 assert_eq!(
708 prepared.staged,
709 vec![binaries.join("dwmapi.dll"), binaries.join("ue4ss.dll")]
710 );
711 assert_eq!(
712 std::fs::read(binaries.join("dwmapi.dll")).unwrap(),
713 b"proxy"
714 );
715 }
716
717 #[test]
718 fn a_proton_steam_launch_gives_the_dll_override_to_paste() {
719 let fixture = Fixture::new();
720 let proton =
721 |mode| LaunchContext::new(HostOs::Linux, StorePlatform::Steam, Runtime::Proton, mode);
722
723 let modded = prepare_launch(
724 &fixture.target(),
725 &Ecosystem::bundled(),
726 &proton(LaunchMode::Modded),
727 )
728 .unwrap();
729 let vanilla = prepare_launch(
730 &fixture.target(),
731 &Ecosystem::bundled(),
732 &proton(LaunchMode::Vanilla),
733 )
734 .unwrap();
735
736 let pasted = vec![LaunchNotice::ProtonDllOverride {
737 dll: "winhttp".to_string(),
738 launch_options: "WINEDLLOVERRIDES=\"winhttp=n,b\" %command%".to_string(),
739 }];
740
741 assert_eq!(modded.notices, pasted);
742 assert_eq!(
743 vanilla.notices, pasted,
744 "Steam keeps one launch-options string for both modes"
745 );
746 }
747
748 #[test]
749 #[cfg(unix)]
750 fn staging_that_fails_partway_removes_the_files_it_created() {
751 let fixture = Fixture::new();
752 let elsewhere = fixture.game_dir.join("elsewhere.dll");
753
754 std::fs::write(fixture.profile_dir.join("a.ini"), b"config").unwrap();
755 std::os::unix::fs::symlink(&elsewhere, fixture.game_dir.join("winhttp.dll")).unwrap();
756
757 let result = prepare_launch(
758 &fixture.target(),
759 &Ecosystem::bundled(),
760 &context(
761 HostOs::Windows,
762 StorePlatform::SteamDirect,
763 LaunchMode::Modded,
764 ),
765 );
766
767 assert!(result.is_err());
768 assert!(!fixture.game_dir.join("a.ini").exists());
769 assert!(!elsewhere.exists());
770 }
771
772 #[test]
773 fn a_vanilla_launch_copies_nothing_into_the_game_folder() {
774 let fixture = Fixture::new();
775
776 let prepared = prepare_launch(
777 &fixture.target(),
778 &Ecosystem::bundled(),
779 &context(
780 HostOs::Windows,
781 StorePlatform::SteamDirect,
782 LaunchMode::Vanilla,
783 ),
784 )
785 .unwrap();
786
787 assert!(prepared.staged.is_empty());
788 assert!(!fixture.game_dir.join("winhttp.dll").exists());
789 }
790
791 #[test]
792 fn a_file_already_in_the_game_folder_is_reported_as_replaced_not_staged() {
793 let fixture = Fixture::new();
794 let own = fixture.game_dir.join("winhttp.dll");
795
796 std::fs::write(&own, b"the player's own").unwrap();
797
798 let prepared = prepare_launch(
799 &fixture.target(),
800 &Ecosystem::bundled(),
801 &context(
802 HostOs::Windows,
803 StorePlatform::SteamDirect,
804 LaunchMode::Modded,
805 ),
806 )
807 .unwrap();
808
809 assert!(prepared.staged.is_empty());
810 assert_eq!(prepared.replaced, vec![own.clone()]);
811 assert_eq!(std::fs::read(&own).unwrap(), b"proxy");
812 }
813}