-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathProgram.cs
More file actions
454 lines (418 loc) · 16.5 KB
/
Program.cs
File metadata and controls
454 lines (418 loc) · 16.5 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
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
452
453
454
using System.IO.Pipes;
using System.Net.Sockets;
using System.Text;
using Avalonia;
using Microsoft.Extensions.DependencyInjection;
using LoupixDeck.Services;
using LoupixDeck.Utils;
namespace LoupixDeck;
sealed class Program
{
#if !WINDOWS
private const string SocketPath = "/tmp/loupixdeck_app.sock";
private static Socket _listenerSocket;
#else
private const string MutexName = "LoupixDeck_Mutex";
private const string PipeName = "LoupixDeck_Pipe";
private static bool _mutexOwned;
private static Mutex _instanceMutex;
#endif
/// <summary>Set by App.axaml.cs after the DI container is built so the
/// CLI command listener can resolve ICommandService at runtime.</summary>
public static IServiceProvider AppServices { get; set; }
[STAThread]
public static void Main(string[] args)
{
InstallCrashLogger(args);
RedirectConsoleToLogFile();
Console.WriteLine($"=== LoupixDeck Main {DateTime.Now:yyyy-MM-dd HH:mm:ss} args=[{string.Join(' ', args)}] ===");
#if !WINDOWS
if (File.Exists(SocketPath))
{
// Another instance is (probably) running. If the user passed CLI
// args, forward them as a command and exit; otherwise just bail.
if (args.Length > 0)
{
ForwardCliToUds(args);
return;
}
try
{
using var probe = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified);
probe.Connect(new UnixDomainSocketEndPoint(SocketPath));
Console.WriteLine("Already running.");
return;
}
catch (SocketException)
{
// Stale socket file (previous instance crashed) — clean up and continue.
File.Delete(SocketPath);
}
}
_listenerSocket = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified);
_listenerSocket.Bind(new UnixDomainSocketEndPoint(SocketPath));
_listenerSocket.Listen(4);
AppDomain.CurrentDomain.ProcessExit += (_, _) =>
{
_listenerSocket.Close();
try { File.Delete(SocketPath); } catch { /* ignore */ }
};
_ = Task.Run(AcceptUdsLoop);
#else
_instanceMutex = new Mutex(true, MutexName, out _mutexOwned);
if (!_mutexOwned)
{
if (args.Length > 0)
{
ForwardCliToPipe(args);
return;
}
Console.WriteLine("Already running.");
return;
}
_ = Task.Run(AcceptPipeLoop);
#endif
BuildAvaloniaApp()
.StartWithClassicDesktopLifetime(args);
}
// ──────── CLI channel: client side ────────
#if !WINDOWS
private static void ForwardCliToUds(string[] args)
{
try
{
using var client = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified);
client.Connect(new UnixDomainSocketEndPoint(SocketPath));
client.Send(Encoding.UTF8.GetBytes(string.Join(' ', args)));
var buf = new byte[4096];
var n = client.Receive(buf);
Console.WriteLine(Encoding.UTF8.GetString(buf, 0, n));
}
catch (Exception ex)
{
Console.WriteLine($"CLI error: {ex.Message}");
Environment.Exit(1);
}
}
private static void AcceptUdsLoop()
{
try
{
while (true)
{
var client = _listenerSocket.Accept();
_ = Task.Run(() => HandleUdsClient(client));
}
}
catch (Exception ex)
{
Console.WriteLine($"[CLI] UDS accept loop ended: {ex.Message}");
}
}
private static void HandleUdsClient(Socket client)
{
try
{
var buf = new byte[4096];
var n = client.Receive(buf);
var raw = Encoding.UTF8.GetString(buf, 0, n).Trim();
var response = CommandChannel.Dispatch(raw);
client.Send(Encoding.UTF8.GetBytes(response));
}
catch (Exception ex)
{
Console.WriteLine($"[CLI] UDS handle failed: {ex.Message}");
}
finally
{
try { client.Close(); } catch { }
}
}
#else
private static void ForwardCliToPipe(string[] args)
{
try
{
using var client = new NamedPipeClientStream(".", PipeName, PipeDirection.InOut);
client.Connect(2000);
var bytes = Encoding.UTF8.GetBytes(string.Join(' ', args));
client.Write(bytes, 0, bytes.Length);
client.WaitForPipeDrain();
var buf = new byte[4096];
var n = client.Read(buf, 0, buf.Length);
Console.WriteLine(Encoding.UTF8.GetString(buf, 0, n));
}
catch (Exception ex)
{
Console.WriteLine($"CLI error: {ex.Message}");
Environment.Exit(1);
}
}
private static void AcceptPipeLoop()
{
while (true)
{
try
{
var server = new NamedPipeServerStream(PipeName, PipeDirection.InOut, 4,
PipeTransmissionMode.Byte, PipeOptions.Asynchronous);
server.WaitForConnection();
_ = Task.Run(() => HandlePipeClient(server));
}
catch (Exception ex)
{
Console.WriteLine($"[CLI] Pipe accept loop error: {ex.Message}");
Thread.Sleep(250);
}
}
}
private static void HandlePipeClient(NamedPipeServerStream pipe)
{
try
{
var buf = new byte[4096];
var n = pipe.Read(buf, 0, buf.Length);
var raw = Encoding.UTF8.GetString(buf, 0, n).Trim();
var response = CommandChannel.Dispatch(raw);
var rb = Encoding.UTF8.GetBytes(response);
pipe.Write(rb, 0, rb.Length);
pipe.WaitForPipeDrain();
}
catch (Exception ex)
{
Console.WriteLine($"[CLI] Pipe handle failed: {ex.Message}");
}
finally
{
try { pipe.Dispose(); } catch { }
}
}
#endif
#if WINDOWS
private const int AttachParentProcess = -1;
[System.Runtime.InteropServices.DllImport("kernel32.dll", SetLastError = true)]
[return: System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.Bool)]
private static extern bool AttachConsole(int dwProcessId);
[System.Runtime.InteropServices.DllImport("kernel32.dll", SetLastError = true)]
[return: System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.Bool)]
private static extern bool AllocConsole();
#endif
/// <summary>
/// Debug builds send console output to the terminal for live diagnostics;
/// release builds redirect it to a log file. Because this is a WinExe (GUI
/// subsystem) there is no console on Windows by default, so the debug path
/// attaches to the launching terminal — or opens a fresh console as a
/// fallback (e.g. when started from Explorer).
/// </summary>
private static void RedirectConsoleToLogFile()
{
#if DEBUG
#if WINDOWS
try
{
// AttachConsole/AllocConsole both fail (returning false) when a
// console is already shared from `dotnet run`; that's fine — we just
// rebind to whatever console we end up with so AutoFlush is on.
if (!AttachConsole(AttachParentProcess))
AllocConsole();
var stdout = new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = true };
Console.SetOut(stdout);
Console.SetError(stdout);
try { Console.OutputEncoding = Encoding.UTF8; } catch { /* console may reject */ }
}
catch
{
// best-effort — leave the default stdout in place
}
#endif
// Non-Windows debug builds already have stdout wired to the terminal.
AppDomain.CurrentDomain.UnhandledException += (_, e) =>
Console.WriteLine($"UnhandledException: {e.ExceptionObject}");
#else
try
{
var home = Environment.GetEnvironmentVariable("HOME")
?? Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
var dir = Path.Combine(home, ".config", "LoupixDeck");
Directory.CreateDirectory(dir);
var path = Path.Combine(dir, "loupixdeck-startup.log");
var stream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read);
var writer = new StreamWriter(stream) { AutoFlush = true };
Console.SetOut(writer);
Console.SetError(writer);
AppDomain.CurrentDomain.UnhandledException += (_, e) =>
{
Console.WriteLine($"UnhandledException: {e.ExceptionObject}");
writer.Flush();
};
}
catch
{
// best-effort
}
#endif
}
// ──────── Crash diagnostics ────────
[ThreadStatic] private static bool _inCrashLog;
private static readonly object _crashLogGate = new();
/// <summary>
/// Absolute path of the crash log. Written into the user config dir
/// (~/.config/LoupixDeck), the same writable location as the startup log —
/// next to the executable would fail for installed release builds (e.g. a
/// read-only Program Files).
/// </summary>
private static string CrashLogPath()
{
try
{
var home = Environment.GetEnvironmentVariable("HOME")
?? Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
var dir = Path.Combine(home, ".config", "LoupixDeck");
Directory.CreateDirectory(dir);
return Path.Combine(dir, "crash.log");
}
catch { return "crash.log"; }
}
/// <summary>
/// Installs process-wide handlers that record unhandled MANAGED exceptions (on any
/// thread) to <c>crash.log</c> with a full stack trace. This catches background-thread
/// failures (e.g. "Collection was modified", NullReferenceException in a render/timer
/// path) that otherwise terminate the process with no visible reason.
///
/// OPT-IN: disabled by default so normal release users get no crash.log and no
/// handler overhead. Enable with the <c>--crashlog</c> command-line switch when
/// diagnosing a crash.
///
/// NOTE: a pure NATIVE access violation (e.g. inside Skia) fast-fails the runtime and
/// is NOT delivered here — for that, run with the .NET minidump env vars
/// (DOTNET_DbgEnableMiniDump=1, DOTNET_DbgMiniDumpType=2, DOTNET_DbgMiniDumpName=…).
/// The two are complementary: this for managed crashes, the dump for native ones.
///
/// Pass <c>--firstchance</c> to also log EVERY thrown exception (very noisy — useful to
/// see the last exception before a crash). It implies <c>--crashlog</c>.
/// </summary>
private static void InstallCrashLogger(string[] args)
{
var firstChance = args.Any(a => a.Equals("--firstchance", StringComparison.OrdinalIgnoreCase));
var enabled = firstChance
|| args.Any(a => a.Equals("--crashlog", StringComparison.OrdinalIgnoreCase));
if (!enabled)
return;
AppDomain.CurrentDomain.UnhandledException += (_, e) =>
WriteCrash("AppDomain.UnhandledException", e.ExceptionObject, e.IsTerminating);
TaskScheduler.UnobservedTaskException += (_, e) =>
{
WriteCrash("TaskScheduler.UnobservedTaskException", e.Exception, false);
e.SetObserved();
};
if (firstChance)
{
AppDomain.CurrentDomain.FirstChanceException += (_, e) =>
WriteCrash("FirstChanceException", e.Exception, false);
}
Console.WriteLine($"[CrashLogger] installed → {CrashLogPath()}");
}
private static void WriteCrash(string source, object error, bool terminating)
{
// Guard against re-entrancy: file IO below can itself raise an exception, which
// would re-trigger the FirstChance handler and recurse.
if (_inCrashLog) return;
_inCrashLog = true;
try
{
var sb = new StringBuilder();
sb.AppendLine("================ CRASH ================");
sb.AppendLine($"Time: {DateTime.Now:yyyy-MM-dd HH:mm:ss.fff}");
sb.AppendLine($"Source: {source}");
sb.AppendLine($"Terminating: {terminating}");
sb.AppendLine($"Thread: {Environment.CurrentManagedThreadId} '{Thread.CurrentThread.Name}'");
sb.AppendLine($"Detail: {error}");
sb.AppendLine("======================================");
try
{
lock (_crashLogGate)
File.AppendAllText(CrashLogPath(), sb.ToString());
}
catch { /* disk best-effort */ }
try { Console.WriteLine(sb.ToString()); } catch { /* console best-effort */ }
}
finally
{
_inCrashLog = false;
}
}
public static AppBuilder BuildAvaloniaApp()
=> AppBuilder.Configure<App>()
.UsePlatformDetect()
.WithInterFont()
.LogToTrace();
}
/// <summary>
/// Maps a raw CLI string to a System.* command and dispatches it via
/// ICommandService on the UI thread. Returns a short status reply to the
/// client (printed by the CLI invocation).
/// </summary>
internal static class CommandChannel
{
public static string Dispatch(string raw)
{
if (string.IsNullOrWhiteSpace(raw)) return "ERROR: empty command";
Console.WriteLine($"[CLI] received: {raw}");
var head = raw.Split(' ', 2)[0];
var lower = head.ToLowerInvariant();
string command;
// page<N> / rotarypage<N>
if (lower.StartsWith("page") && int.TryParse(lower.AsSpan(4), out var tp))
command = $"System.GotoPage({tp})";
else if (lower.StartsWith("rotarypage") && int.TryParse(lower.AsSpan(10), out var rp))
command = $"System.GotoRotaryPage({rp})";
// Fork-CLI compat: `updatebutton 6 text=Hi backColor=Red` →
// `System.UpdateButton(6,text=Hi,backColor=Red)`.
else if (lower == "updatebutton" && raw.Length > head.Length)
{
var rest = raw.Substring(head.Length).Trim();
command = $"System.UpdateButton({rest.Replace(' ', ',')})";
}
// Fork-CLI compat: `removelayer 6 MyImage` → `System.RemoveLayer(6,MyImage)`.
else if (lower == "removelayer" && raw.Length > head.Length)
{
var rest = raw.Substring(head.Length).Trim();
command = $"System.RemoveLayer({rest.Replace(' ', ',')})";
}
else
{
command = lower switch
{
"off" => "System.DeviceOff",
"on" => "System.DeviceOn",
"toggle-device" or "on-off" => "System.DeviceToggle",
"wakeup" => "System.DeviceWakeup",
"nextpage" => "System.NextPage",
"previouspage" => "System.PreviousPage",
"nextrotarypage" => "System.NextRotaryPage",
"previousrotarypage" => "System.PreviousRotaryPage",
"show" or "hide" or "toggle" => "System.ToggleWindow",
"quit" => "__quit__",
_ => raw // assume the user already passed a full System.* command
};
}
if (command == "__quit__")
{
Avalonia.Threading.Dispatcher.UIThread.Post(() =>
{
if (WindowHelper.GetMainWindow() is Views.MainWindow mw) mw.QuitApplication();
else Environment.Exit(0);
});
return "OK: quitting";
}
var svc = Program.AppServices?.GetService<ICommandService>();
if (svc == null) return "ERROR: app not ready yet";
// Fire on the UI thread so we don't block the listener thread.
Avalonia.Threading.Dispatcher.UIThread.Post(async () =>
{
try { await svc.ExecuteCommand(command, LoupixDeck.PluginSdk.ButtonTargets.None); }
catch (Exception ex) { Console.WriteLine($"[CLI] dispatch failed: {ex.Message}"); }
});
return $"OK: {command}";
}
}