-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
2223 lines (1940 loc) · 82.7 KB
/
Program.cs
File metadata and controls
2223 lines (1940 loc) · 82.7 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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Nikolaos Protopapas. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
using System.CommandLine;
using ServerHub.Config;
using ServerHub.Models;
using ServerHub.Services;
using ServerHub.UI;
using FocusManager = ServerHub.Services.FocusManager;
using ServerHub.Utils;
using ServerHub.Exceptions;
using ServerHub.Commands;
using SharpConsoleUI;
using SharpConsoleUI.Builders;
using SharpConsoleUI.Configuration;
using SharpConsoleUI.Controls;
using SharpConsoleUI.Core;
using SharpConsoleUI.Drivers;
using Spectre.Console;
using YamlDotNet.Serialization;
using YamlDotNet.Serialization.NamingConventions;
namespace ServerHub;
public class Program
{
private static ConsoleWindowSystem? _windowSystem;
private static Window? _mainWindow;
private static ServerHubConfig? _config;
private static readonly Dictionary<string, WidgetData> _widgetDataCache = new();
private static readonly Dictionary<string, Task> _widgetTasks = new();
private static readonly Dictionary<string, PeriodicTimer> _widgetTimers = new();
private static CancellationTokenSource _cancellationTokenSource = new();
private static WidgetRenderer? _renderer;
private static LayoutEngine? _layoutEngine;
private static ScriptExecutor? _executor;
private static WidgetProtocolParser? _parser;
private static int _lastTerminalWidth = 0;
private static bool _isPaused = false;
private static readonly Dictionary<string, DateTime> _lastSuccessfulUpdate = new();
private static readonly Dictionary<string, int> _consecutiveErrors = new();
private static readonly string[] _spinnerFrames = { "◐", "◓", "◑", "◒" };
private static int _spinnerFrame = 0;
private static readonly Dictionary<string, bool> _isRefreshing = new();
private static FocusManager? _focusManager;
private static readonly Dictionary<string, WidgetData> _fullWidgetData = new();
private static string? _openModalWidgetId = null;
private static WidgetRefreshService? _refreshService;
private static bool _devMode = false;
private static string? _configPath;
private static DateTime _lastConfigLoadTime = DateTime.MinValue;
private static CommandPaletteService? _commandPaletteService;
private static StatusBarManager? _statusBarManager;
private static int _initialLoadPendingCount = 0;
private static readonly object _initialLoadLock = new object();
public static async Task<int> Main(string[] args)
{
// Initialize SQLite for embedded single-file deployment
SQLitePCL.Batteries_V2.Init();
// Create root command (default dashboard command)
var rootCommand = new RootCommand("ServerHub - Terminal-based server monitoring dashboard");
// Default command arguments and options
var configArgument = new Argument<string?>("config")
{
Description = "Path to configuration file",
DefaultValueFactory = _ => null
};
var widgetsPathOption = new Option<string?>("--widgets-path")
{
Description = "Override widget directory path"
};
var devModeOption = new Option<bool>("--dev-mode")
{
Description = "Enable development mode (disables custom widget checksum validation)"
};
var discoverOption = new Option<bool>("--discover")
{
Description = "Discover and list all available widgets, then exit"
};
var verifyChecksumsOption = new Option<bool>("--verify-checksums")
{
Description = "Verify bundled widget checksums, then exit"
};
var initConfigOption = new Option<string?>("--init-config")
{
Description = "Initialize a new configuration file at specified path"
};
rootCommand.Arguments.Add(configArgument);
rootCommand.Options.Add(widgetsPathOption);
rootCommand.Options.Add(devModeOption);
rootCommand.Options.Add(discoverOption);
rootCommand.Options.Add(verifyChecksumsOption);
rootCommand.Options.Add(initConfigOption);
rootCommand.SetAction(async (parseResult) =>
{
var config = parseResult.GetValue(configArgument);
var widgetsPath = parseResult.GetValue(widgetsPathOption);
var devMode = parseResult.GetValue(devModeOption);
var discover = parseResult.GetValue(discoverOption);
var verifyChecksums = parseResult.GetValue(verifyChecksumsOption);
var initConfig = parseResult.GetValue(initConfigOption);
var exitCode = await Commands.Cli.DefaultCommand.ExecuteAsync(
config, widgetsPath, devMode, discover, verifyChecksums, initConfig);
Environment.ExitCode = exitCode;
});
// Marketplace commands
var marketplaceCommand = new Command("marketplace", "Manage marketplace widgets");
rootCommand.Subcommands.Add(marketplaceCommand);
// marketplace search
var marketplaceSearchCommand = new Command("search", "Search for community widgets");
var searchQueryArgument = new Argument<string>("query")
{
Description = "Search query for widgets"
};
marketplaceSearchCommand.Arguments.Add(searchQueryArgument);
marketplaceSearchCommand.SetAction(async (parseResult) =>
{
var query = parseResult.GetValue(searchQueryArgument);
var exitCode = await Commands.Cli.Marketplace.SearchCommand.ExecuteAsync(query!);
Environment.ExitCode = exitCode;
});
marketplaceCommand.Subcommands.Add(marketplaceSearchCommand);
// marketplace list
var marketplaceListCommand = new Command("list", "List all available widgets");
marketplaceListCommand.SetAction(async (parseResult) =>
{
var exitCode = await Commands.Cli.Marketplace.ListCommand.ExecuteAsync();
Environment.ExitCode = exitCode;
});
marketplaceCommand.Subcommands.Add(marketplaceListCommand);
// marketplace info
var marketplaceInfoCommand = new Command("info", "Show widget details");
var infoWidgetIdArgument = new Argument<string>("widget-id")
{
Description = "Widget ID to show information for"
};
marketplaceInfoCommand.Arguments.Add(infoWidgetIdArgument);
marketplaceInfoCommand.SetAction(async (parseResult) =>
{
var widgetId = parseResult.GetValue(infoWidgetIdArgument);
var exitCode = await Commands.Cli.Marketplace.InfoCommand.ExecuteAsync(widgetId!);
Environment.ExitCode = exitCode;
});
marketplaceCommand.Subcommands.Add(marketplaceInfoCommand);
// marketplace install
var marketplaceInstallCommand = new Command("install", "Install widget from marketplace");
var installWidgetIdArgument = new Argument<string>("widget-id")
{
Description = "Widget ID to install"
};
marketplaceInstallCommand.Arguments.Add(installWidgetIdArgument);
marketplaceInstallCommand.SetAction(async (parseResult) =>
{
var widgetId = parseResult.GetValue(installWidgetIdArgument);
var exitCode = await Commands.Cli.Marketplace.InstallCommand.ExecuteAsync(widgetId!);
Environment.ExitCode = exitCode;
});
marketplaceCommand.Subcommands.Add(marketplaceInstallCommand);
// marketplace list-installed
var marketplaceListInstalledCommand = new Command("list-installed", "List installed marketplace widgets");
marketplaceListInstalledCommand.SetAction(async (parseResult) =>
{
var exitCode = await Commands.Cli.Marketplace.ListInstalledCommand.ExecuteAsync();
Environment.ExitCode = exitCode;
});
marketplaceCommand.Subcommands.Add(marketplaceListInstalledCommand);
// marketplace check-updates
var marketplaceCheckUpdatesCommand = new Command("check-updates", "Check for widget updates");
var checkUpdatesJsonOption = new Option<bool>("--json")
{
Description = "Output results as JSON"
};
marketplaceCheckUpdatesCommand.Options.Add(checkUpdatesJsonOption);
marketplaceCheckUpdatesCommand.SetAction(async (parseResult) =>
{
var jsonOutput = parseResult.GetValue(checkUpdatesJsonOption);
var exitCode = await Commands.Cli.Marketplace.CheckUpdatesCommand.ExecuteAsync(jsonOutput);
Environment.ExitCode = exitCode;
});
marketplaceCommand.Subcommands.Add(marketplaceCheckUpdatesCommand);
// marketplace update
var marketplaceUpdateCommand = new Command("update", "Update widget to latest version");
var updateWidgetIdArgument = new Argument<string>("widget-id")
{
Description = "Widget ID to update"
};
var updateVersionOption = new Option<string?>("--version")
{
Description = "Specific version to install (defaults to latest)"
};
var updateYesOption = new Option<bool>("--yes")
{
Description = "Skip confirmation prompts"
};
marketplaceUpdateCommand.Arguments.Add(updateWidgetIdArgument);
marketplaceUpdateCommand.Options.Add(updateVersionOption);
marketplaceUpdateCommand.Options.Add(updateYesOption);
marketplaceUpdateCommand.SetAction(async (parseResult) =>
{
var widgetId = parseResult.GetValue(updateWidgetIdArgument);
var version = parseResult.GetValue(updateVersionOption);
var skipConfirmation = parseResult.GetValue(updateYesOption);
var exitCode = await Commands.Cli.Marketplace.UpdateCommand.ExecuteAsync(widgetId!, version, skipConfirmation);
Environment.ExitCode = exitCode;
});
marketplaceCommand.Subcommands.Add(marketplaceUpdateCommand);
// marketplace update-all
var marketplaceUpdateAllCommand = new Command("update-all", "Update all widgets");
var updateAllYesOption = new Option<bool>("--yes")
{
Description = "Skip confirmation prompts"
};
marketplaceUpdateAllCommand.Options.Add(updateAllYesOption);
marketplaceUpdateAllCommand.SetAction(async (parseResult) =>
{
var skipConfirmation = parseResult.GetValue(updateAllYesOption);
var exitCode = await Commands.Cli.Marketplace.UpdateAllCommand.ExecuteAsync(skipConfirmation);
Environment.ExitCode = exitCode;
});
marketplaceCommand.Subcommands.Add(marketplaceUpdateAllCommand);
// Storage commands
var storageCommand = new Command("storage", "Manage storage and database");
rootCommand.Subcommands.Add(storageCommand);
// storage stats
var storageStatsCommand = new Command("stats", "Show database statistics");
var statsConfigOption = new Option<string?>("--config")
{
Description = "Path to configuration file"
};
storageStatsCommand.Options.Add(statsConfigOption);
storageStatsCommand.SetAction((parseResult) =>
{
var config = parseResult.GetValue(statsConfigOption);
var exitCode = Commands.Cli.Storage.StorageStatsCommand.Execute(config);
Environment.ExitCode = exitCode;
});
storageCommand.Subcommands.Add(storageStatsCommand);
// storage cleanup
var storageCleanupCommand = new Command("cleanup", "Run database cleanup");
var cleanupConfigOption = new Option<string?>("--config")
{
Description = "Path to configuration file"
};
var cleanupForceOption = new Option<bool>("--force")
{
Description = "Skip confirmation prompt"
};
storageCleanupCommand.Options.Add(cleanupConfigOption);
storageCleanupCommand.Options.Add(cleanupForceOption);
storageCleanupCommand.SetAction((parseResult) =>
{
var config = parseResult.GetValue(cleanupConfigOption);
var force = parseResult.GetValue(cleanupForceOption);
var exitCode = Commands.Cli.Storage.StorageCleanupCommand.Execute(config, force);
Environment.ExitCode = exitCode;
});
storageCommand.Subcommands.Add(storageCleanupCommand);
// storage export
var storageExportCommand = new Command("export", "Export widget data to CSV or JSON");
var exportWidgetOption = new Option<string?>("--widget")
{
Description = "Widget ID to export data for"
};
var exportOutputOption = new Option<string?>("--output")
{
Description = "Output file path"
};
var exportFormatOption = new Option<string>("--format")
{
Description = "Output format (csv or json)",
DefaultValueFactory = _ => "csv"
};
var exportConfigOption = new Option<string?>("--config")
{
Description = "Path to configuration file"
};
storageExportCommand.Options.Add(exportWidgetOption);
storageExportCommand.Options.Add(exportOutputOption);
storageExportCommand.Options.Add(exportFormatOption);
storageExportCommand.Options.Add(exportConfigOption);
storageExportCommand.SetAction((parseResult) =>
{
var widgetId = parseResult.GetValue(exportWidgetOption);
var output = parseResult.GetValue(exportOutputOption);
var format = parseResult.GetValue(exportFormatOption);
var config = parseResult.GetValue(exportConfigOption);
var exitCode = Commands.Cli.Storage.StorageExportCommand.Execute(widgetId, output, format!, config);
Environment.ExitCode = exitCode;
});
storageCommand.Subcommands.Add(storageExportCommand);
// test-widget command
var testWidgetCommand = new Command("test-widget", "Test and validate widget scripts");
var testScriptArgument = new Argument<string>("script")
{
Description = "Path to widget script"
};
var testExtendedOption = new Option<bool>("--extended")
{
Description = "Show extended output"
};
var testUiModeOption = new Option<bool>("--ui")
{
Description = "Show UI preview"
};
var testSkipConfirmOption = new Option<bool>("--skip-confirmation")
{
Description = "Skip confirmation prompts"
};
testWidgetCommand.Arguments.Add(testScriptArgument);
testWidgetCommand.Options.Add(testExtendedOption);
testWidgetCommand.Options.Add(testUiModeOption);
testWidgetCommand.Options.Add(testSkipConfirmOption);
testWidgetCommand.SetAction(async (parseResult) =>
{
var script = parseResult.GetValue(testScriptArgument);
var extended = parseResult.GetValue(testExtendedOption);
var ui = parseResult.GetValue(testUiModeOption);
var skipConfirm = parseResult.GetValue(testSkipConfirmOption);
var exitCode = await Commands.Cli.TestWidgetCommandCli.ExecuteAsync(script!, extended, ui, skipConfirm);
Environment.ExitCode = exitCode;
});
rootCommand.Subcommands.Add(testWidgetCommand);
// new-widget command
var newWidgetCommand = new Command("new-widget", "Interactive widget creation wizard");
var newTemplateArgument = new Argument<string?>("template")
{
Description = "Widget template to use",
DefaultValueFactory = _ => null
};
var newNameOption = new Option<string?>("--name")
{
Description = "Widget name"
};
var newOutputOption = new Option<string?>("--output")
{
Description = "Output file path"
};
var newListOption = new Option<bool>("--list")
{
Description = "List available templates and exit"
};
newWidgetCommand.Arguments.Add(newTemplateArgument);
newWidgetCommand.Options.Add(newNameOption);
newWidgetCommand.Options.Add(newOutputOption);
newWidgetCommand.Options.Add(newListOption);
newWidgetCommand.SetAction(async (parseResult) =>
{
var templateName = parseResult.GetValue(newTemplateArgument);
var name = parseResult.GetValue(newNameOption);
var outputFile = parseResult.GetValue(newOutputOption);
var listTemplates = parseResult.GetValue(newListOption);
var exitCode = await Commands.Cli.NewWidgetCommandCli.ExecuteAsync(templateName, name, outputFile, listTemplates);
Environment.ExitCode = exitCode;
});
rootCommand.Subcommands.Add(newWidgetCommand);
// completion command - generate shell completion scripts
var completionCommand = new Command("completion", "Generate shell completion scripts");
var completionShellArgument = new Argument<string>("shell")
{
Description = "Shell type: bash, zsh, or fish"
};
completionCommand.Arguments.Add(completionShellArgument);
completionCommand.SetAction((parseResult) =>
{
var shell = parseResult.GetValue(completionShellArgument);
var exitCode = Commands.Cli.CompletionCommand.Execute(shell!);
Environment.ExitCode = exitCode;
});
rootCommand.Subcommands.Add(completionCommand);
var parseResult = rootCommand.Parse(args);
return await parseResult.InvokeAsync();
}
/// <summary>
/// Runs the ServerHub dashboard (called by DefaultCommand)
/// </summary>
public static async Task<int> RunDashboardAsync(string[] args, string configPath, bool devMode)
{
Storage.StorageService? storageService = null;
try
{
_configPath = configPath;
_devMode = devMode;
var configMgr = new ConfigManager();
_config = configMgr.LoadConfig(configPath);
_lastConfigLoadTime = File.GetLastWriteTime(configPath);
// Initialize storage service if enabled
// If storage section is missing from config, use defaults (enabled: true)
_config.Storage ??= new Storage.StorageConfig();
if (_config.Storage.Enabled)
{
try
{
storageService = Storage.StorageService.Initialize(_config.Storage);
}
catch (Exception ex)
{
// Log storage initialization error but don't crash the app
// Note: Using Console.Error here because Logger isn't initialized yet
Console.Error.WriteLine($"Warning: Failed to initialize storage service: {ex.Message}");
Console.Error.WriteLine("Dashboard will continue without data persistence.");
}
}
// Initialize services
var validator = new ScriptValidator(devMode: devMode);
_executor = new ScriptExecutor(validator);
_parser = new WidgetProtocolParser();
_renderer = new WidgetRenderer();
_layoutEngine = new LayoutEngine();
_refreshService = new WidgetRefreshService(_executor, _parser, _config, storageService);
_commandPaletteService = new CommandPaletteService();
RegisterCommandPaletteCallbacks();
// Initialize ConsoleEx window system
_windowSystem = new ConsoleWindowSystem(
new NetConsoleDriver(RenderMode.Buffer),
options: new ConsoleWindowSystemOptions(
StatusBarOptions: new StatusBarOptions(
ShowTaskBar: false,
ShowBottomStatus: true
)
));
// Initialize logger with SharpConsoleUI's LogService
// Enable debug logging with: export SHARPCONSOLEUI_DEBUG_LOG=/tmp/serverhub-debug.log
Utils.Logger.Initialize(_windowSystem.LogService);
Utils.Logger.Info("ServerHub logger initialized", "Startup");
Utils.Logger.Debug($"Storage enabled: {_config.Storage?.Enabled}, widgets count: {_config.Widgets.Count}", "Startup");
// Initialize StatusBarManager
_statusBarManager = new StatusBarManager(_windowSystem.StatusBarStateService, devMode: _devMode);
// Setup graceful shutdown
Console.CancelKeyPress += (sender, e) =>
{
e.Cancel = true;
_windowSystem?.Shutdown(0);
};
// Create main window
CreateMainWindow();
// Subscribe to terminal resize events
_windowSystem.ConsoleDriver.ScreenResized += OnTerminalResized;
// Check for unconfigured scripts and show warning
CheckForUnconfiguredWidgets();
// Dev mode: show warning dialog that MUST be acknowledged before scripts run
if (_devMode)
{
ShowDevModeWarningDialog(); // Will call StartWidgetRefreshTimers() when acknowledged
}
else
{
// Normal mode: start scripts immediately
StartWidgetRefreshTimers();
}
// Run the application
await Task.Run(() => _windowSystem.Run());
// Cleanup
StopWidgetRefreshTimers();
return 0;
}
catch (ConfigurationException configEx)
{
DisplayConfigurationError(configEx);
return 1;
}
catch (Exception ex)
{
DisplayGenericError(ex);
return 1;
}
finally
{
// Ensure storage service is properly disposed
if (storageService != null)
{
try
{
Storage.StorageService.Shutdown();
}
catch (Exception ex)
{
Console.Error.WriteLine($"Warning: Error shutting down storage service: {ex.Message}");
}
}
}
}
private static void CreateMainWindow()
{
if (_windowSystem == null || _config == null)
return;
var windowBuilder = new WindowBuilder(_windowSystem)
.WithTitle("ServerHub")
.WithName("MainWindow")
.WithColors(Spectre.Console.Color.Grey93, Spectre.Console.Color.Grey11)
.Borderless()
.Maximized()
.WithAsyncWindowThread(UpdateDashboardAsync)
.OnKeyPressed(HandleKeyPress);
// Dev mode: orange border color (not foreground!) as visual indicator
if (_devMode)
{
windowBuilder.WithActiveBorderColor(Spectre.Console.Color.Orange1);
}
_mainWindow = windowBuilder.Build();
// Get terminal dimensions
var terminalWidth = Console.WindowWidth;
var terminalHeight = Console.WindowHeight;
// Store initial terminal width
_lastTerminalWidth = terminalWidth;
// Calculate layout
var placements = _layoutEngine!.CalculateLayout(_config, terminalWidth, terminalHeight);
// Initialize FocusManager
_focusManager = new FocusManager();
_focusManager.Initialize(_mainWindow, placements);
// No widget focused on startup - user must click or tab to focus
// Build widget layout
BuildWidgetLayout(placements, terminalWidth, useCache: false);
_windowSystem.AddWindow(_mainWindow);
}
private static void OnTerminalResized(object? sender, SharpConsoleUI.Helpers.Size size)
{
var newWidth = size.Width;
// Only rebuild if width changed (column count might change)
if (newWidth != _lastTerminalWidth)
{
_lastTerminalWidth = newWidth;
RebuildLayout();
}
}
private static void RebuildLayout()
{
if (
_mainWindow == null
|| _windowSystem == null
|| _config == null
|| _layoutEngine == null
)
return;
try
{
// SAVE current focus BEFORE clearing controls
var currentFocusedId = _focusManager?.GetFocusedWidgetId();
// Clear all controls from the window
_mainWindow.ClearControls();
// Get terminal dimensions
var terminalWidth = Console.WindowWidth;
var terminalHeight = Console.WindowHeight;
// Recalculate layout
var placements = _layoutEngine.CalculateLayout(_config, terminalWidth, terminalHeight);
// Check if dashboard is empty
if (placements.Count == 0)
{
ShowEmptyDashboardMessage();
UpdateStatusBar();
return;
}
// RE-INITIALIZE FocusManager with new placements
_focusManager?.Initialize(_mainWindow, placements);
// Build widget layout using cache
BuildWidgetLayout(placements, terminalWidth, useCache: true);
// RESTORE focus to same widget (by ID) after rebuild completes
if (currentFocusedId != null)
{
_focusManager?.FocusWidget(currentFocusedId);
}
// If no widget was focused before rebuild, keep it that way
// Update status
_statusBarManager?.ShowInfo($"Layout rebuilt for {terminalWidth} cols", 2000);
}
catch (Exception ex)
{
// If rebuild fails, just log it - don't crash the app
_statusBarManager?.ShowError($"Layout rebuild error: {ex.Message}", 5000);
}
}
private static void BuildWidgetLayout(
List<LayoutEngine.WidgetPlacement> placements,
int terminalWidth,
bool useCache
)
{
if (_mainWindow == null || _renderer == null)
return;
// Determine column count for this terminal width
var columnCount = GetColumnCountFromWidth(terminalWidth);
// Calculate base column width (no spacing between widgets)
const int spacingBetweenWidgets = 0;
int totalSpacing = Math.Max(0, (columnCount - 1) * spacingBetweenWidgets);
int availableWidth = terminalWidth - totalSpacing;
int baseColumnWidth = availableWidth / columnCount;
// Group placements by row
var rowGroups = placements.GroupBy(p => p.Row).OrderBy(g => g.Key);
// Consistent styling for all widgets (btop-style with rounded borders)
var widgetBackgroundColor = Spectre.Console.Color.Grey11; // Minimal background, same as window
// Build rows (no vertical spacing between rows)
foreach (var rowGroup in rowGroups)
{
var rowPlacements = rowGroup.OrderBy(p => p.Column).ToList();
// Create horizontal grid for this row
var rowGrid = Controls
.HorizontalGrid()
.WithAlignment(SharpConsoleUI.Layout.HorizontalAlignment.Stretch)
.WithVerticalAlignment(SharpConsoleUI.Layout.VerticalAlignment.Top);
bool firstWidget = true;
var widgetBgColors = new List<Spectre.Console.Color>();
var widgetIdByColumnIndex = new List<string?>(); // Track which widget owns each column
foreach (var placement in rowPlacements)
{
// Add spacing between widgets (not before first widget)
if (!firstWidget)
{
rowGrid.Column(colBuilder => colBuilder.Width(spacingBetweenWidgets));
widgetBgColors.Add(Spectre.Console.Color.Grey11); // Spacer color
widgetIdByColumnIndex.Add(null); // Spacer column has no widget
}
firstWidget = false;
// Calculate widget width based on column span
// width = (baseColumnWidth * spanCount) + (spacing * (spanCount - 1))
int widgetWidth =
(baseColumnWidth * placement.ColumnSpan)
+ (spacingBetweenWidgets * Math.Max(0, placement.ColumnSpan - 1));
// Get widget data: use cache if rebuilding, otherwise show loading spinner
var widgetData =
useCache
&& _widgetDataCache.TryGetValue(placement.WidgetId, out var cachedData)
? cachedData
: CreateLoadingWidget(placement.WidgetId);
// Determine border color: highlight pinned widgets with cyan border
var borderColor = placement.IsPinned
? Spectre.Console.Color.Cyan1
: Spectre.Console.Color.Grey35;
widgetBgColors.Add(widgetBackgroundColor);
widgetIdByColumnIndex.Add(placement.WidgetId); // Track widget for this column
// Get max lines: widget-specific > global > default 20
var widgetConfig = _config?.Widgets.GetValueOrDefault(placement.WidgetId);
int maxLines = widgetConfig?.MaxLines ?? _config?.MaxLinesPerWidget ?? 20;
bool showIndicator = _config?.ShowTruncationIndicator ?? true;
var widgetPanel = _renderer.CreateWidgetPanel(
placement.WidgetId,
widgetData,
placement.IsPinned,
widgetBackgroundColor,
borderColor,
widgetId =>
{
// Toggle focus: click again to deselect
if (_focusManager?.GetFocusedWidgetId() == widgetId)
{
_focusManager?.ClearFocus();
}
else
{
_focusManager?.FocusWidget(widgetId);
}
},
widgetId => ShowWidgetDialog(widgetId), // Double-click opens dialog
maxLines,
showIndicator
);
// Store full widget data for expansion dialog
_fullWidgetData[placement.WidgetId] = widgetData;
// Add widget column with explicit width
rowGrid.Column(colBuilder =>
{
colBuilder.Width(widgetWidth);
colBuilder.Add(widgetPanel);
});
}
// Build and add row grid
var builtRowGrid = rowGrid.Build();
// Set background colors for columns and wire up click events
for (int i = 0; i < builtRowGrid.Columns.Count && i < widgetBgColors.Count; i++)
{
builtRowGrid.Columns[i].BackgroundColor = widgetBgColors[i];
// Wire up click events for widget columns (skip spacer columns)
// Note: Double-click handler is already registered on PanelControl in CreateWidgetPanel
if (i < widgetIdByColumnIndex.Count && widgetIdByColumnIndex[i] != null)
{
var widgetId = widgetIdByColumnIndex[i]!;
// Single click: toggle focus (click again to deselect)
builtRowGrid.Columns[i].MouseClick += (sender, e) =>
{
if (_focusManager?.GetFocusedWidgetId() == widgetId)
{
_focusManager?.ClearFocus();
}
else
{
_focusManager?.FocusWidget(widgetId);
}
};
// REMOVED: Duplicate MouseDoubleClick handler that was causing two modals to open
// The handler is already registered on the PanelControl via CreateWidgetPanel (line 438)
}
}
_mainWindow.AddControl(builtRowGrid);
}
}
private static async Task UpdateDashboardAsync(Window window, CancellationToken ct)
{
// This async thread updates the status bar with current time and system stats
while (!ct.IsCancellationRequested)
{
try
{
// Rotate spinner frame
_spinnerFrame++;
// Update widgets that are currently refreshing to animate spinner
foreach (
var widgetId in _isRefreshing
.Where(kvp => kvp.Value)
.Select(kvp => kvp.Key)
.ToList()
)
{
if (_widgetDataCache.TryGetValue(widgetId, out var widgetData))
{
UpdateWidgetUI(widgetId, widgetData);
}
}
// Update status bar with widget counts and system stats
UpdateStatusBar();
await Task.Delay(250, ct); // Faster spinner animation
}
catch (OperationCanceledException)
{
break;
}
}
}
private static WidgetData CreateLoadingWidget(string widgetId)
{
return new WidgetData
{
Title = widgetId,
Timestamp = DateTime.Now,
Rows = new List<WidgetRow>
{
new() { Content = "" },
new()
{
Content = $" [cyan1]Loading... {_spinnerFrames[_spinnerFrame % 4]}[/]",
},
new() { Content = "" },
},
};
}
private static void TogglePause()
{
_isPaused = !_isPaused;
if (_windowSystem != null)
{
// Bottom status doesn't need updating - it's static keyboard shortcuts
// Just force a status bar update to show pause state in top status
UpdateStatusBar();
}
}
private static void ShowHelpOverlay()
{
if (_windowSystem == null)
return;
// Calculate centered position and size based on terminal dimensions
var terminalWidth = Console.WindowWidth;
var terminalHeight = Console.WindowHeight;
// Dialog size: larger for better readability
var dialogWidth = Math.Min(78, terminalWidth - 10);
var dialogHeight = Math.Min(24, terminalHeight - 6);
// Center the dialog
var dialogX = (terminalWidth - dialogWidth) / 2;
var dialogY = (terminalHeight - dialogHeight) / 2;
// Create help window with rounded borders
var helpWindow = new WindowBuilder(_windowSystem)
.WithName("HelpOverlay")
.WithBounds(dialogX, dialogY, dialogWidth, dialogHeight)
.WithBorderStyle(BorderStyle.Rounded)
.WithBorderColor(SharpConsoleUI.Color.Grey35)
.WithColors(SharpConsoleUI.Color.Grey93, SharpConsoleUI.Color.Grey15)
.HideTitle()
.AsModal()
.Minimizable(false)
.Maximizable(false)
.Resizable(false)
.Movable(false)
.OnKeyPressed(
(sender, e) =>
{
// Close on ESC, Enter, or ? key
if (
e.KeyInfo.Key == ConsoleKey.Escape
|| e.KeyInfo.Key == ConsoleKey.Enter
|| e.KeyInfo.KeyChar == '?'
|| e.KeyInfo.Key == ConsoleKey.F1
)
{
_windowSystem.CloseWindow((Window)sender!);
e.Handled = true;
}
}
)
.Build();
var helpContent =
@"
[bold cyan1]ServerHub[/] [grey70]v0.1.0[/] [grey50]•[/] [grey70]Server Monitoring Dashboard[/]
[bold cyan1]▸ Navigation[/]
[cyan1]Tab[/] [grey50]/[/] [cyan1]Shift+Tab[/] Move between widgets
[cyan1]Arrow keys[/] Scroll within widget
[cyan1]Ctrl[/] [grey50]+[/] [cyan1]←/→[/] Swap widget left/right in row
[cyan1]Ctrl[/] [grey50]+[/] [cyan1]↑/↓[/] Swap widget with row above/below
[cyan1]Ctrl+Shift[/] [grey50]+[/] [cyan1]←/→[/] Decrease/increase widget width
[cyan1]Ctrl+Shift[/] [grey50]+[/] [cyan1]↑/↓[/] Decrease/increase widget height
[bold cyan1]▸ Widget Actions[/]
[cyan1]Click[/] Focus widget
[cyan1]Double-click[/] [grey50]or[/] [cyan1]Enter[/] Open expanded view
[bold cyan1]▸ Application[/]
[cyan1]F2[/] Configure widgets [grey50](add/remove/edit)[/]
[cyan1]F3[/] Browse marketplace [grey50](install widgets)[/]
[cyan1]Ctrl+P[/] Command palette [grey50](quick actions)[/]
[cyan1]F5[/] Refresh all widgets
[cyan1]Space[/] Pause / resume auto-refresh
[cyan1]? [/][grey50]or[/] [cyan1]F1[/] Show this help
[cyan1]Ctrl+Q[/] Exit ServerHub
[grey50]───────────────────────────────────────────────────────────────────────[/]
[grey70]Press [cyan1]ESC[/], [cyan1]Enter[/], [cyan1]?[/], or [cyan1]F1[/] to close this help[/]
";
var helpBuilder = Controls
.Markup()
.WithBackgroundColor(SharpConsoleUI.Color.Grey15)
.WithMargin(2, 1, 2, 1);
// Split content into lines and add them
var lines = helpContent.Split('\n');
foreach (var line in lines)
{
helpBuilder.AddLine(line);
}
var helpControl = helpBuilder.Build();
helpWindow.AddControl(helpControl);
_windowSystem.AddWindow(helpWindow);
}
/// <summary>
/// Shows a warning dialog when running in dev mode (Layer 3 of dev mode warnings)
/// Scripts will not start until user acknowledges by clicking the button
/// </summary>
private static void ShowDevModeWarningDialog()
{
if (_windowSystem == null)
return;
Window? warningWindow = null;
warningWindow = new WindowBuilder(_windowSystem)
.WithName("DevModeWarning")
.HideTitle()
.WithSize(60, 16)
.Centered()
.WithBackgroundColor(SharpConsoleUI.Color.Grey11)
.WithBorderStyle(BorderStyle.Single)
.AsModal()
.Minimizable(false)
.Maximizable(false)
.Resizable(false)
.Movable(false)
.HideCloseButton()
.Build();
var contentBuilder = Controls
.Markup()
.WithBackgroundColor(SharpConsoleUI.Color.Grey11)
.WithMargin(2, 1, 2, 1);
contentBuilder.AddLine("");
contentBuilder.AddLine("[bold yellow] Development Mode Active[/]");
contentBuilder.AddLine("");
contentBuilder.AddLine("[white]Custom widget checksum validation is DISABLED.[/]");
contentBuilder.AddLine("");
contentBuilder.AddLine("[grey70]• Custom widgets will run without integrity checks[/]");
contentBuilder.AddLine("[grey70]• Bundled widgets are still validated[/]");
contentBuilder.AddLine("[grey70]• Use for development and testing only[/]");
contentBuilder.AddLine("");
contentBuilder.AddLine("[red]Do NOT use --dev-mode in production![/]");
var contentControl = contentBuilder.Build();
warningWindow.AddControl(contentControl);
// Buttons: I Understand and Quit
var understandButton = Controls
.Button(" I Understand ")
.OnClick((sender, e) =>
{
_windowSystem?.CloseWindow(warningWindow!);
StartWidgetRefreshTimers(); // Start scripts only after acknowledgment
})
.Build();