using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Timers; using BepInEx.Configuration; using BepInEx.Logging; using HarmonyLib; using Mono.Cecil; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: AssemblyTitle("BepInEx.SplashScreen.Patcher")] [assembly: AssemblyDescription("Splash screen that shows loading progress when a game patched with BepInEx is loading.")] [assembly: AssemblyCompany("https://github.com/BepInEx/BepInEx.SplashScreen")] [assembly: AssemblyProduct("BepInEx.SplashScreen")] [assembly: AssemblyCopyright("Copyright © 2023")] [assembly: ComVisible(false)] [assembly: Guid("449b9f51-bbe5-4d4a-8936-e0a3081d79cb")] [assembly: AssemblyVersion("2.2.1.0")] namespace BepInEx.SplashScreen; public static class BepInExSplashScreenPatcher { public const string Version = "1.0"; private static int _initialized; public static IEnumerable TargetDLLs { get { Init(); return Enumerable.Empty(); } } static BepInExSplashScreenPatcher() { Init(); } public static void Patch(AssemblyDefinition _) { Init(); } public static void Init() { if (Interlocked.Exchange(ref _initialized, 1) != 1) { SplashScreenController.SpawnSplash(); } } } internal class Metadata { public const string Version = "2.2.1"; } internal sealed class LoadingLogListener : ILogListener, IDisposable { [CompilerGenerated] private sealed class d__5 : IEnumerator, IDisposable, IEnumerator { private int <>1__state; private object <>2__current; private int 5__1; object IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public d__5(int <>1__state) { this.<>1__state = <>1__state; } [DebuggerHidden] void IDisposable.Dispose() { <>1__state = -2; } private bool MoveNext() { switch (<>1__state) { default: return false; case 0: <>1__state = -1; 5__1 = 0; break; case 1: <>1__state = -1; 5__1++; break; } if (5__1 < 1) { <>2__current = null; <>1__state = 1; return true; } SplashScreenController.KillSplash(); return false; } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } } private bool _disposed; private LoadingLogListener() { } public static LoadingLogListener StartListening() { LoadingLogListener loadingLogListener = new LoadingLogListener(); Logger.Listeners.Add((ILogListener)(object)loadingLogListener); return loadingLogListener; } public void Dispose() { _disposed = true; } public void LogEvent(object sender, LogEventArgs eventArgs) { if (_disposed || !(eventArgs.Source.SourceName == "BepInEx") || eventArgs.Data == null) { return; } try { string text = (eventArgs.Data as string) ?? eventArgs.Data.ToString(); if (text == "Chainloader startup complete") { Dispose(); Traverse threadingHelper = Traverse.CreateWithType("BepInEx.ThreadingHelper").Property("Instance", (object[])null); Traverse val = threadingHelper.Method("StartSyncInvoke", new Type[1] { typeof(Action) }, (object[])null); if (val.MethodExists()) { val.GetValue(new object[1] { (Action)delegate { try { threadingHelper.Method("StartCoroutine", new Type[1] { typeof(IEnumerator) }, (object[])null).GetValue(new object[1] { DelayedCo() }); } catch (Exception ex2) { SplashScreenController.Logger.LogError((object)("Unexpected crash when trying to StartCoroutine: " + ex2)); SplashScreenController.KillSplash(); } } }); } else { Process currentProcess = Process.GetCurrentProcess(); System.Timers.Timer timer = new System.Timers.Timer(500.0); timer.Elapsed += delegate { try { timer.Stop(); currentProcess.Refresh(); if (currentProcess.Responding) { timer.Dispose(); SplashScreenController.KillSplash(); } else { SplashScreenController.Logger.LogDebug((object)"Process not responding, waiting..."); timer.Start(); } } catch (Exception ex) { SplashScreenController.Logger.LogError((object)("Unexpected crash in timer.Elapsed: " + ex)); SplashScreenController.KillSplash(); } }; timer.AutoReset = false; timer.Start(); } } else if (text.StartsWith("Failed to run [BepInEx.Chainloader]", StringComparison.Ordinal) || string.Equals(text, "Could not run preloader!", StringComparison.Ordinal)) { Dispose(); SplashScreenController.KillSplash(); } SplashScreenController.SendMessage(text); } catch (Exception arg) { SplashScreenController.Logger.LogError((object)string.Format("Crash in {0}, aborting. Exception: {1}", "LogEvent", arg)); SplashScreenController.KillSplash(); } } private static IEnumerator DelayedCo() { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new d__5(0); } } public static class SplashScreenController { internal static readonly ManualLogSource Logger = Logger.CreateLogSource("Splash"); private static readonly Queue _StatusQueue = Queue.Synchronized(new Queue(10, 2f)); private static LoadingLogListener _logListener; private static Process _guiProcess; public static void SpawnSplash() { //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Expected O, but got Unknown //IL_006a: Unknown result type (might be due to invalid IL or missing references) //IL_0074: Expected O, but got Unknown //IL_00b9: Unknown result type (might be due to invalid IL or missing references) //IL_00c3: Expected O, but got Unknown //IL_01ec: Unknown result type (might be due to invalid IL or missing references) //IL_01f6: Expected O, but got Unknown //IL_023e: Unknown result type (might be due to invalid IL or missing references) //IL_0248: Expected O, but got Unknown //IL_02d0: Unknown result type (might be due to invalid IL or missing references) //IL_02da: Expected O, but got Unknown try { ConfigFile val = new ConfigFile(Path.Combine(Paths.ConfigPath, "Bertogim.LoadingScreen.cfg"), true); bool value = val.Bind("1. LoadingScreen", "Enabled", true, "Display a loading window with information about game load progress on game start-up.").Value; string value2 = val.Bind("2. Window", "WindowType", "FakeGame", new ConfigDescription("FakeGame = Makes a window with the same icon as the game, tries to mimic the game till it appears\nFixedWindow = A fixed loading screen on top of all windows, cant move or close and is not on the taskbar (Same behavior as v1.0.5 and less).", (AcceptableValueBase)(object)new AcceptableValueList(new string[2] { "FakeGame", "FixedWindow" }), new object[0])).Value; int value3 = val.Bind("2. Window", "WindowWidth", 640, "The window width in pixels (Gets affected by windows screen scale config) \nHeight is automatically calculated by the image aspect ratio.").Value; int value4 = val.Bind("2. Window", "ExtraWaitTime", 1, new ConfigDescription("Seconds extra to maintain the loading screen starting when the game window shows up.\nGood for big modpacks where the game window stays blank loading for a few seconds", (AcceptableValueBase)(object)new AcceptableValueRange(0, 60), new object[0])).Value; string value5 = val.Bind("2. Window", "TitleBarColor", "#FFFFFF", "Hex color for the window's title bar (e.g. #1E90FF for DodgerBlue). Leave as #FFFFFF for default behavior. Requires Windows 10 build 1809+").Value; string value6 = val.Bind("2. Window", "BackgroundColor", "#000000", "Hex color for the background (Custom images cover this)").Value; string value7 = val.Bind("3. Text", "TextColor", "#FFFFFF", "Text color in hex format (e.g. #FFFFFF for white).").Value; string value8 = val.Bind("3. Text", "TextFont", "Segoe UI", "Font name used for the loading text (e.g. Arial, Segoe UI, Consolas). Must match an installed system font.\nFor a list of default Windows fonts, visit: https://learn.microsoft.com/en-us/typography/fonts/windows_10_font_list").Value; string value9 = val.Bind("3. Text", "TextBackgroundColor", "#595959", "Hex color for background behind the text (e.g. #595959 for gray)").Value; bool value10 = val.Bind("4. ProgressBar", "UseCustomProgressBar", true, "Whether to use a customizable progress bar (allows changing colors) instead of the Windows native one").Value; string value11 = val.Bind("4. ProgressBar", "ProgressBarColor", "#34b233", "Progress bar color, use a hex color (e.g. #34b233 for Wageningen Green)").Value; string value12 = val.Bind("4. ProgressBar", "ProgressBarBackgroundColor", "#FFFFFF", "Progress bar background color, use a hex color (e.g. #FFFFFF for white)").Value; int value13 = val.Bind("4. ProgressBar", "ProgressBarBorderSize", 0, new ConfigDescription("Border thickness in pixels (0-4)", (AcceptableValueBase)(object)new AcceptableValueRange(0, 4), new object[0])).Value; string value14 = val.Bind("4. ProgressBar", "ProgressBarBorderColor", "#FFFFFF", "Border color in hex format (e.g. #FF0000)").Value; int value15 = val.Bind("4. ProgressBar", "ProgressBarSmoothness", 25, new ConfigDescription("Loading bar smoothness when changing (0-100)", (AcceptableValueBase)(object)new AcceptableValueRange(0, 100), new object[0])).Value; string value16 = val.Bind("4. ProgressBar", "ProgressBarCurve", "EaseOut", new ConfigDescription("Animation curve used to interpolate the loading bar value smoothly over time.\nAvailable curves:\n- Linear: Constant speed\n- EaseIn: Starts slow, speeds up\n- EaseOut: Starts fast, slows down\n- EaseInOut: Slow start and end\n- SmootherStep: Smoothest transition (default)\n- Exponential: Very slow start, accelerates\n- Elastic: Overshoots and bounces into place\n- Bounce: Bounces like a ball at the end\n- BackIn: Starts by going backward, then forward\n- BackOut: Overshoots slightly and comes back\n- Spring: Oscillates like a spring", (AcceptableValueBase)(object)new AcceptableValueList(new string[11] { "Linear", "EaseIn", "EaseOut", "EaseInOut", "SmootherStep", "Exponential", "Elastic", "Bounce", "BackIn", "BackOut", "Spring" }), new object[0])).Value; if (!value) { Logger.LogDebug((object)"Not showing splash because the Enabled setting is off"); return; } string text = Path.Combine(Path.GetDirectoryName(typeof(SplashScreenController).Assembly.Location) ?? Path.Combine(Paths.PatcherPluginPath, "1. LoadingScreen"), "LoadingScreen.GUI.exe"); if (!File.Exists(text)) { throw new FileNotFoundException("Executable not found or inaccessible at " + text); } Logger.Log((LogLevel)32, (object)("Starting GUI process: " + text)); ProcessStartInfo startInfo = new ProcessStartInfo(text, Process.GetCurrentProcess().Id.ToString()) { UseShellExecute = false, RedirectStandardInput = true, RedirectStandardOutput = true, RedirectStandardError = true, StandardOutputEncoding = Encoding.UTF8, StandardErrorEncoding = Encoding.UTF8 }; _guiProcess = Process.Start(startInfo); Thread thread = new Thread(CommunicationThread); thread.IsBackground = true; thread.Start(_guiProcess); _logListener = LoadingLogListener.StartListening(); } catch (Exception ex) { Logger.LogError((object)("Failed to start GUI: " + ex)); KillSplash(); } } internal static void SendMessage(string message) { _StatusQueue.Enqueue(message); } private static void CommunicationThread(object processArg) { try { Process process = (Process)processArg; process.Exited += delegate { KillSplash(); }; process.OutputDataReceived += delegate(object sender, DataReceivedEventArgs args) { if (args.Data != null) { Logger.Log((LogLevel)32, (object)("[GUI] " + args.Data.Replace('\t', '\n').TrimEnd(new char[1] { '\n' }))); } }; process.BeginOutputReadLine(); process.ErrorDataReceived += delegate(object sender, DataReceivedEventArgs args) { if (args.Data != null) { Logger.Log((LogLevel)2, (object)("[GUI] " + args.Data.Replace('\t', '\n').TrimEnd(new char[1] { '\n' }))); } }; process.BeginErrorReadLine(); process.StandardInput.AutoFlush = false; Logger.LogDebug((object)"Connected to the GUI process"); bool flag = false; while (!process.HasExited) { while (_StatusQueue.Count > 0 && process.StandardInput.BaseStream.CanWrite) { process.StandardInput.WriteLine(_StatusQueue.Dequeue()); flag = true; } if (flag) { flag = false; process.StandardInput.Flush(); } Thread.Sleep(150); } } catch (ThreadAbortException) { } catch (Exception arg) { Logger.LogError((object)string.Format("Crash in {0}, aborting. Exception: {1}", "CommunicationThread", arg)); } finally { KillSplash(); } } internal static void KillSplash() { try { _logListener?.Dispose(); _StatusQueue.Clear(); _StatusQueue.TrimToSize(); try { if (_guiProcess != null && !_guiProcess.HasExited) { Logger.LogDebug((object)"Closing GUI process"); _guiProcess.Kill(); } } catch (Exception) { } Logger.Dispose(); } catch (Exception value) { Console.WriteLine(value); } } }