Techblox Mod Manager / Launcher
25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.

279 satır
11KB

  1. using System;
  2. using System.Diagnostics;
  3. using System.Drawing;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Net;
  7. using System.Threading.Tasks;
  8. using System.Windows.Forms;
  9. using Microsoft.Win32;
  10. namespace TBMM
  11. {
  12. partial class MainForm
  13. {
  14. public void UpdateButton(Button button, bool enabled)
  15. {
  16. if (enabled)
  17. {
  18. button.ForeColor = Color.Lime;
  19. button.FlatAppearance.MouseOverBackColor = Color.FromArgb(0, 40, 0);
  20. button.FlatAppearance.MouseDownBackColor = Color.Green;
  21. }
  22. else
  23. {
  24. button.ForeColor = Color.Green;
  25. button.FlatAppearance.MouseOverBackColor = Color.Black;
  26. button.FlatAppearance.MouseDownBackColor = Color.Black;
  27. }
  28. }
  29. public string GetGameFolder()
  30. {
  31. using var key =
  32. Registry.LocalMachine.OpenSubKey(
  33. @"SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\Techblox Launcher") ??
  34. Registry.LocalMachine.OpenSubKey(
  35. @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Techblox Launcher");
  36. string launcherPath = key?.GetValue("DisplayIcon") is string launcherExecutable
  37. ? Directory.GetParent(launcherExecutable)?.FullName
  38. : null;
  39. launcherPath ??= Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
  40. "Techblox Launcher");
  41. string launcherConfig = Path.Combine(launcherPath, "launcher_settings.ini");
  42. if (!File.Exists(launcherConfig)) return null;
  43. string path = File.ReadLines(launcherConfig)
  44. .FirstOrDefault(line => line.StartsWith("133062..GAME_PATH="))
  45. ?.Substring("133062..GAME_PATH=".Length).Replace("/TBMM/", "/");
  46. if (path != null) path = (path + "StandaloneWindows64").Replace('/', Path.DirectorySeparatorChar);
  47. if (path != null && GetExe(path) != null) return path;
  48. return null;
  49. }
  50. public string SelectGameFolder()
  51. {
  52. var ofd = new OpenFileDialog();
  53. ofd.Filter = "Techblox executable|Techblox.exe|Techblox Preview executable|TechbloxPreview.exe";
  54. ofd.Title = "Game location";
  55. ofd.CheckFileExists = true;
  56. ofd.ShowDialog();
  57. return string.IsNullOrWhiteSpace(ofd.FileName) ? null : Directory.GetParent(ofd.FileName)?.FullName;
  58. }
  59. private (EventHandler, Task) CheckStartGame(string command)
  60. {
  61. var tcs = new TaskCompletionSource<object>();
  62. return ((sender, e) =>
  63. {
  64. Action act = async () =>
  65. {
  66. if (((sender as Process)?.ExitCode ?? 0) != 0)
  67. {
  68. status.Text = "Status: Patching failed";
  69. return;
  70. }
  71. var patched = CheckIfPatched();
  72. if (patched == GameState.Patched)
  73. {
  74. Process process = null;
  75. if (command != null)
  76. {
  77. await CheckModUpdatesAsync();
  78. process = Process.Start(command);
  79. }
  80. else if (Environment.OSVersion.Platform == PlatformID.Win32NT)
  81. {
  82. process = Process.Start(new ProcessStartInfo(GamePath("\\" + GetExe()))
  83. {
  84. WorkingDirectory = GamePath("\\") //Mods are only loaded if the working directory is correct
  85. });
  86. }
  87. if (process is null)
  88. throw new NullReferenceException("Game process is null");
  89. process.EnableRaisingEvents = true;
  90. process.Exited += HandleGameExit;
  91. _gameProcess = (process, true);
  92. patched = CheckIfPatched(); // Set in-game status
  93. }
  94. EndWork(patched, false);
  95. tcs.SetResult(null);
  96. };
  97. if (InvokeRequired)
  98. Invoke(act);
  99. else
  100. act();
  101. }, tcs.Task);
  102. }
  103. private void HandleGameExit(object sender, EventArgs e)
  104. {
  105. _gameProcess = (null, false);
  106. if (InvokeMethod(CheckIfPatched) != GameState.Patched || Configuration.KeepPatched)
  107. return;
  108. InvokeMethod(() => ExecutePatcher(false)).Exited += (_, _) =>
  109. {
  110. if (InvokeMethod(CheckIfPatched) == GameState.Patched)
  111. {
  112. MessageBox.Show("Failed to unpatch game, launching through the launcher will fail because of anticheat. " +
  113. "Check the output in the panel on the right.\n\n" +
  114. "Please try starting the game again by clicking Play.", "Patcher error",
  115. MessageBoxButtons.OK, MessageBoxIcon.Error);
  116. }
  117. };
  118. }
  119. private (Process Process, bool ExitHandlerAdded) _gameProcess = (null, false);
  120. private bool CheckIfGameIsRunning()
  121. {
  122. switch (_gameProcess.Process)
  123. {
  124. case { HasExited: false }:
  125. return true;
  126. case { HasExited: true }:
  127. MessageBox.Show("Game has exited without handling... Please report.");
  128. HandleGameExit(null, EventArgs.Empty);
  129. return false;
  130. default:
  131. if (_gameProcess.Process?.HasExited ?? true)
  132. _gameProcess = (Process.GetProcessesByName(GetExe(withExtension: false)).FirstOrDefault(), false);
  133. if (_gameProcess.Process == null) return false;
  134. if (_gameProcess.Process.HasExited)
  135. {
  136. HandleGameExit(null, EventArgs.Empty);
  137. return false;
  138. }
  139. else
  140. {
  141. if (_gameProcess.ExitHandlerAdded) return true;
  142. _gameProcess.Process.Exited += HandleGameExit;
  143. _gameProcess.Process.EnableRaisingEvents = true;
  144. _gameProcess.ExitHandlerAdded = true;
  145. return true;
  146. }
  147. }
  148. }
  149. private async Task CheckModUpdatesAsync()
  150. {
  151. var updatable = mods.Values.Where(mod => mod.Updatable).ToArray();
  152. if (updatable.Length == 0)
  153. return;
  154. if (MessageBox.Show("Mod update(s) available!\n\n"
  155. + updatable.Select(mod => mod.Name + " " + mod.LatestVersion).Aggregate((a, b) => a + "\n")
  156. + "\n\nDo you want to update them now? You can also update later by opening TBMM.",
  157. "Update(s) available", MessageBoxButtons.YesNo) == DialogResult.No)
  158. return;
  159. foreach (var mod in updatable)
  160. await InstallMod(mod);
  161. MessageBox.Show("Mods updated");
  162. }
  163. public WebClient GetClient()
  164. {
  165. var client = new WebClient();
  166. client.Headers.Clear();
  167. client.Headers[HttpRequestHeader.Accept] = "application/json";
  168. client.BaseAddress = "https://git.exmods.org";
  169. return client;
  170. }
  171. public T InvokeMethod<T>(Func<T> func)
  172. {
  173. if (InvokeRequired)
  174. return (T)Invoke(func);
  175. else
  176. return func();
  177. }
  178. private bool working = false;
  179. /// <summary>
  180. /// Some simple "locking", only allow one operation at a time
  181. /// </summary>
  182. /// <returns>Whether the work can begin</returns>
  183. public bool BeginWork()
  184. {
  185. if (working) return false;
  186. working = true;
  187. UpdateButton(playbtn, false);
  188. UpdateButton(installbtn, false);
  189. UpdateButton(uninstallbtn, false);
  190. UpdateButton(settingsbtn, false);
  191. return true;
  192. }
  193. public void EndWork(GameState state, bool desc = true)
  194. {
  195. working = false;
  196. if (state != GameState.InGame)
  197. UpdateButton(playbtn, true);
  198. UpdateButton(settingsbtn, true);
  199. if (desc)
  200. modlist_SelectedIndexChanged(modlist, null);
  201. }
  202. /// <summary>
  203. /// Path must start with \
  204. /// </summary>
  205. /// <param name="path"></param>
  206. /// <param name="gamepath"></param>
  207. /// <returns></returns>
  208. public string GamePath(string path, string gamepath = null)
  209. {
  210. return ((gamepath ?? Configuration.GamePath) + path).Replace('\\', Path.DirectorySeparatorChar);
  211. }
  212. public string GetExe(string path = null, bool withExtension = true)
  213. {
  214. if (File.Exists(GamePath("\\Techblox.exe", path)))
  215. return "Techblox" + (withExtension ? ".exe" : "");
  216. if (File.Exists(GamePath("\\TechbloxPreview.exe", path)))
  217. return "TechbloxPreview" + (withExtension ? ".exe" : "");
  218. return null;
  219. }
  220. private bool CheckNoExe()
  221. {
  222. return CheckNoExe(out _);
  223. }
  224. private bool CheckNoExe(out string path)
  225. {
  226. path = GetExe();
  227. if (path == null)
  228. {
  229. MessageBox.Show("Techblox not found! Set the correct path in Settings.");
  230. return true;
  231. }
  232. return false;
  233. }
  234. public DateTime GetGameVersionAsDate()
  235. {
  236. if (Configuration.GamePath == null) return default;
  237. using var fs = File.OpenRead(GamePath($"\\{GetExe(withExtension: false)}_Data\\globalgamemanagers"));
  238. using var sr = new StreamReader(fs);
  239. char[] data = new char[512];
  240. while(!sr.EndOfStream)
  241. {
  242. Array.Copy(data, 256, data, 0, 256);
  243. int read = sr.ReadBlock(data, 256, 256);
  244. for (int i = 0; i < data.Length - 11; i++)
  245. {
  246. if (data[i] == '2')
  247. {
  248. string date = new string(data, i, 11);
  249. if (date.StartsWith("202") && DateTime.TryParse(date, out var ret))
  250. return ret;
  251. }
  252. }
  253. }
  254. return default;
  255. }
  256. }
  257. }