casualexpiesource

cu-trainer/Ultra Paradise Linux/app/Mac.cs

308 lines · 13.7 KB · plain text · download

1using System;
2using System.Collections.Generic;
3using System.Diagnostics;
4using System.IO;
5using System.Linq;
6using System.Text;
7using System.Text.RegularExpressions;
8using System.Threading.Tasks;
9
10namespace UltraParadise.Linux
11{
12 internal static class Mac
13 {
14 public static bool On => OperatingSystem.IsMacOS();
15 public const string OverrideKey = "\"winhttp\"=\"native,builtin\"";
16
17 public static string AppSupport => Path.Combine(Dirs.Home, "Library", "Application Support");
18
19 public static List<(string prefix, string kind)> Bottles()
20 {
21 List<(string, string)> o = new();
22 HashSet<string> seen = new(StringComparer.Ordinal);
23 void Add(string p, string kind)
24 {
25 try
26 {
27 if (Directory.Exists(Path.Combine(p, "drive_c")) && seen.Add(Path.GetFullPath(p))) o.Add((p, kind));
28 }
29 catch (Exception) { }
30 }
31 void Each(string dir, string kind, Func<string, string> map)
32 {
33 try
34 {
35 if (!Directory.Exists(dir)) return;
36 foreach (string d in Directory.GetDirectories(dir)) Add(map(d), kind);
37 }
38 catch (Exception) { }
39 }
40 string h = Dirs.Home;
41 Each(Path.Combine(AppSupport, "CrossOver", "Bottles"), "CrossOver", d => d);
42 Each(Path.Combine(h, "Library", "Containers", "com.isaacmarovitz.Whisky", "Bottles"), "Whisky", d => d);
43 Each(Path.Combine(h, "Library", "Containers", "com.isaacmarovitz.Whisky", "Data", "Library", "Application Support", "com.isaacmarovitz.Whisky", "Bottles"), "Whisky", d => d);
44 Each(Path.Combine(h, "Games", "Heroic", "Prefixes"), "Heroic", d => d);
45 Each(Path.Combine(h, "Games", "Heroic", "Prefixes", "default"), "Heroic", d => d);
46 foreach (string apps in new[] { Path.Combine(h, "Applications"), Path.Combine(h, "Applications", "Wineskin"), Path.Combine(h, "Applications", "Sikarugir"), "/Applications/Wineskin" })
47 Each(apps, "Wineskin", d => Path.Combine(d, "Contents", "SharedSupport", "prefix"));
48 Add(Path.Combine(h, ".wine"), "Wine");
49 return o;
50 }
51
52 public static string BottleOf(string game)
53 {
54 try
55 {
56 DirectoryInfo d = new(game);
57 while (d != null)
58 {
59 if (Directory.Exists(Path.Combine(d.FullName, "drive_c")) && File.Exists(Path.Combine(d.FullName, "user.reg"))) return d.FullName;
60 d = d.Parent;
61 }
62 }
63 catch (Exception) { }
64 return null;
65 }
66
67 public static string KindOf(string bottle)
68 {
69 if (bottle == null) return null;
70 if (bottle.Contains("/CrossOver/Bottles/", StringComparison.Ordinal)) return "CrossOver";
71 if (bottle.Contains("com.isaacmarovitz.Whisky", StringComparison.Ordinal)) return "Whisky";
72 if (bottle.Contains("/Heroic/", StringComparison.Ordinal)) return "Heroic";
73 if (bottle.Contains("/SharedSupport/prefix", StringComparison.Ordinal)) return "Wineskin";
74 return "Wine";
75 }
76
77 public static string FromWindows(string bottle, string winPath)
78 {
79 if (string.IsNullOrEmpty(winPath) || winPath.Length < 2 || winPath[1] != ':') return null;
80 char drive = char.ToLowerInvariant(winPath[0]);
81 string rest = winPath[2..].Replace("\\\\", "\\").Replace('\\', '/').TrimStart('/');
82 string root = drive == 'c' ? Path.Combine(bottle, "drive_c") : Path.Combine(bottle, "dosdevices", drive + ":");
83 try
84 {
85 FileSystemInfo t = new DirectoryInfo(root).ResolveLinkTarget(true);
86 if (t != null) root = t.FullName;
87 }
88 catch (Exception) { }
89 return Path.Combine(root, rest);
90 }
91
92 public static List<string> Libraries()
93 {
94 List<string> libs = new();
95 HashSet<string> seen = new(StringComparer.Ordinal);
96 foreach (var (b, _) in Bottles())
97 {
98 foreach (string s in new[] { Path.Combine(b, "drive_c", "Program Files (x86)", "Steam"), Path.Combine(b, "drive_c", "Program Files", "Steam") })
99 {
100 if (!Directory.Exists(s)) continue;
101 if (seen.Add(s)) libs.Add(s);
102 try
103 {
104 string f = Path.Combine(s, "steamapps", "libraryfolders.vdf");
105 if (!File.Exists(f)) continue;
106 VNode v = Vdf.Parse(File.ReadAllText(f));
107 VNode lf = v.Child("libraryfolders") ?? v;
108 foreach (VNode n in lf.Kids ?? new List<VNode>())
109 {
110 string p = FromWindows(b, n.Kids != null ? n.Child("path")?.Value : n.Value);
111 if (p != null && Directory.Exists(p) && seen.Add(p)) libs.Add(p);
112 }
113 }
114 catch (Exception) { }
115 }
116 }
117 return libs;
118 }
119
120 public static string Find()
121 {
122 foreach (string lib in Libraries())
123 {
124 try
125 {
126 string acf = Path.Combine(lib, "steamapps", "appmanifest_" + Game.AppId + ".acf");
127 if (File.Exists(acf))
128 {
129 string dir = Vdf.Parse(File.ReadAllText(acf)).Child("AppState")?.Child("installdir")?.Value;
130 if (!string.IsNullOrEmpty(dir))
131 {
132 string d = Path.Combine(lib, "steamapps", "common", dir);
133 if (Game.IsGameDir(d)) return d;
134 }
135 }
136 string guess = Path.Combine(lib, "steamapps", "common", "Casualties Unknown");
137 if (Game.IsGameDir(guess)) return guess;
138 }
139 catch (Exception) { }
140 }
141 return null;
142 }
143
144 public static string Ps()
145 {
146 try
147 {
148 ProcessStartInfo si = new("/bin/ps") { RedirectStandardOutput = true, UseShellExecute = false };
149 si.ArgumentList.Add("-axo");
150 si.ArgumentList.Add("command=");
151 using Process p = Process.Start(si);
152 string o = p.StandardOutput.ReadToEnd();
153 p.WaitForExit(3000);
154 return o;
155 }
156 catch (Exception) { return ""; }
157 }
158
159 public static bool GameRunning()
160 {
161 foreach (string l in Ps().Split('\n'))
162 if (l.Contains(Game.Exe, StringComparison.OrdinalIgnoreCase) && !l.Contains("UltraParadise", StringComparison.Ordinal)) return true;
163 return false;
164 }
165
166 public static bool WineRunning()
167 {
168 foreach (string l in Ps().Split('\n'))
169 if (l.Contains("wineserver", StringComparison.Ordinal)) return true;
170 return false;
171 }
172
173 public static string OverrideState(string game)
174 {
175 string b = BottleOf(game);
176 if (b == null) return "unknown";
177 try
178 {
179 string reg = File.ReadAllText(Path.Combine(b, "user.reg"));
180 int s = SectionStart(reg);
181 if (s < 0) return "unset";
182 int e = reg.IndexOf("\n[", s + 1, StringComparison.Ordinal);
183 string sec = e < 0 ? reg[s..] : reg[s..e];
184 return Regex.IsMatch(sec, "^\"\\*?winhttp\"=\"native(,builtin)?\"", RegexOptions.Multiline | RegexOptions.IgnoreCase) ? "set" : "unset";
185 }
186 catch (Exception) { return "unknown"; }
187 }
188
189 private static int SectionStart(string reg)
190 {
191 Match m = Regex.Match(reg, "^\\[Software\\\\\\\\Wine\\\\\\\\DllOverrides\\][^\\n]*$", RegexOptions.Multiline | RegexOptions.IgnoreCase);
192 return m.Success ? m.Index : -1;
193 }
194
195 public static string SetOverride(string game)
196 {
197 string b = BottleOf(game);
198 if (b == null) return "couldn't find the Wine bottle the game is in";
199 if (WineRunning()) return "something is still running in Wine. Quit Steam and anything else in " + KindOf(b) + " (or the whole app), then try again";
200 string f = Path.Combine(b, "user.reg");
201 try
202 {
203 string reg = File.ReadAllText(f).Replace("\r\n", "\n");
204 if (OverrideState(game) == "set") return null;
205 int s = SectionStart(reg);
206 if (s >= 0)
207 {
208 int eol = reg.IndexOf('\n', s);
209 if (eol < 0) { reg += "\n"; eol = reg.Length - 1; }
210 int at = eol + 1;
211 if (reg.Length > at && reg[at] == '#') { int e2 = reg.IndexOf('\n', at); at = e2 < 0 ? reg.Length : e2 + 1; }
212 string body = reg[at..];
213 Match old = Regex.Match(body, "^\"\\*?winhttp\"=\"[^\"\\n]*\"\\n?", RegexOptions.Multiline | RegexOptions.IgnoreCase);
214 int end = reg.IndexOf("\n[", at, StringComparison.Ordinal);
215 if (old.Success && (end < 0 || at + old.Index < end)) reg = reg.Remove(at + old.Index, old.Length);
216 reg = reg.Insert(at, OverrideKey + "\n");
217 }
218 else
219 {
220 if (!reg.EndsWith("\n\n", StringComparison.Ordinal)) reg += reg.EndsWith('\n') ? "\n" : "\n\n";
221 reg += "[Software\\\\Wine\\\\DllOverrides] " + DateTimeOffset.UtcNow.ToUnixTimeSeconds() + "\n" + OverrideKey + "\n";
222 }
223 string bak = f + ".ultraparadise.bak";
224 if (!File.Exists(bak)) File.Copy(f, bak);
225 string tmp = f + ".tmp";
226 File.WriteAllText(tmp, reg, new UTF8Encoding(false));
227 File.Move(tmp, f, true);
228 return OverrideState(game) == "set" ? null : "the setting didn't stick";
229 }
230 catch (Exception e) { return e.Message; }
231 }
232
233 private static string CrossOverWine()
234 {
235 foreach (string app in new[] { "/Applications/CrossOver.app", Path.Combine(Dirs.Home, "Applications", "CrossOver.app") })
236 {
237 string w = Path.Combine(app, "Contents", "SharedSupport", "CrossOver", "bin", "wine");
238 if (File.Exists(w)) return w;
239 }
240 return null;
241 }
242
243 public static async Task<string> Start(string game)
244 {
245 string b = BottleOf(game);
246 if (b == null) return "couldn't find the Wine bottle the game is in. Start it from CrossOver, Whisky or your Wine app instead.";
247 string kind = KindOf(b);
248 string steam = new[] { Path.Combine(b, "drive_c", "Program Files (x86)", "Steam", "steam.exe"), Path.Combine(b, "drive_c", "Program Files", "Steam", "steam.exe") }.FirstOrDefault(File.Exists);
249 if (kind == "CrossOver")
250 {
251 string w = CrossOverWine();
252 if (w != null)
253 {
254 try
255 {
256 ProcessStartInfo si = new(w) { UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true };
257 si.ArgumentList.Add("--bottle");
258 si.ArgumentList.Add(Path.GetFileName(b));
259 if (steam != null)
260 {
261 si.ArgumentList.Add(steam);
262 si.ArgumentList.Add("-applaunch");
263 si.ArgumentList.Add(Game.AppId);
264 }
265 else si.ArgumentList.Add(Path.Combine(game, Game.Exe));
266 Process p = Process.Start(si);
267 if (p != null)
268 {
269 _ = p.StandardOutput.ReadToEndAsync();
270 _ = p.StandardError.ReadToEndAsync();
271 await Task.Delay(300);
272 return null;
273 }
274 }
275 catch (Exception) { }
276 }
277 }
278 string open = kind switch { "CrossOver" => "CrossOver", "Whisky" => "Whisky", _ => null };
279 if (open != null)
280 {
281 try
282 {
283 ProcessStartInfo si = new("/usr/bin/open") { UseShellExecute = false };
284 si.ArgumentList.Add("-a");
285 si.ArgumentList.Add(open);
286 Process.Start(si);
287 }
288 catch (Exception) { }
289 return open + " is opening. Start Casualties: Unknown from there (through Steam in that bottle).";
290 }
291 return "start Casualties: Unknown from your Wine app (" + kind + ").";
292 }
293
294 public static string WineVersion(string game)
295 {
296 string kind = KindOf(BottleOf(game));
297 string app = kind switch { "CrossOver" => "/Applications/CrossOver.app", "Whisky" => "/Applications/Whisky.app", _ => null };
298 if (app == null) return kind;
299 try
300 {
301 string plist = File.ReadAllText(Path.Combine(app, "Contents", "Info.plist"));
302 Match m = Regex.Match(plist, "<key>CFBundleShortVersionString</key>\\s*<string>([^<]{1,40})</string>");
303 return kind + (m.Success ? " " + m.Groups[1].Value : "");
304 }
305 catch (Exception) { return kind; }
306 }
307 }
308}