Techblox Mod Manager / Launcher
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

245 lines
9.6KB

  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. if (CheckIfPatched() == GameState.Patched || unpatched.Checked)
  72. {
  73. Process process = null;
  74. if (command != null)
  75. {
  76. if (sender is Process) //Patched just now
  77. CheckCompatibilityAndDisableMods();
  78. await CheckModUpdatesAsync();
  79. process = Process.Start(command);
  80. }
  81. else if (Environment.OSVersion.Platform == PlatformID.Win32NT)
  82. {
  83. process = Process.Start(new ProcessStartInfo(GamePath("\\" + GetExe()))
  84. {
  85. WorkingDirectory = GamePath("\\") //Mods are only loaded if the working directory is correct
  86. });
  87. }
  88. if (process is null)
  89. throw new NullReferenceException("Game process is null");
  90. process.EnableRaisingEvents = true;
  91. process.Exited += HandleGameExit;
  92. }
  93. EndWork(false);
  94. tcs.SetResult(null);
  95. };
  96. if (InvokeRequired)
  97. Invoke(act);
  98. else
  99. act();
  100. }, tcs.Task);
  101. }
  102. private void HandleGameExit(object sender, EventArgs e)
  103. {
  104. ExecutePatcher(false).Exited += (o, args) =>
  105. {
  106. if (CheckIfPatched() == GameState.Patched)
  107. {
  108. MessageBox.Show("Failed to unpatch game, launching through the launcher will fail because of anticheat. " +
  109. "Check the output in the panel on the right.\n\n" +
  110. "Please try starting the game again by clicking Play.", "Patcher error",
  111. MessageBoxButtons.OK, MessageBoxIcon.Error);
  112. }
  113. };
  114. }
  115. private void CheckCompatibilityAndDisableMods()
  116. {
  117. if (!unpatched.Checked && MessageBox.Show("If the game updated just now, some mods may be incompatible or they may work just fine." +
  118. " Do you want to try running with mods?" +
  119. "\n\nClick Yes to start the game with mods (after a small update or if you just installed TBMM)" +
  120. "\nClick No to disable mods before starting the game (after a major update)" +
  121. "\n\nYou can always enable/disable mods by launching TBMM.",
  122. "Possible incompatibility warning", MessageBoxButtons.YesNo) == DialogResult.No)
  123. unpatched.Checked = true;
  124. }
  125. private async Task CheckModUpdatesAsync()
  126. {
  127. var updatable = mods.Values.Where(mod => mod.Updatable).ToArray();
  128. if (updatable.Length == 0)
  129. return;
  130. if (MessageBox.Show("Mod update(s) available!\n\n"
  131. + updatable.Select(mod => mod.Name + " " + mod.LatestVersion).Aggregate((a, b) => a + "\n")
  132. + "\n\nDo you want to update them now? You can also update later by opening TBMM.",
  133. "Update(s) available", MessageBoxButtons.YesNo) == DialogResult.No)
  134. return;
  135. foreach (var mod in updatable)
  136. await InstallMod(mod);
  137. MessageBox.Show("Mods updated");
  138. }
  139. public WebClient GetClient()
  140. {
  141. var client = new WebClient();
  142. client.Headers.Clear();
  143. client.Headers[HttpRequestHeader.Accept] = "application/json";
  144. client.BaseAddress = "https://git.exmods.org";
  145. return client;
  146. }
  147. private bool working = false;
  148. /// <summary>
  149. /// Some simple "locking", only allow one operation at a time
  150. /// </summary>
  151. /// <returns>Whether the work can begin</returns>
  152. public bool BeginWork()
  153. {
  154. if (working) return false;
  155. working = true;
  156. UpdateButton(playbtn, false);
  157. UpdateButton(installbtn, false);
  158. UpdateButton(uninstallbtn, false);
  159. UpdateButton(settingsbtn, false);
  160. unpatched.Enabled = false;
  161. return true;
  162. }
  163. public void EndWork(bool desc = true)
  164. {
  165. working = false;
  166. UpdateButton(playbtn, true);
  167. UpdateButton(settingsbtn, true);
  168. if (desc)
  169. modlist_SelectedIndexChanged(modlist, null);
  170. unpatched.Enabled = true;
  171. }
  172. /// <summary>
  173. /// Path must start with \
  174. /// </summary>
  175. /// <param name="path"></param>
  176. /// <param name="gamepath"></param>
  177. /// <returns></returns>
  178. public string GamePath(string path, string gamepath = null)
  179. {
  180. return ((gamepath ?? Configuration.GamePath) + path).Replace('\\', Path.DirectorySeparatorChar);
  181. }
  182. public string GetExe(string path = null, bool withExtension = true)
  183. {
  184. if (File.Exists(GamePath("\\Techblox.exe", path)))
  185. return "Techblox" + (withExtension ? ".exe" : "");
  186. if (File.Exists(GamePath("\\TechbloxPreview.exe", path)))
  187. return "TechbloxPreview.exe" + (withExtension ? ".exe" : "");
  188. return null;
  189. }
  190. private bool CheckNoExe()
  191. {
  192. return CheckNoExe(out _);
  193. }
  194. private bool CheckNoExe(out string path)
  195. {
  196. path = GetExe();
  197. if (path == null)
  198. {
  199. MessageBox.Show("Techblox not found! Set the correct path in Settings.");
  200. return true;
  201. }
  202. return false;
  203. }
  204. public DateTime GetGameVersionAsDate()
  205. {
  206. if (Configuration.GamePath == null) return default;
  207. using var fs = File.OpenRead(GamePath($"\\{GetExe(withExtension: false)}_Data\\globalgamemanagers"));
  208. using var sr = new StreamReader(fs);
  209. char[] data = new char[512];
  210. while(!sr.EndOfStream)
  211. {
  212. Array.Copy(data, 256, data, 0, 256);
  213. int read = sr.ReadBlock(data, 256, 256);
  214. for (int i = 0; i < data.Length - 11; i++)
  215. {
  216. if (data[i] == '2')
  217. {
  218. string date = new string(data, i, 11);
  219. if (date.StartsWith("202") && DateTime.TryParse(date, out var ret))
  220. return ret;
  221. }
  222. }
  223. }
  224. return default;
  225. }
  226. }
  227. }