This repository has been archived by the owner on Jun 24, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Program.cs
451 lines (414 loc) · 15.4 KB
/
Program.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using System.ComponentModel;
using System.Reflection;
using Application = System.Windows.Forms.Application;
namespace MW5_Mod_Manager
{
static class Program
{
/// <summary>
/// The main entry point for the application.
///
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
Application.Run(new Form1());
}
private static System.Reflection.Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("EmbedAssembly.Newtonsoft.Json.dll"))
{
byte[] assemblyData = new byte[stream.Length];
stream.Read(assemblyData, 0, assemblyData.Length);
return Assembly.Load(assemblyData);
}
}
}
public class MainLogic
{
public float Version = 0.85f;
public float NewVersion = 0f;
public string Vendor = "";
public bool CreatedModlist = false;
public JObject parent;
public string CurrentFolderInsearch;
public bool InterruptSearch = false;
public string BasePath = "";
public string[] Directories;
public Dictionary<string, bool> ModList = new Dictionary<string, bool>();
public Dictionary<string, ModObject> ModDetails = new Dictionary<string, ModObject>();
public string rawJson;
public void Loadstuff()
{
//Check if the Mods directory exits:
if (!this.CheckModsDir())
return;
//find all mod directories and parse them into just folder names:
ParseDirectories();
//parse modlist.json
ModListParser();
//Combine so we have all mods in the ModList Dict for easy later use and writing to JObject
CombineDirModList();
//Load each mods mod.json and store in Dict.
LoadModDetails();
}
public void LoadStuff2()
{
//find all mod directories and parse them into just folder names:
ParseDirectories();
//Combine so we have all mods in the ModList Dict for easy later use and writing to JObject
CombineDirModList();
//Load each mods mod.json and store in Dict.
LoadModDetails();
}
private bool CheckModsDir()
{
if (this.BasePath == null || this.BasePath == "" || this.BasePath == " ")
return false;
if (!Directory.Exists(this.BasePath))
{
string message = "ERROR Mods folder does not exits in : " + this.BasePath + " Do you want to create it?";
string caption = "ERROR Loading";
MessageBoxButtons buttons = MessageBoxButtons.YesNo;
DialogResult Result = MessageBox.Show(message, caption, buttons);
if(Result == DialogResult.Yes)
{
Directory.CreateDirectory(BasePath);
}
return false;
}
return true;
}
//Try and load install dir path from stored data files.
public bool TryLoadInstallDir()
{
//Load install dir from previous session:
string systemPath = System.Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
string complete = Path.Combine(systemPath, @"MW5LoadOrderManager");
if (!File.Exists(complete))
{
System.IO.Directory.CreateDirectory(complete);
}
Console.WriteLine(complete);
Console.WriteLine(this.Vendor);
try
{
string[] text = System.IO.File.ReadLines(complete + @"\installdir.txt").ToArray<string>();
if (text[0] != null && text[0] != "")
{
this.BasePath = text[0];
}
if (text[1] != null && text[1] != "")
{
this.Vendor = text[1];
}
Console.WriteLine(this.BasePath);
Console.WriteLine(this.Vendor);
}
catch (Exception e)
{
}
if (this.BasePath != null && this.BasePath != "")
return true;
return false;
}
public void WhipeInstallDirMemory()
{
try
{
string systemPath = System.Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
string complete = Path.Combine(systemPath, @"MW5LoadOrderManager");
System.IO.File.WriteAllText(complete + @"\installdir.txt", " ");
}catch(Exception Ex)
{
return;
}
}
public void ParseDirectories()
{
this.Directories = Directory.GetDirectories(BasePath);
for (int i = 0; i < Directories.Length; i++)
{
string directory = this.Directories[i];
string[] temp = directory.Split('\\');
Directories[i] = temp[temp.Length - 1];
}
}
public void ModListParser()
{
try
{
this.rawJson = File.ReadAllText(BasePath + @"\modlist.json");
this.parent = JObject.Parse(rawJson);
}
catch (Exception e)
{
string message = "ERROR loading modlist.json in : " + this.BasePath + ". It will be created after locating possible mod directories.";
string caption = "ERROR Loading";
MessageBoxButtons buttons = MessageBoxButtons.OK;
DialogResult Result = MessageBox.Show(message, caption, buttons);
this.CreatedModlist = true;
return;
}
foreach (JProperty mod in this.parent.Value<JObject>("modStatus").Properties())
{
bool enabled = (bool)this.parent["modStatus"][mod.Name]["bEnabled"];
this.ModList.Add(mod.Name, enabled);
}
}
public void SaveToFiles()
{
UpdateJObject();
SaveModDetails();
SaveModListJson();
}
public void ClearAll()
{
this.ModDetails = new Dictionary<string, ModObject>();
this.ModList = new Dictionary<string, bool>();
}
//Check if the mod dir is already present in data loaded from modlist.json, if not add it.
public void CombineDirModList()
{
foreach (string modDir in this.Directories)
{
if (this.ModList.ContainsKey(modDir))
continue;
ModList.Add(modDir, false);
}
//Turns out there are sometimes "ghost" entries in the modlist.json for witch there are no directories left, lets remove those.
List<string> toRemove = new List<string>();
foreach (KeyValuePair<string, bool> entry in this.ModList)
{
if (this.Directories.Contains<string>(entry.Key))
{
continue;
}
toRemove.Add(entry.Key);
}
foreach (string key in toRemove)
{
this.ModList.Remove(key);
}
if (this.CreatedModlist)
{
UpdateJObject();
SaveModListJson();
}
}
public void LoadModDetails()
{
foreach (string modDir in this.Directories)
{
try
{
string modJson = File.ReadAllText(BasePath + @"\" + modDir + @"\mod.json");
ModObject mod = JsonConvert.DeserializeObject<ModObject>(modJson);
this.ModDetails.Add(modDir, mod);
}
catch (Exception e)
{
string message = "ERROR loading mod.json in : " + modDir +
" folder will be skipped. " +
" If this is not a mod folder you can ignore ths message.";
string caption = "ERROR Loading";
MessageBoxButtons buttons = MessageBoxButtons.OK;
MessageBox.Show(message, caption, buttons);
if (ModList.ContainsKey(modDir))
{
ModList.Remove(modDir);
}
if (ModDetails.ContainsKey(modDir))
{
ModDetails.Remove(modDir);
}
}
}
}
public void SaveModDetails()
{
foreach (KeyValuePair<string, ModObject> entry in this.ModDetails)
{
string modJsonPath = BasePath + @"\" + entry.Key + @"\mod.json";
JsonSerializer serializer = new JsonSerializer();
serializer.Formatting = Formatting.Indented;
using (StreamWriter sw = new StreamWriter(modJsonPath))
using (JsonWriter writer = new JsonTextWriter(sw))
{
serializer.Serialize(writer, entry.Value);
}
}
}
public void UpdateJObject()
{
if(this.parent == null)
{
this.parent = new JObject();
this.parent.Add("modStatus", JObject.Parse(@"{}"));
}
this.parent.Value<JObject>("modStatus").RemoveAll();
foreach (KeyValuePair<string, bool> entry in this.ModList)
{
AddModToJObject(entry.Key, entry.Value);
}
}
public void SaveModListJson()
{
string jsonString = this.parent.ToString();
StreamWriter sw = File.CreateText(BasePath + @"\modlist.json");
sw.WriteLine(jsonString);
sw.Flush();
sw.Close();
}
public void AddModToJObject(string ModName, bool status)
{
//ugly but I'm lazy today
if (status)
{
(this.parent["modStatus"] as JObject).Add(ModName, JObject.Parse(@"{""bEnabled"": true}"));
}
else
{
(this.parent["modStatus"] as JObject).Add(ModName, JObject.Parse(@"{""bEnabled"": false}"));
}
}
public void SetModInJObject(string ModName, bool status)
{
this.parent["modStatus"][ModName]["bEnabled"] = status;
}
public string Findfile(string folder, string fname, BackgroundWorker worker, DoWorkEventArgs e)
{
foreach (string newFolder in Directory.GetDirectories(folder))
{
this.CurrentFolderInsearch = newFolder;
worker.ReportProgress(0, newFolder);
if (worker.CancellationPending)
{
e.Cancel = true;
return "";
}
try
{
string found = Findfile(newFolder, fname, worker, e);
if (found != null && found != "")
{
return found;
}
}
catch (Exception ex)
{
}
}
if (File.Exists(folder + @"\" + fname) == true)
{
try
{
//ExeFilePath = folder;
return folder;
}
catch (Exception ex)
{
}
}
return "";
}
public string FindInstallDir(BackgroundWorker worker, DoWorkEventArgs e)
{
//No dir set from previous session locate install dir
//first lets look in common install folders to minimize search time:
foreach (DriveInfo d in DriveInfo.GetDrives().Where(x => x.IsReady == true))
{
foreach (string folder in this.CommonFolders)
{
string found = Findfile(d.Name, "MechWarrior.exe", worker, e);
if (found != null && found != "")
{
this.BasePath = found + @"\MW5Mercs\Mods";
return BasePath;
}
}
}
//install location not found, look EVERYWHERE:
foreach (DriveInfo d in DriveInfo.GetDrives().Where(x => x.IsReady == true))
{
string found = Findfile(d.Name, "MechWarrior.exe", worker, e);
if (found != null && found != "")
{
this.BasePath = found + @"\MW5Mercs\Mods";
return BasePath;
}
}
//return some sort of error in locating the install location.
return "";
}
public string Scramble(string input)
{
input = input.Replace(" ", "");
input = input.Replace("\n", "");
input = input.Replace("\t", "");
char[] chars = input.ToArray();
Random r = new Random(69); //he he he...
for (int i = 0; i < chars.Length; i++)
{
int randomIndex = r.Next(0, chars.Length);
char temp = chars[randomIndex];
chars[randomIndex] = chars[i];
chars[i] = temp;
}
string scrambled = new string(chars);
Console.WriteLine(scrambled);
return scrambled;
}
public string UnScramble(string scrambled)
{
Random r = new Random(69);
char[] scramChars = scrambled.ToArray();
List<int> swaps = new List<int>();
for (int i = 0; i < scramChars.Length; i++)
{
swaps.Add(r.Next(0, scramChars.Length));
}
for (int i = scramChars.Length - 1; i >= 0; i--)
{
char temp = scramChars[swaps[i]];
scramChars[swaps[i]] = scramChars[i];
scramChars[i] = temp;
}
string unscrambled = new string(scramChars);
Console.WriteLine(unscrambled);
return unscrambled;
}
//Searched first when looking for file names
public List<string> CommonFolders = new List<string>()
{
@"games\",
@"Program Files\",
@"Program Files (x86)\",
@"Epic\",
@"EpicGames\",
@"Epic Games\",
@"Epic_Games\"
};
}
public class ModObject
{
public string displayName { set; get; }
public string version { set; get; }
public string description { set; get; }
public string author { set; get; }
public string authorURL { set; get; }
public float defaultLoadOrder { set; get; }
public string gameVersion { set; get; }
public List<string> manifest { get; set; }
}
}