casualexpiesource

cu-trainer/Ultra Paradise Application/src/Theme.cs

454 lines · 19.9 KB · plain text · download

1using System;
2using System.Collections.Generic;
3using System.Drawing;
4using System.Drawing.Drawing2D;
5using System.Drawing.Imaging;
6using System.Globalization;
7using System.IO;
8using System.Text;
9using System.Windows.Forms;
10
11namespace UltraParadise
12{
13 internal static class Theme
14 {
15 public static Color Back, Side, Panel, Hover, Line, Edge, Text, Dim, Orange, On, Bad, Warn;
16 public static Color Bright, Soft, Faint, Thumb, Scroll, Sunk, Grid, OnFill, OnEdge, AccentHover, OnAccent;
17 public static bool Light;
18 public static float Scale = 1f, UiScale = 1f;
19 public static string FontName;
20 public static Image BgImage;
21 public static string BgFit = "cover", OverlayCorner = "top-left";
22 public static int BgOpacity = 30, OverlayOpacity = 93, OverlaySize = 100;
23 public static bool BannerArt = true;
24 public static event Action<Color[]> Changed;
25
26 public static readonly Dictionary<string, string> Values = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
27 public static readonly string[] ColorKeys = { "accent", "background", "sidebar", "panel", "line", "text", "dim", "good", "warn", "bad" };
28 public static readonly string[] ColorNames = { "Accent", "Background", "Sidebar and header", "Panels and boxes", "Lines and borders", "Text", "Dim text", "Good / On", "Warning", "Bad / Error" };
29 public static readonly string[] PresetIds = { "dark", "light", "midnight", "contrast", "paradise", "system" };
30 public static readonly string[] PresetNames = { "Dark", "Light", "Midnight", "High Contrast", "Paradise", "Follow Windows" };
31 public static readonly string[] Fits = { "cover", "fit", "stretch", "center", "tile" };
32 public static readonly string[] Corners = { "top-left", "top-right", "bottom-left", "bottom-right" };
33 private static readonly string[] OtherKeys = { "base", "name", "font", "scale", "image", "image.opacity", "image.fit", "banner", "overlay.corner", "overlay.opacity" };
34
35 private static Bitmap cache;
36 private static Size cacheSize;
37
38 static Theme() { Apply(); }
39
40 public static string Folder { get { return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "UltraParadise"); } }
41 public static string FilePath { get { return Path.Combine(Folder, "theme.ini"); } }
42
43 private static Dictionary<string, string> Preset(string id)
44 {
45 string[] v;
46 switch (id)
47 {
48 case "light": v = new[] { "e8650a", "f3f3f1", "e6e6e3", "ffffff", "d4d4cf", "1e1e20", "6b6b70", "2f9e44", "b86e00", "d63b2f" }; break;
49 case "midnight": v = new[] { "ff7a18", "000000", "000000", "0c0c0e", "1e1e23", "e6e6ea", "6c6c75", "84d65c", "ffb03c", "e85448" }; break;
50 case "contrast": v = new[] { "ffd400", "000000", "000000", "000000", "ffffff", "ffffff", "d0d0d0", "00ff66", "ffd400", "ff4040" }; break;
51 case "paradise": v = new[] { "ff5fa2", "1a1320", "140f19", "241a2c", "3a2c46", "f0e6f5", "9a88a8", "7fe0a0", "ffc060", "ff5a6a" }; break;
52 default: v = new[] { "ff7a18", "141415", "0f0f10", "1c1c1e", "2e2e32", "e2e2de", "7a7a7e", "84d65c", "ffb03c", "e85448" }; break;
53 }
54 Dictionary<string, string> d = new Dictionary<string, string>();
55 for (int i = 0; i < ColorKeys.Length; i++) d[ColorKeys[i]] = "#" + v[i];
56 return d;
57 }
58
59 public static bool SystemLight()
60 {
61 try
62 {
63 using (Microsoft.Win32.RegistryKey k = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize"))
64 {
65 object o = k != null ? k.GetValue("AppsUseLightTheme") : null;
66 return o is int && (int)o == 1;
67 }
68 }
69 catch (Exception) { return false; }
70 }
71
72 public static string Base
73 {
74 get
75 {
76 string b;
77 if (!Values.TryGetValue("base", out b)) return "dark";
78 b = b.Trim().ToLowerInvariant();
79 return Array.IndexOf(PresetIds, b) >= 0 ? b : "dark";
80 }
81 }
82
83 private static string Resolved { get { string b = Base; return b == "system" ? (SystemLight() ? "light" : "dark") : b; } }
84
85 public static string PresetName
86 {
87 get
88 {
89 int i = Array.IndexOf(PresetIds, Base);
90 bool custom = false;
91 foreach (string k in ColorKeys) if (Values.ContainsKey(k)) custom = true;
92 return (i >= 0 ? PresetNames[i] : "Dark") + (custom ? " (customised)" : "");
93 }
94 }
95
96 public static bool TryHex(string s, out Color c)
97 {
98 c = Color.Empty;
99 if (s == null) return false;
100 s = s.Trim().TrimStart('#');
101 if (s.Length == 3) s = new string(new[] { s[0], s[0], s[1], s[1], s[2], s[2] });
102 int v;
103 if (s.Length != 6 || !int.TryParse(s, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out v)) return false;
104 c = Color.FromArgb((v >> 16) & 255, (v >> 8) & 255, v & 255);
105 return true;
106 }
107
108 public static string Hex(Color c) { return "#" + c.R.ToString("x2") + c.G.ToString("x2") + c.B.ToString("x2"); }
109
110 public static Color ColorOf(string key)
111 {
112 string v;
113 Color c;
114 if (Values.TryGetValue(key, out v) && TryHex(v, out c)) return c;
115 TryHex(Preset(Resolved)[key], out c);
116 return c;
117 }
118
119 public static Color Mix(Color a, Color b, double t)
120 {
121 return Color.FromArgb((int)(a.R + (b.R - a.R) * t), (int)(a.G + (b.G - a.G) * t), (int)(a.B + (b.B - a.B) * t));
122 }
123
124 public static double Lum(Color c) { return (0.2126 * c.R + 0.7152 * c.G + 0.0722 * c.B) / 255.0; }
125
126 private static int Int(string k, int def, int min, int max)
127 {
128 string v;
129 int i;
130 if (!Values.TryGetValue(k, out v) || !int.TryParse(v.Trim().TrimEnd('%'), NumberStyles.Integer, CultureInfo.InvariantCulture, out i)) return def;
131 return Math.Max(min, Math.Min(max, i));
132 }
133
134 private static string Pick(string k, string[] allowed, string def)
135 {
136 string v;
137 if (!Values.TryGetValue(k, out v)) return def;
138 v = v.Trim().ToLowerInvariant();
139 return Array.IndexOf(allowed, v) >= 0 ? v : def;
140 }
141
142 public static void Apply()
143 {
144 Orange = ColorOf("accent");
145 Back = ColorOf("background");
146 Side = ColorOf("sidebar");
147 Panel = ColorOf("panel");
148 Line = ColorOf("line");
149 Text = ColorOf("text");
150 Dim = ColorOf("dim");
151 On = ColorOf("good");
152 Warn = ColorOf("warn");
153 Bad = ColorOf("bad");
154 Light = Lum(Back) > 0.5;
155 Hover = Mix(Panel, Text, Light ? 0.07 : 0.05);
156 Edge = Mix(Line, Text, 0.18);
157 Bright = Light ? Mix(Text, Color.Black, 0.5) : Mix(Text, Color.White, 0.6);
158 Soft = Mix(Text, Back, 0.22);
159 Faint = Mix(Dim, Back, 0.35);
160 Thumb = Mix(Panel, Text, 0.05);
161 Scroll = Mix(Back, Text, 0.22);
162 Sunk = Mix(Back, Panel, 0.45);
163 Grid = Mix(Back, Line, 0.5);
164 OnFill = Mix(Panel, On, 0.13);
165 OnEdge = Mix(Panel, On, 0.4);
166 AccentHover = Mix(Orange, Light ? Color.Black : Color.White, 0.15);
167 OnAccent = Lum(Orange) > 0.45 ? Color.FromArgb(20, 20, 21) : Color.White;
168
169 string f;
170 FontName = Values.TryGetValue("font", out f) && f.Trim().Length > 0 ? f.Trim() : null;
171 if (FontName != null) { try { using (FontFamily ff = new FontFamily(FontName)) { } } catch (Exception) { FontName = null; } }
172 UiScale = Int("scale", 100, 80, 160) / 100f;
173 BgOpacity = Int("image.opacity", 30, 0, 100);
174 BgFit = Pick("image.fit", Fits, "cover");
175 BannerArt = Pick("banner", new[] { "art", "plain" }, "art") == "art";
176 OverlayCorner = Pick("overlay.corner", Corners, "top-left");
177 OverlayOpacity = Int("overlay.opacity", 93, 30, 100);
178 OverlaySize = Int("overlay.size", 100, 60, 160);
179
180 string img;
181 Image old = BgImage;
182 BgImage = Values.TryGetValue("image", out img) ? LoadImage(img.Trim()) : null;
183 if (old != null && old != BgImage) old.Dispose();
184 if (cache != null) { cache.Dispose(); cache = null; }
185 }
186
187 private static Image LoadImage(string path)
188 {
189 try
190 {
191 if (path.Length == 0 || !File.Exists(path) || new FileInfo(path).Length > 40L * 1024 * 1024) return null;
192 byte[] b = File.ReadAllBytes(path);
193 using (MemoryStream ms = new MemoryStream(b))
194 using (Image im = Image.FromStream(ms))
195 return new Bitmap(im);
196 }
197 catch (Exception) { return null; }
198 }
199
200 public static void Load()
201 {
202 Values.Clear();
203 try
204 {
205 if (File.Exists(FilePath)) Parse(File.ReadAllLines(FilePath), Values);
206 }
207 catch (Exception) { }
208 Apply();
209 }
210
211 public static void Parse(string[] lines, Dictionary<string, string> into)
212 {
213 foreach (string raw in lines)
214 {
215 string l = raw;
216 int hash = l.IndexOf(" #", StringComparison.Ordinal);
217 if (hash >= 0) l = l.Substring(0, hash);
218 l = l.Trim();
219 if (l.Length == 0 || l[0] == '#' || l[0] == ';' || l[0] == '[') continue;
220 int eq = l.IndexOf('=');
221 if (eq <= 0) continue;
222 string k = l.Substring(0, eq).Trim().ToLowerInvariant(), v = l.Substring(eq + 1).Trim();
223 if (Array.IndexOf(ColorKeys, k) < 0 && Array.IndexOf(OtherKeys, k) < 0) continue;
224 if (v.Length > 400) continue;
225 into[k] = v;
226 }
227 }
228
229 public static string Serialize()
230 {
231 StringBuilder sb = new StringBuilder();
232 sb.AppendLine("# Ultra Paradise CU:Trainer theme");
233 sb.AppendLine("# Edit this file and click Reload Theme File in the Appearance tab. The same file works in the Windows, Linux and Mac trainers.");
234 sb.AppendLine("#");
235 sb.AppendLine("# base dark | light | midnight | contrast | paradise | system (the preset everything starts from)");
236 sb.AppendLine("# accent, background, sidebar, panel, line, text, dim, good, warn, bad colours as #rrggbb (leave one out to use the preset's)");
237 sb.AppendLine("# font any installed font name scale 80 to 160 (percent, needs a restart)");
238 sb.AppendLine("# image path to a background picture image.opacity 0 to 100 image.fit cover | fit | stretch | center | tile");
239 sb.AppendLine("# banner art | plain overlay.corner top-left | top-right | bottom-left | bottom-right overlay.opacity 30 to 100");
240 sb.AppendLine();
241 sb.AppendLine("base = " + Base);
242 string n;
243 if (Values.TryGetValue("name", out n)) sb.AppendLine("name = " + n);
244 foreach (string k in ColorKeys) { string v; if (Values.TryGetValue(k, out v)) sb.AppendLine(k + " = " + v); }
245 foreach (string k in OtherKeys) { string v; if (k != "base" && k != "name" && Values.TryGetValue(k, out v)) sb.AppendLine(k + " = " + v); }
246 return sb.ToString();
247 }
248
249 public static void Save()
250 {
251 try
252 {
253 Directory.CreateDirectory(Folder);
254 File.WriteAllText(FilePath, Serialize(), new UTF8Encoding(false));
255 }
256 catch (Exception) { }
257 }
258
259 public static void Set(string k, string v)
260 {
261 Color[] before = Tokens();
262 if (v == null) Values.Remove(k); else Values[k] = v;
263 Save();
264 Apply();
265 Fire(before);
266 }
267
268 public static void Fire(Color[] before) { if (Changed != null) Changed(before); }
269
270 public static void ResetAll()
271 {
272 Color[] before = Tokens();
273 Values.Clear();
274 Save();
275 Apply();
276 Fire(before);
277 }
278
279 public static void UsePreset(string id)
280 {
281 Color[] before = Tokens();
282 foreach (string k in ColorKeys) Values.Remove(k);
283 Values["base"] = id;
284 Save();
285 Apply();
286 Fire(before);
287 }
288
289 public static void Reload()
290 {
291 Color[] before = Tokens();
292 Load();
293 Fire(before);
294 }
295
296 public static string Import(string path)
297 {
298 try
299 {
300 Dictionary<string, string> d = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
301 if (new FileInfo(path).Length > 64 * 1024) return "That file is too big to be a theme.";
302 Parse(File.ReadAllLines(path), d);
303 if (d.Count == 0) return "That file has no theme settings in it.";
304 Color[] before = Tokens();
305 Values.Clear();
306 foreach (KeyValuePair<string, string> kv in d) Values[kv.Key] = kv.Value;
307 Save();
308 Apply();
309 Fire(before);
310 return null;
311 }
312 catch (Exception e) { return "Couldn't read that file: " + e.Message; }
313 }
314
315 public static string Export(string path)
316 {
317 try { File.WriteAllText(path, Serialize(), new UTF8Encoding(false)); return null; }
318 catch (Exception e) { return "Couldn't save it: " + e.Message; }
319 }
320
321 public static Color[] Tokens()
322 {
323 return new[] { Back, Side, Panel, Hover, Line, Edge, Text, Dim, Orange, On, Bad, Warn, Bright, Soft, Faint, Thumb, Scroll, Sunk, Grid, OnFill, OnEdge, AccentHover, OnAccent };
324 }
325
326 public static void Recolor(Control c, Color[] before, Color[] after)
327 {
328 c.BackColor = Map(c.BackColor, before, after);
329 c.ForeColor = Map(c.ForeColor, before, after);
330 Button b = c as Button;
331 if (b != null)
332 {
333 b.FlatAppearance.MouseOverBackColor = Map(b.FlatAppearance.MouseOverBackColor, before, after);
334 b.FlatAppearance.MouseDownBackColor = Map(b.FlatAppearance.MouseDownBackColor, before, after);
335 if (!b.FlatAppearance.BorderColor.IsEmpty) b.FlatAppearance.BorderColor = Map(b.FlatAppearance.BorderColor, before, after);
336 }
337 foreach (Control k in c.Controls) Recolor(k, before, after);
338 c.Invalidate();
339 }
340
341 private static Color Map(Color c, Color[] before, Color[] after)
342 {
343 if (c.IsEmpty || c.A == 0) return c;
344 for (int i = 0; i < before.Length; i++) if (before[i].ToArgb() == c.ToArgb()) return after[i];
345 return c;
346 }
347
348 public static Font F(string family, float size) { return F(family, size, FontStyle.Regular); }
349
350 public static Font F(string family, float size, FontStyle style)
351 {
352 float s = size * UiScale;
353 if (FontName != null && family != "Consolas")
354 {
355 FontStyle st = style;
356 if (family.EndsWith("Semibold", StringComparison.Ordinal) || family.EndsWith("Black", StringComparison.Ordinal)) st |= FontStyle.Bold;
357 try { return new Font(FontName, s, st); } catch (Exception) { }
358 }
359 return new Font(family, s, style);
360 }
361
362 public static void PaintBack(Graphics g, Control c)
363 {
364 g.Clear(Back);
365 if (BgImage == null || BgOpacity <= 0) return;
366 Form f = c.FindForm();
367 if (f == null || f.ClientSize.Width <= 0 || f.ClientSize.Height <= 0) return;
368 if (cache == null || cacheSize != f.ClientSize) Build(f.ClientSize);
369 if (cache == null) return;
370 Point off = f.PointToClient(c.PointToScreen(Point.Empty));
371 g.DrawImage(cache, new Rectangle(0, 0, c.Width, c.Height), new Rectangle(off.X, off.Y, c.Width, c.Height), GraphicsUnit.Pixel);
372 }
373
374 private static void Build(Size area)
375 {
376 if (cache != null) { cache.Dispose(); cache = null; }
377 try
378 {
379 Bitmap b = new Bitmap(area.Width, area.Height);
380 using (Graphics g = Graphics.FromImage(b))
381 using (ImageAttributes ia = new ImageAttributes())
382 {
383 g.Clear(Back);
384 g.InterpolationMode = InterpolationMode.HighQualityBicubic;
385 ColorMatrix cm = new ColorMatrix();
386 cm.Matrix33 = BgOpacity / 100f;
387 ia.SetColorMatrix(cm);
388 int iw = BgImage.Width, ih = BgImage.Height;
389 if (BgFit == "tile")
390 {
391 for (int y = 0; y < area.Height; y += ih)
392 for (int x = 0; x < area.Width; x += iw)
393 g.DrawImage(BgImage, new Rectangle(x, y, iw, ih), 0, 0, iw, ih, GraphicsUnit.Pixel, ia);
394 }
395 else
396 {
397 Rectangle dest;
398 if (BgFit == "stretch") dest = new Rectangle(Point.Empty, area);
399 else if (BgFit == "center") dest = new Rectangle((area.Width - iw) / 2, (area.Height - ih) / 2, iw, ih);
400 else
401 {
402 float s = BgFit == "fit" ? Math.Min(area.Width / (float)iw, area.Height / (float)ih) : Math.Max(area.Width / (float)iw, area.Height / (float)ih);
403 int w = (int)(iw * s), h = (int)(ih * s);
404 dest = new Rectangle((area.Width - w) / 2, (area.Height - h) / 2, w, h);
405 }
406 g.DrawImage(BgImage, dest, 0, 0, iw, ih, GraphicsUnit.Pixel, ia);
407 }
408 }
409 cache = b;
410 cacheSize = area;
411 }
412 catch (Exception) { cache = null; }
413 }
414
415 public static GraphicsPath Round(Rectangle r, int rad)
416 {
417 GraphicsPath p = new GraphicsPath();
418 int d = Math.Max(1, Math.Min(rad * 2, Math.Min(r.Width, r.Height)));
419 p.AddArc(r.X, r.Y, d, d, 180, 90);
420 p.AddArc(r.Right - d, r.Y, d, d, 270, 90);
421 p.AddArc(r.Right - d, r.Bottom - d, d, d, 0, 90);
422 p.AddArc(r.X, r.Bottom - d, d, d, 90, 90);
423 p.CloseFigure();
424 return p;
425 }
426
427 public static void FillRound(Graphics g, Color c, Rectangle r, int rad)
428 {
429 SmoothingMode m = g.SmoothingMode;
430 g.SmoothingMode = SmoothingMode.AntiAlias;
431 using (GraphicsPath p = Round(r, rad))
432 using (SolidBrush b = new SolidBrush(c)) g.FillPath(b, p);
433 g.SmoothingMode = m;
434 }
435
436 public static void DrawRound(Graphics g, Color c, Rectangle r, int rad)
437 {
438 SmoothingMode m = g.SmoothingMode;
439 g.SmoothingMode = SmoothingMode.AntiAlias;
440 using (GraphicsPath p = Round(r, rad))
441 using (Pen pen = new Pen(c)) g.DrawPath(pen, p);
442 g.SmoothingMode = m;
443 }
444
445 public static string Spaced(string s)
446 {
447 StringBuilder sb = new StringBuilder();
448 foreach (char c in s) { if (sb.Length > 0) sb.Append(' '); sb.Append(c); }
449 return sb.ToString();
450 }
451
452 public static int S(float v) { return (int)Math.Round(v * Scale); }
453 }
454}