Repository navigation
Expand file tree
/
Copy pathProgram.cs
More file actions
425 lines (393 loc) · 18.2 KB
/
Copy pathProgram.cs
File metadata and controls
425 lines (393 loc) · 18.2 KB
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
using System;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using System.Security.AccessControl;
using System.Security.Principal;
using System.Threading;
using System.Windows.Forms;
using MHelper.Hardware;
namespace MHelper
{
internal static class Program
{
private const string SingleInstanceMutexName = @"Global\M-Helper.SingleInstance";
private const string ActivateEventName = @"Global\M-Helper.Activate";
private const int StdOutputHandle = -11;
private const uint LoadLibrarySearchSystem32 = 0x00000800u;
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool SetDefaultDllDirectories(uint directoryFlags);
[DllImport("kernel32.dll")]
private static extern bool AttachConsole(int dwProcessId);
[DllImport("kernel32.dll")]
private static extern IntPtr GetStdHandle(int nStdHandle);
private static Mutex CreateOrOpenSingleInstanceMutex()
{
var sec = new MutexSecurity();
sec.SetAccessRuleProtection(true, false);
sec.AddAccessRule(new MutexAccessRule(
new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null),
MutexRights.FullControl,
AccessControlType.Allow));
sec.AddAccessRule(new MutexAccessRule(
new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null),
MutexRights.FullControl,
AccessControlType.Allow));
try
{
bool created;
return new Mutex(false, SingleInstanceMutexName, out created, sec);
}
catch
{
try { return Mutex.OpenExisting(SingleInstanceMutexName); }
catch
{
bool localCreated;
return new Mutex(false, @"Local\M-Helper.SingleInstance", out localCreated, sec);
}
}
}
private static EventWaitHandle TryCreateActivateEvent()
{
var evSec = new EventWaitHandleSecurity();
evSec.SetAccessRuleProtection(true, false);
evSec.AddAccessRule(new EventWaitHandleAccessRule(
new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null),
EventWaitHandleRights.FullControl,
AccessControlType.Allow));
evSec.AddAccessRule(new EventWaitHandleAccessRule(
new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null),
EventWaitHandleRights.FullControl,
AccessControlType.Allow));
try
{
bool created;
return new EventWaitHandle(false, EventResetMode.AutoReset, ActivateEventName, out created, evSec);
}
catch
{
try { return EventWaitHandle.OpenExisting(ActivateEventName); }
catch { return null; }
}
}
[STAThread]
private static int Main(string[] args)
{
try { SetDefaultDllDirectories(LoadLibrarySearchSystem32); } catch { }
bool isTrayLaunch = args.Length == 1 && string.Equals(args[0], "--tray", StringComparison.OrdinalIgnoreCase);
if (args.Length > 0 && !isTrayLaunch)
{
IntPtr stdOut = GetStdHandle(StdOutputHandle);
if (stdOut == IntPtr.Zero || stdOut == new IntPtr(-1))
{
AttachConsole(-1);
}
return RunCli(args);
}
using (Mutex singleInstance = CreateOrOpenSingleInstanceMutex())
{
bool ownsMutex = false;
try
{
try { ownsMutex = singleInstance.WaitOne(0, false); }
catch (AbandonedMutexException) { ownsMutex = true; }
if (!ownsMutex)
{
try
{
using (var ev = EventWaitHandle.OpenExisting(ActivateEventName, EventWaitHandleRights.Modify))
ev.Set();
}
catch { }
return 0;
}
using (EventWaitHandle activateEvent = TryCreateActivateEvent())
using (var settings = AppSettings.Load())
{
UiFonts.SetLargeText(settings.GetLargeText());
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
string acpiError;
using (MsiAcpi acpi = MsiAcpi.TryOpen(out acpiError))
using (var smu = new RyzenSmuController())
using (var rgb = new KeyboardRgbController())
{
bool startHidden = isTrayLaunch;
Application.Run(new MainForm(acpi, smu, rgb, settings, activateEvent, acpiError, startHidden));
}
}
return 0;
}
finally
{
if (ownsMutex)
{
try { singleInstance.ReleaseMutex(); } catch { }
}
}
}
}
private static void PrintUsage(TextWriter writer)
{
writer.WriteLine("Usage:");
writer.WriteLine(" M-Helper.exe Launch tray UI");
writer.WriteLine(" M-Helper.exe --tray Launch minimized to tray");
writer.WriteLine(" M-Helper.exe --status Print hardware status (read-only)");
writer.WriteLine(" M-Helper.exe --report [<file.txt>] Save a hardware report .txt (read-only; no file = Save dialog)");
writer.WriteLine(" M-Helper.exe --battery <50-100> Set EC battery charge limit");
writer.WriteLine(" M-Helper.exe --mode <eco|balanced|extreme>");
writer.WriteLine(" M-Helper.exe --coolerboost <on|off>");
writer.WriteLine(" M-Helper.exe --rgb <off|static|breath|cycle|wave> [--color=#RRGGBB] [--brightness=0..100] [--speed=slow|medium|fast]");
writer.WriteLine(" M-Helper.exe --ryzen [--co=-30..0] [--tdp=15..115] [--temp=65..95]");
}
private static int RunCli(string[] args)
{
string cmd = args[0].ToLowerInvariant();
if (cmd == "--help" || cmd == "-h" || cmd == "/?")
{
PrintUsage(Console.Out);
return 0;
}
if (cmd == "--rgb")
{
return RunRgbCli(args);
}
string err;
using (MsiAcpi acpi = MsiAcpi.TryOpen(out err))
using (var smu = new RyzenSmuController())
using (var rgb = new KeyboardRgbController())
{
// --report works even when MSI ACPI-WMI is missing: that is exactly the unsupported-model case.
if (cmd == "--report")
{
if (args.Length == 2)
{
try
{
HardwareReport.SaveToPath(args[1], acpi, err, smu, rgb);
Console.WriteLine("Hardware report saved to " + Path.GetFullPath(args[1]));
return 0;
}
catch (Exception ex)
{
Console.Error.WriteLine("ERROR: Could not save report: " + ex.Message);
return 1;
}
}
if (args.Length == 1)
{
Application.EnableVisualStyles();
HardwareReport.SaveWithDialog(null, acpi, err, smu, rgb);
return 0;
}
Console.Error.WriteLine("ERROR: Usage: M-Helper.exe --report [<file.txt>]");
return 2;
}
if (acpi == null)
{
Console.Error.WriteLine("ERROR: " + err);
return 1;
}
if ((cmd == "--status" || cmd == "-s") && args.Length == 1)
{
HardwareReport.WriteStatus(Console.Out, acpi, smu, rgb);
return 0;
}
if (cmd == "--battery")
{
int pct;
if (args.Length != 2 || !int.TryParse(args[1], out pct) || pct < 50 || pct > 100)
{
Console.Error.WriteLine("ERROR: Battery limit must be an integer between 50 and 100.");
return 2;
}
bool ok = acpi.SetChargeLimit(pct);
if (!ok) { Console.Error.WriteLine("ERROR: Failed to set battery charge limit."); return 1; }
Console.WriteLine("Battery charge limit set to " + pct + "%.");
return 0;
}
if (cmd == "--mode")
{
if (args.Length != 2)
{
Console.Error.WriteLine("ERROR: Mode must be: eco | balanced | extreme");
return 2;
}
ShiftMode m = ShiftMode.Unknown;
switch (args[1].ToLowerInvariant())
{
case "eco": m = ShiftMode.Eco; break;
case "balanced": m = ShiftMode.Balanced; break;
case "extreme": case "turbo": m = ShiftMode.Extreme; break;
}
if (m == ShiftMode.Unknown)
{
Console.Error.WriteLine("ERROR: Mode must be: eco | balanced | extreme");
return 2;
}
bool ok = acpi.SetShiftMode(m);
if (!ok) { Console.Error.WriteLine("ERROR: Failed to set performance mode."); return 1; }
Console.WriteLine("Performance mode set to " + m + ".");
return 0;
}
if (cmd == "--coolerboost")
{
if (args.Length != 2)
{
Console.Error.WriteLine("ERROR: --coolerboost requires 'on' or 'off'.");
return 2;
}
string val = args[1].ToLowerInvariant();
if (val != "on" && val != "1" && val != "off" && val != "0")
{
Console.Error.WriteLine("ERROR: --coolerboost value must be 'on' or 'off'.");
return 2;
}
bool on = val == "on" || val == "1";
bool ok = acpi.SetCoolerBoost(on);
if (!ok) { Console.Error.WriteLine("ERROR: Failed to toggle Cooler Boost."); return 1; }
Console.WriteLine("Cooler Boost " + (on ? "ON" : "OFF") + ".");
return 0;
}
if (cmd == "--ryzen")
{
int? co = null, tdp = null, temp = null;
for (int i = 1; i < args.Length; i++)
{
string a = args[i];
int v;
if (a.StartsWith("--co=", StringComparison.OrdinalIgnoreCase))
{
if (!int.TryParse(a.Substring(5), out v) || v < RyzenSmuController.MinCo || v > RyzenSmuController.MaxCo)
{
Console.Error.WriteLine("ERROR: --co must be an integer between {0} and {1}.", RyzenSmuController.MinCo, RyzenSmuController.MaxCo);
return 2;
}
co = v;
}
else if (a.StartsWith("--tdp=", StringComparison.OrdinalIgnoreCase))
{
if (!int.TryParse(a.Substring(6), out v) || v < RyzenSmuController.MinTdpW || v > RyzenSmuController.MaxTdpW)
{
Console.Error.WriteLine("ERROR: --tdp must be an integer between {0} and {1} (Watts).", RyzenSmuController.MinTdpW, RyzenSmuController.MaxTdpW);
return 2;
}
tdp = v;
}
else if (a.StartsWith("--temp=", StringComparison.OrdinalIgnoreCase))
{
if (!int.TryParse(a.Substring(7), out v) || v < RyzenSmuController.MinTempC || v > RyzenSmuController.MaxTempC)
{
Console.Error.WriteLine("ERROR: --temp must be an integer between {0} and {1} (Celsius).", RyzenSmuController.MinTempC, RyzenSmuController.MaxTempC);
return 2;
}
temp = v;
}
else
{
Console.Error.WriteLine("ERROR: Unrecognized --ryzen option '" + a + "'.");
return 2;
}
}
if (!co.HasValue && !tdp.HasValue && !temp.HasValue)
{
Console.Error.WriteLine("ERROR: --ryzen requires at least one of --co=<-30..0>, --tdp=<15..115>, or --temp=<65..95>.");
return 2;
}
RyzenApplyResult res = smu.ApplyTuning(co, tdp, temp);
if (!res.Ok)
{
Console.Error.WriteLine("ERROR: " + res.Summary);
return 1;
}
Console.WriteLine("Applied: " + res.Summary);
return 0;
}
Console.Error.WriteLine("ERROR: Unknown or incomplete command '" + string.Join(" ", args) + "'.");
PrintUsage(Console.Error);
return 2;
}
}
private static int RunRgbCli(string[] args)
{
if (args.Length < 2)
{
Console.Error.WriteLine("ERROR: --rgb requires mode: off | static | breath | cycle | wave");
return 2;
}
KeyboardRgbMode mode;
switch (args[1].ToLowerInvariant())
{
case "off": mode = KeyboardRgbMode.Off; break;
case "static": mode = KeyboardRgbMode.Static; break;
case "breath": case "breathing": mode = KeyboardRgbMode.Breathing; break;
case "cycle": mode = KeyboardRgbMode.Cycle; break;
case "wave": mode = KeyboardRgbMode.Wave; break;
default:
Console.Error.WriteLine("ERROR: Unknown --rgb mode '" + args[1] + "'. Use: off | static | breath | cycle | wave");
return 2;
}
Color color = Color.FromArgb(0xE1, 0x1D, 0x48);
int brightness = 100;
KeyboardRgbSpeed speed = KeyboardRgbSpeed.Medium;
for (int i = 2; i < args.Length; i++)
{
string a = args[i];
if (a.StartsWith("--color=", StringComparison.OrdinalIgnoreCase))
{
string hex = a.Substring(8).TrimStart('#');
int rgbInt;
if (hex.Length != 6 || !int.TryParse(hex, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out rgbInt))
{
Console.Error.WriteLine("ERROR: --color must be a 6-digit hex code like #FF0044.");
return 2;
}
color = Color.FromArgb((rgbInt >> 16) & 0xFF, (rgbInt >> 8) & 0xFF, rgbInt & 0xFF);
}
else if (a.StartsWith("--brightness=", StringComparison.OrdinalIgnoreCase))
{
if (!int.TryParse(a.Substring(13), out brightness) || brightness < 0 || brightness > 100)
{
Console.Error.WriteLine("ERROR: --brightness must be an integer between 0 and 100.");
return 2;
}
}
else if (a.StartsWith("--speed=", StringComparison.OrdinalIgnoreCase))
{
switch (a.Substring(8).ToLowerInvariant())
{
case "slow": speed = KeyboardRgbSpeed.Slow; break;
case "medium": case "med": speed = KeyboardRgbSpeed.Medium; break;
case "fast": speed = KeyboardRgbSpeed.Fast; break;
default:
Console.Error.WriteLine("ERROR: --speed must be: slow | medium | fast");
return 2;
}
}
else
{
Console.Error.WriteLine("ERROR: Unrecognized --rgb option '" + a + "'.");
return 2;
}
}
using (var rgb = new KeyboardRgbController())
{
if (!rgb.IsSupported)
{
Console.Error.WriteLine("ERROR: No supported MSI Mystic Light USB HID keyboard detected.");
return 1;
}
string err;
if (!rgb.Apply(mode, color, brightness, speed, true, out err))
{
Console.Error.WriteLine("ERROR: " + err);
return 1;
}
Console.WriteLine("Keyboard RGB applied: {0} ({1}% brightness) on {2}.", mode, brightness, rgb.DeviceName);
return 0;
}
}
}
}