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