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.

240 lines
9.1KB

  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. namespace GCMM
  10. {
  11. partial class MainForm
  12. {
  13. public void UpdateButton(Button button, bool enabled)
  14. {
  15. if (enabled)
  16. {
  17. button.ForeColor = Color.Lime;
  18. button.FlatAppearance.MouseOverBackColor = Color.FromArgb(0, 40, 0);
  19. button.FlatAppearance.MouseDownBackColor = Color.Green;
  20. }
  21. else
  22. {
  23. button.ForeColor = Color.Green;
  24. button.FlatAppearance.MouseOverBackColor = Color.Black;
  25. button.FlatAppearance.MouseDownBackColor = Color.Black;
  26. }
  27. }
  28. private bool EnableDisableAutoPatching(bool enable)
  29. {
  30. string launcherConfig =
  31. Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
  32. "Techblox Launcher", "launcher_settings.ini");
  33. bool gamePathSet = false;
  34. if (File.Exists(launcherConfig))
  35. {
  36. string[] lines = File.ReadLines(launcherConfig).Select(line =>
  37. {
  38. if (line.StartsWith("133062..GAME_PATH=") && line.Contains('/'))
  39. {
  40. gamePathSet = true;
  41. return
  42. $"{line.Substring(0, Math.Max(line.LastIndexOf("TBMM", StringComparison.Ordinal), line.Length))}{(enable ? "TBMM/" : "")}";
  43. }
  44. return line;
  45. }).ToArray(); //Need to close the file
  46. File.WriteAllLines(launcherConfig, lines);
  47. }
  48. return gamePathSet;
  49. }
  50. public void EnableDisableAutoPatchingWithDialog(bool enable)
  51. {
  52. if (EnableDisableAutoPatching(enable))
  53. {
  54. DialogUtils.ShowInfo(resources.GetString("Change_launch_settings_done"),
  55. resources.GetString("Change_launch_settings_title"));
  56. Configuration.AutoPatch = enable ? AutoPatchingState.Enabled : AutoPatchingState.Disabled;
  57. }
  58. else
  59. DialogUtils.ShowError(resources.GetString("Change_launch_settings_error"),
  60. resources.GetString("Change_launch_settings_title"));
  61. }
  62. public string GetGameFolder()
  63. {
  64. string launcherConfig =
  65. Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
  66. "Techblox Launcher", "launcher_settings.ini");
  67. if (!File.Exists(launcherConfig)) return null;
  68. string path = File.ReadLines(launcherConfig)
  69. .FirstOrDefault(line => line.StartsWith("133062..GAME_PATH="))
  70. ?.Substring("133062..GAME_PATH=".Length);
  71. if (path != null && GetExe(path) != null) return path;
  72. return null;
  73. }
  74. public string SelectGameFolder()
  75. {
  76. var ofd = new OpenFileDialog();
  77. ofd.Filter = "Techblox executable|Techblox.exe|Techblox Preview executable|TechbloxPreview.exe";
  78. ofd.Title = "Game location";
  79. ofd.CheckFileExists = true;
  80. ofd.ShowDialog();
  81. return string.IsNullOrWhiteSpace(ofd.FileName) ? null : Directory.GetParent(ofd.FileName)?.FullName;
  82. }
  83. private (EventHandler, Task) CheckStartGame(string command)
  84. {
  85. var tcs = new TaskCompletionSource<object>();
  86. return ((sender, e) =>
  87. {
  88. Action act = async () =>
  89. {
  90. if (((sender as Process)?.ExitCode ?? 0) != 0)
  91. {
  92. status.Text = "Status: Patching failed";
  93. return;
  94. }
  95. if (CheckIfPatched() == GameState.Patched || unpatched.Checked)
  96. if (command != null)
  97. {
  98. if (sender is Process) //Patched just now
  99. CheckCompatibilityAndDisableMods();
  100. await CheckModUpdatesAsync();
  101. Process.Start(command);
  102. }
  103. if (Environment.OSVersion.Platform == PlatformID.Win32NT)
  104. Process.Start(new ProcessStartInfo(GamePath("\\" + GetExe()))
  105. {
  106. WorkingDirectory = GamePath("\\") //Mods are only loaded if the working directory is correct
  107. });
  108. EndWork(false);
  109. tcs.SetResult(null);
  110. };
  111. if (InvokeRequired)
  112. Invoke(act);
  113. else
  114. act();
  115. }, tcs.Task);
  116. }
  117. private void CheckCompatibilityAndDisableMods()
  118. {
  119. if (!unpatched.Checked && MessageBox.Show("If the game updated just now, some mods may be incompatible or they may work just fine." +
  120. " Do you want to try running with mods?" +
  121. "\n\nClick Yes to start the game with mods (after a small update or if you just installed GCMM)" +
  122. "\nClick No to disable mods before starting the game (after a major update)" +
  123. "\n\nYou can always enable/disable mods by launching GCMM.",
  124. "Possible incompatibility warning", MessageBoxButtons.YesNo) == DialogResult.No)
  125. unpatched.Checked = true;
  126. }
  127. private async Task CheckModUpdatesAsync()
  128. {
  129. var updatable = mods.Values.Where(mod => mod.Updatable).ToArray();
  130. if (updatable.Length == 0)
  131. return;
  132. if (MessageBox.Show("Mod update(s) available!\n\n"
  133. + updatable.Select(mod => mod.Name + " " + mod.LatestVersion).Aggregate((a, b) => a + "\n")
  134. + "\n\nDo you want to update them now? You can also update later by opening GCMM.",
  135. "Update(s) available", MessageBoxButtons.YesNo) == DialogResult.No)
  136. return;
  137. foreach (var mod in updatable)
  138. await InstallMod(mod);
  139. MessageBox.Show("Mods updated");
  140. }
  141. public WebClient GetClient()
  142. {
  143. var client = new WebClient();
  144. client.Headers.Clear();
  145. client.Headers[HttpRequestHeader.Accept] = "application/json";
  146. client.BaseAddress = "https://git.exmods.org";
  147. return client;
  148. }
  149. private bool working = false;
  150. /// <summary>
  151. /// Some simple "locking", only allow one operation at a time
  152. /// </summary>
  153. /// <returns>Whether the work can begin</returns>
  154. public bool BeginWork()
  155. {
  156. if (working) return false;
  157. working = true;
  158. UpdateButton(playbtn, false);
  159. UpdateButton(installbtn, false);
  160. UpdateButton(uninstallbtn, false);
  161. UpdateButton(settingsbtn, false);
  162. unpatched.Enabled = false;
  163. return true;
  164. }
  165. public void EndWork(bool desc = true)
  166. {
  167. working = false;
  168. UpdateButton(playbtn, true);
  169. UpdateButton(settingsbtn, true);
  170. if (desc)
  171. modlist_SelectedIndexChanged(modlist, null);
  172. unpatched.Enabled = true;
  173. }
  174. /// <summary>
  175. /// Path must start with \
  176. /// </summary>
  177. /// <param name="path"></param>
  178. /// <param name="gamepath"></param>
  179. /// <returns></returns>
  180. public string GamePath(string path, string gamepath = null)
  181. {
  182. return ((gamepath ?? Configuration.GamePath) + path).Replace('\\', Path.DirectorySeparatorChar);
  183. }
  184. public string GetExe(string path = null)
  185. {
  186. if (File.Exists(GamePath("\\Techblox.exe", path)))
  187. return "Techblox.exe";
  188. if (File.Exists(GamePath("\\TechbloxPreview.exe", path)))
  189. return "TechbloxPreview.exe";
  190. return null;
  191. }
  192. private bool CheckNoExe()
  193. {
  194. return CheckNoExe(out _);
  195. }
  196. private bool CheckNoExe(out string path)
  197. {
  198. path = GetExe();
  199. if (path == null)
  200. {
  201. MessageBox.Show("Techblox not found! Set the correct path in Settings.");
  202. return true;
  203. }
  204. return false;
  205. }
  206. public async Task<DateTime> GetLastGameUpdateTime()
  207. {
  208. /*using (var client = GetClient())
  209. {
  210. string html = await client.DownloadStringTaskAsync("https://api.steamcmd.net/v1/info/1078000");
  211. var regex = new Regex("<i>timeupdated:</i>[^<]*<b>([^<]*)</b>");
  212. var match = regex.Match(html);
  213. if (!match.Success)
  214. return default;
  215. return new DateTime(1970, 1, 1).AddSeconds(long.Parse(match.Groups[1].Value));
  216. }*/
  217. //return new DateTime(2020, 12, 28);
  218. return default;
  219. }
  220. }
  221. }