From 8d17ed5bc4b27b06c2555c29835520ec70b25ac6 Mon Sep 17 00:00:00 2001 From: Rod Christiansen Date: Mon, 12 Oct 2026 23:21:50 -0700 Subject: [PATCH 1/3] Show one policy note and a read-only Services card on the Prefs tab Drop the per-field "Managed by Policy" captions: fields set by policy stay disabled and gray, and a single line at the top of the tab says so when any value comes from the policy key. Add a Services card listing what the installer registers (the daily self-heal scheduled task) with its state, last result and schedule in plain words, queried through the Task Scheduler without elevation. Lay the Prefs cards out on an even two-column grid with Services spanning both columns. --- .../ViewModels/PrefsViewModel.cs | 43 ++-- src/BootstrapMate.App/Views/PrefsPage.xaml | 190 +++++++------- src/BootstrapMate.App/Views/PrefsPage.xaml.cs | 6 + src/BootstrapMate.Core/InstallFootprint.cs | 237 ++++++++++++++++++ .../InstallFootprintTests.cs | 121 +++++++++ 5 files changed, 491 insertions(+), 106 deletions(-) create mode 100644 src/BootstrapMate.Core/InstallFootprint.cs create mode 100644 tests/BootstrapMate.Core.Tests/InstallFootprintTests.cs diff --git a/src/BootstrapMate.App/ViewModels/PrefsViewModel.cs b/src/BootstrapMate.App/ViewModels/PrefsViewModel.cs index 84771fc..a5c7265 100644 --- a/src/BootstrapMate.App/ViewModels/PrefsViewModel.cs +++ b/src/BootstrapMate.App/ViewModels/PrefsViewModel.cs @@ -70,6 +70,32 @@ partial void OnSaveStatusChanged(SaveState value) public bool IsManaged(string key) => _managedKeys.Contains(key); + /// True when any value comes from the policy key; shows the policy note on the tab. + public bool HasPolicySettings => _managedKeys.Count > 0; + + // ── Services ───────────────────────────────────────────────── + + /// The services and scheduled tasks the installer creates, with their live state. + [ObservableProperty] private IReadOnlyList _services = []; + + [ObservableProperty] private bool _isServicesLoading; + + /// Queries the installer's services and tasks off the UI thread. + public async Task LoadServicesAsync() + { + if (IsServicesLoading) + return; + IsServicesLoading = true; + try + { + Services = await Task.Run(InstallFootprint.QueryAll); + } + finally + { + IsServicesLoading = false; + } + } + // ── Binding-Friendly Display Properties ────────────────────── public string VersionDisplay => $"Version {AppVersion}"; @@ -89,8 +115,6 @@ public double NetworkTimeoutValue partial void OnNetworkTimeoutChanged(int value) => OnPropertyChanged(nameof(NetworkTimeoutValue)); - // ── Policy Lock Properties (for x:Bind) ───────────────────── - // ── Elevation State ───────────────────────────────────────── /// True when this process can write HKLM (elevated administrator token). @@ -154,19 +178,6 @@ public bool TryRelaunchElevated() public bool CanEditCustomInstallPath => CanEdit("CustomInstallPath"); public bool CanEditNetworkTimeout => CanEdit("NetworkTimeout"); - public bool IsManifestUrlLocked => IsLocked("ManifestUrl"); - public bool IsAuthHeaderLocked => IsLocked("AuthorizationHeader"); - public bool IsSilentModeLocked => IsLocked("SilentMode"); - public bool IsVerboseModeLocked => IsLocked("VerboseMode"); - public bool IsDryRunLocked => IsLocked("DryRun"); - public bool IsEnableDialogLocked => IsLocked("EnableDialog"); - public bool IsDialogTitleLocked => IsLocked("DialogTitle"); - public bool IsDialogMessageLocked => IsLocked("DialogMessage"); - public bool IsDialogIconLocked => IsLocked("DialogIcon"); - public bool IsBlurScreenLocked => IsLocked("BlurScreen"); - public bool IsCustomInstallPathLocked => IsLocked("CustomInstallPath"); - public bool IsNetworkTimeoutLocked => IsLocked("NetworkTimeout"); - // ── Save Status Display (for x:Bind) ──────────────────────── public string SaveStatusGlyph => SaveStatus switch @@ -203,6 +214,7 @@ public void Load() var config = configMgr.Config; _managedKeys = ManagementDetector.Instance.AllManagedKeys(); + OnPropertyChanged(nameof(HasPolicySettings)); ManifestUrl = config.ManifestUrl ?? ""; HasExistingAuth = !string.IsNullOrEmpty(config.AuthorizationHeader); @@ -234,6 +246,7 @@ public void Load() nameof(IsManifestPreviewLoading), nameof(ManifestPreviewContent), nameof(ManifestPreviewError), nameof(HasManifestPreviewContent), nameof(HasManifestPreviewError), nameof(UnlockError), nameof(HasUnlockError), + nameof(HasPolicySettings), nameof(Services), nameof(IsServicesLoading), "", // string.Empty from Load's bulk notify ]; diff --git a/src/BootstrapMate.App/Views/PrefsPage.xaml b/src/BootstrapMate.App/Views/PrefsPage.xaml index 91d213e..3098d7e 100644 --- a/src/BootstrapMate.App/Views/PrefsPage.xaml +++ b/src/BootstrapMate.App/Views/PrefsPage.xaml @@ -3,15 +3,26 @@ xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:vm="using:BootstrapMate.App.ViewModels" + xmlns:core="using:BootstrapMate.Core" NavigationCacheMode="Required"> + + + + - + @@ -40,6 +51,15 @@ HorizontalAlignment="Center" /> + + + + + + - + - + + - + - - - - - - - - - + - - - - - - - - - - - - - + - - - - - - - - - - - - - - - - - - - - - + - - - - @@ -329,12 +272,77 @@ - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/BootstrapMate.App/Views/PrefsPage.xaml.cs b/src/BootstrapMate.App/Views/PrefsPage.xaml.cs index 8c79a76..5241277 100644 --- a/src/BootstrapMate.App/Views/PrefsPage.xaml.cs +++ b/src/BootstrapMate.App/Views/PrefsPage.xaml.cs @@ -26,6 +26,7 @@ protected override void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); ViewModel.Load(); + _ = ViewModel.LoadServicesAsync(); } private void UnlockButton_Click(object sender, RoutedEventArgs e) @@ -40,4 +41,9 @@ private async void PreviewManifestButton_Click(object sender, RoutedEventArgs e) { await ViewModel.FetchManifestPreviewAsync(); } + + private async void RefreshServicesButton_Click(object sender, RoutedEventArgs e) + { + await ViewModel.LoadServicesAsync(); + } } diff --git a/src/BootstrapMate.Core/InstallFootprint.cs b/src/BootstrapMate.Core/InstallFootprint.cs new file mode 100644 index 0000000..c2823b3 --- /dev/null +++ b/src/BootstrapMate.Core/InstallFootprint.cs @@ -0,0 +1,237 @@ +using System.Globalization; +using System.Xml; +using System.Xml.Linq; + +namespace BootstrapMate.Core; + +/// A Windows service or scheduled task the installer creates. +public enum FootprintKind { Service, ScheduledTask } + +/// One entry of the installer's footprint: what it is called and what it is for. +public sealed record FootprintItem(string FriendlyName, string Name, FootprintKind Kind, string Description); + +/// The live state of one footprint entry, already in plain words for display. +public sealed record FootprintStatus( + string FriendlyName, string Name, string KindText, string Description, + string State, string LastResult, string Trigger); + +/// +/// The Windows services and scheduled tasks the MSI installs, and a read-only look at their +/// current state for the Prefs tab. The list is the installer's own (installer/Product.wxs): +/// it registers one scheduled task and no services. Querying never needs elevation; anything +/// the caller may not read shows as "Unknown". +/// +public static class InstallFootprint +{ + public const string SelfHealTaskName = "BootstrapMate Self-Heal"; + + public static readonly IReadOnlyList Items = + [ + new("Daily self-heal", SelfHealTaskName, FootprintKind.ScheduledTask, + "Re-runs the bootstrap as SYSTEM so missing packages are reinstalled."), + ]; + + // Task Scheduler result codes that are not failures. + private const int SchedTaskHasNotRun = 0x00041303; + private const int SchedTaskRunning = 0x00041301; + + private const int HResultFileNotFound = unchecked((int)0x80070002); + private const int HResultPathNotFound = unchecked((int)0x80070003); + + private static readonly XNamespace TaskNs = "http://schemas.microsoft.com/windows/2004/02/mit/task"; + + /// Queries every footprint entry. Blocking; call it off the UI thread. + public static IReadOnlyList QueryAll() => Items.Select(Query).ToList(); + + private static FootprintStatus Query(FootprintItem item) => item.Kind switch + { + FootprintKind.ScheduledTask => QueryTask(item), + // The installer registers no services, so there is nothing to query here yet. + _ => Row(item, "Unknown", "—", "—"), + }; + + private static FootprintStatus QueryTask(FootprintItem item) + { + try + { + var type = Type.GetTypeFromProgID("Schedule.Service"); + if (type is null) + return Row(item, "Unknown", "—", "—"); + + dynamic service = Activator.CreateInstance(type)!; + service.Connect(); + dynamic task = service.GetFolder("\\").GetTask(item.Name); + + int state = task.State; + DateTime lastRun = task.LastRunTime; + int lastResult = task.LastTaskResult; + string xml = task.Xml; + + return Row(item, DescribeTaskState(state), DescribeTaskResult(lastRun, lastResult), DescribeTaskTriggers(xml)); + } + catch (Exception ex) when (ex.HResult is HResultFileNotFound or HResultPathNotFound) + { + return Row(item, "Not installed", "—", "—"); + } + catch (Exception) + { + // Access denied for a standard user, or the scheduler is unavailable. + return Row(item, "Unknown", "Unknown", "Unknown"); + } + } + + private static FootprintStatus Row(FootprintItem item, string state, string lastResult, string trigger) => + new(item.FriendlyName, item.Name, DescribeKind(item.Kind), item.Description, state, lastResult, trigger); + + // ── Plain-words formatting ─────────────────────────────────── + + public static string DescribeKind(FootprintKind kind) => + kind == FootprintKind.Service ? "Service" : "Scheduled task"; + + /// Task Scheduler TASK_STATE value in words. + public static string DescribeTaskState(int state) => state switch + { + 1 => "Disabled", + 2 => "Ready", // queued to run + 3 => "Ready", + 4 => "Running", + _ => "Unknown", + }; + + /// + /// Last run time and result in words: "Never run", or "Succeeded" / "Failed (0x…)" with the + /// run time. The scheduler reports a task that has never run with a zero date or 0x41303. + /// + public static string DescribeTaskResult(DateTime lastRun, int lastResult) + { + if (lastResult == SchedTaskHasNotRun || lastRun.Year < 2000) + return "Never run"; + + var outcome = lastResult switch + { + 0 => "Succeeded", + SchedTaskRunning => "Running", + _ => $"Failed (0x{lastResult:X8})", + }; + return $"{outcome} — {lastRun.ToString("MMM d, yyyy h:mm tt", CultureInfo.InvariantCulture)}"; + } + + /// A service start type in words ("Starts automatically at boot", …). + public static string DescribeStartType(string startType, bool delayed) => startType switch + { + "Automatic" when delayed => "Starts automatically (delayed) at boot", + "Automatic" => "Starts automatically at boot", + "Boot" or "System" => "Starts with Windows", + "Manual" => "Starts manually", + "Disabled" => "Disabled", + _ => "Unknown", + }; + + /// A stopped service's Win32 exit code in words; "—" while it runs. + public static string DescribeServiceResult(bool running, int win32ExitCode) => + running ? "—" : $"Exit code {win32ExitCode}"; + + /// + /// The enabled triggers of a task definition (Task Scheduler XML) in words, joined with "; ". + /// + public static string DescribeTaskTriggers(string taskXml) + { + XDocument doc; + try { doc = XDocument.Parse(taskXml); } + catch (XmlException) { return "Unknown"; } + + var triggers = doc.Root?.Element(TaskNs + "Triggers")?.Elements() ?? []; + var words = triggers + .Where(t => !string.Equals((string?)t.Element(TaskNs + "Enabled"), "false", StringComparison.OrdinalIgnoreCase)) + .Select(DescribeTrigger) + .ToList(); + + return words.Count == 0 ? "On demand only" : string.Join("; ", words); + } + + private static string DescribeTrigger(XElement trigger) + { + var text = trigger.Name.LocalName switch + { + "BootTrigger" => "At startup", + "LogonTrigger" => trigger.Element(TaskNs + "UserId") is { } user + ? $"At logon of {user.Value}" + : "At logon of any user", + "TimeTrigger" => $"Once at {FormatBoundary(trigger)}", + "CalendarTrigger" => DescribeCalendar(trigger), + "IdleTrigger" => "When the computer is idle", + "EventTrigger" => "On an event log entry", + "RegistrationTrigger" => "When the task is created or changed", + "SessionStateChangeTrigger" => "On a session change", + _ => "On a custom trigger", + }; + + var interval = (string?)trigger.Element(TaskNs + "Repetition")?.Element(TaskNs + "Interval"); + if (!string.IsNullOrEmpty(interval) && TryDuration(interval, out var every)) + text += $", then every {every}"; + return text; + } + + private static string DescribeCalendar(XElement trigger) + { + var at = $"at {FormatTime(trigger)}"; + + if (trigger.Element(TaskNs + "ScheduleByDay") is { } byDay) + { + var days = (int?)byDay.Element(TaskNs + "DaysInterval") ?? 1; + return days == 1 ? $"Daily {at}" : $"Every {days} days {at}"; + } + if (trigger.Element(TaskNs + "ScheduleByWeek") is { } byWeek) + { + var weeks = (int?)byWeek.Element(TaskNs + "WeeksInterval") ?? 1; + var names = byWeek.Element(TaskNs + "DaysOfWeek")?.Elements().Select(d => d.Name.LocalName).ToList() ?? []; + var prefix = weeks == 1 ? "Weekly" : $"Every {weeks} weeks"; + return names.Count == 0 ? $"{prefix} {at}" : $"{prefix} on {string.Join(", ", names)} {at}"; + } + if (trigger.Element(TaskNs + "ScheduleByMonth") is not null + || trigger.Element(TaskNs + "ScheduleByMonthDayOfWeek") is not null) + return $"Monthly {at}"; + + return $"On a schedule {at}"; + } + + private static string FormatTime(XElement trigger) => + TryBoundary(trigger, out var start) + ? start.ToString("h:mm tt", CultureInfo.InvariantCulture) + : "an unknown time"; + + private static string FormatBoundary(XElement trigger) => + TryBoundary(trigger, out var start) + ? start.ToString("MMM d, yyyy h:mm tt", CultureInfo.InvariantCulture) + : "an unknown time"; + + // StartBoundary is local wall-clock time, sometimes with an offset; the wall-clock part is + // what the scheduler shows, so the offset is ignored rather than converted. + private static bool TryBoundary(XElement trigger, out DateTime start) + { + start = default; + var raw = (string?)trigger.Element(TaskNs + "StartBoundary"); + if (string.IsNullOrEmpty(raw) || raw.Length < 19) + return false; + return DateTime.TryParseExact(raw[..19], "yyyy-MM-ddTHH:mm:ss", CultureInfo.InvariantCulture, + DateTimeStyles.None, out start); + } + + private static bool TryDuration(string iso, out string words) + { + words = ""; + TimeSpan span; + try { span = XmlConvert.ToTimeSpan(iso); } + catch (FormatException) { return false; } + + words = span switch + { + { TotalDays: >= 1 } when span.TotalDays % 1 == 0 => Plural((int)span.TotalDays, "day"), + { TotalHours: >= 1 } when span.TotalHours % 1 == 0 => Plural((int)span.TotalHours, "hour"), + _ => Plural((int)span.TotalMinutes, "minute"), + }; + return true; + } + + private static string Plural(int n, string unit) => n == 1 ? unit : $"{n} {unit}s"; +} diff --git a/tests/BootstrapMate.Core.Tests/InstallFootprintTests.cs b/tests/BootstrapMate.Core.Tests/InstallFootprintTests.cs new file mode 100644 index 0000000..62146a9 --- /dev/null +++ b/tests/BootstrapMate.Core.Tests/InstallFootprintTests.cs @@ -0,0 +1,121 @@ +using BootstrapMate.Core; +using Xunit; + +namespace BootstrapMate.Core.Tests; + +public class InstallFootprintTests +{ + private static string TaskXml(string triggers) => $""" + + + {triggers} + + """.Trim(); + + [Fact] + public void TheFootprintIsTheSelfHealTaskTheInstallerRegisters() + { + var item = Assert.Single(InstallFootprint.Items); + Assert.Equal("BootstrapMate Self-Heal", item.Name); + Assert.Equal(FootprintKind.ScheduledTask, item.Kind); + } + + [Theory] + [InlineData("Automatic", false, "Starts automatically at boot")] + [InlineData("Automatic", true, "Starts automatically (delayed) at boot")] + [InlineData("Manual", false, "Starts manually")] + [InlineData("Disabled", false, "Disabled")] + [InlineData("Something", false, "Unknown")] + public void StartTypesReadAsWords(string startType, bool delayed, string expected) => + Assert.Equal(expected, InstallFootprint.DescribeStartType(startType, delayed)); + + [Theory] + [InlineData(1, "Disabled")] + [InlineData(3, "Ready")] + [InlineData(4, "Running")] + [InlineData(0, "Unknown")] + public void TaskStatesReadAsWords(int state, string expected) => + Assert.Equal(expected, InstallFootprint.DescribeTaskState(state)); + + [Fact] + public void ASuccessfulRunShowsSucceededWithItsTime() => + Assert.Equal("Succeeded — Oct 12, 2026 3:00 AM", + InstallFootprint.DescribeTaskResult(new DateTime(2026, 10, 12, 3, 0, 0), 0)); + + [Fact] + public void AFailedRunShowsItsHexCode() => + Assert.StartsWith("Failed (0x00000002)", + InstallFootprint.DescribeTaskResult(new DateTime(2026, 10, 12, 3, 0, 0), 2)); + + [Fact] + public void ANegativeResultShowsAsAnHResult() => + Assert.StartsWith("Failed (0x80070005)", + InstallFootprint.DescribeTaskResult(new DateTime(2026, 10, 12, 3, 0, 0), unchecked((int)0x80070005))); + + [Theory] + [InlineData(0x41303)] + [InlineData(0)] + public void ATaskThatHasNotRunSaysSo(int result) => + Assert.Equal("Never run", InstallFootprint.DescribeTaskResult(new DateTime(1899, 12, 30), result)); + + [Theory] + [InlineData(false, 1067, "Exit code 1067")] + [InlineData(true, 0, "—")] + public void ServiceResultsReadAsWords(bool running, int code, string expected) => + Assert.Equal(expected, InstallFootprint.DescribeServiceResult(running, code)); + + [Fact] + public void TheSelfHealScheduleReadsAsDailyAtThree() => + Assert.Equal("Daily at 3:00 AM", InstallFootprint.DescribeTaskTriggers(TaskXml(""" + + 2026-10-12T03:00:00 + true + 1 + + """))); + + [Fact] + public void EveryFewDaysNamesTheInterval() => + Assert.Equal("Every 3 days at 9:30 PM", InstallFootprint.DescribeTaskTriggers(TaskXml(""" + + 2026-10-12T21:30:00-07:00 + 3 + + """))); + + [Fact] + public void WeeklyListsItsDays() => + Assert.Equal("Weekly on Monday, Friday at 8:00 AM", InstallFootprint.DescribeTaskTriggers(TaskXml(""" + + 2026-10-12T08:00:00 + 1 + + """))); + + [Fact] + public void StartupLogonAndRepetitionReadAsWords() => + Assert.Equal("At startup; At logon of any user; Once at Oct 12, 2026 12:00 AM, then every 4 hours", + InstallFootprint.DescribeTaskTriggers(TaskXml(""" + + + + 2026-10-12T00:00:00 + PT4H + + """))); + + [Fact] + public void DisabledTriggersAreLeftOut() => + Assert.Equal("At startup", InstallFootprint.DescribeTaskTriggers(TaskXml(""" + + false + """))); + + [Fact] + public void ATaskWithNoTriggersRunsOnDemand() => + Assert.Equal("On demand only", InstallFootprint.DescribeTaskTriggers(TaskXml(""))); + + [Fact] + public void UnreadableXmlIsUnknown() => + Assert.Equal("Unknown", InstallFootprint.DescribeTaskTriggers(" Date: Mon, 12 Oct 2026 23:39:54 -0700 Subject: [PATCH 2/3] Edit Prefs without an Unlock mode and ask for elevation only at save time Every setting policy does not manage is editable in the normal app. Edits stay pending behind Save and Discard; Save writes directly when elevated, otherwise it raises UAC and runs the app's own executable headless with --apply-settings and a temp JSON file. That writer re-reads policy, skips every managed key, validates the values and exits without a window. A declined prompt keeps the edits pending and says so. Removes the Unlock banner, the whole-app elevated relaunch and the --prefs switch it used. --- README.md | 8 +- .../BootstrapMate.App.csproj | 2 + src/BootstrapMate.App/MainWindow.xaml.cs | 7 +- src/BootstrapMate.App/Program.cs | 31 +++ .../ViewModels/PrefsViewModel.cs | 162 ++++++++++------ src/BootstrapMate.App/Views/PrefsPage.xaml | 63 +++--- src/BootstrapMate.App/Views/PrefsPage.xaml.cs | 12 +- src/BootstrapMate.Core/PrefsElevation.cs | 28 +-- src/BootstrapMate.Core/PrefsPolicy.cs | 5 + src/BootstrapMate.Core/PrefsSettingsFile.cs | 182 ++++++++++++++++++ .../PrefsElevationTests.cs | 51 ++--- .../PrefsSettingsFileTests.cs | 144 ++++++++++++++ 12 files changed, 535 insertions(+), 160 deletions(-) create mode 100644 src/BootstrapMate.App/Program.cs create mode 100644 src/BootstrapMate.Core/PrefsSettingsFile.cs create mode 100644 tests/BootstrapMate.Core.Tests/PrefsSettingsFileTests.cs diff --git a/README.md b/README.md index 637b17f..6bcd0f2 100644 --- a/README.md +++ b/README.md @@ -47,7 +47,7 @@ shared between the two views and is never removed. Deliver a header through policy as usual. The next elevated run moves it into that key and blanks the copy in policy, which every user can read. The policy value is emptied, not deleted, so the setting still shows as managed. The GUI shows a saved header masked and saves a new one -only after Unlock. BootstrapMate never writes a header to its logs, `session.json` or +when you click Save on the Prefs tab. BootstrapMate never writes a header to its logs, `session.json` or `last-run.json`, and it redacts `--headers` from every logged command line. ## Reporting @@ -318,6 +318,12 @@ policy for each, and either one locks the Prefs tab's "Show progress dialog" swi sets the dialog's icon. `SilentMode` and `VerboseMode` from policy or settings turn those modes on, and a CLI switch cannot turn them off. +The GUI Prefs tab edits every setting that policy does not manage; policy-set fields show in gray +under one note at the top of the tab. Edits stay pending until you click Save, which writes them to +`HKLM\SOFTWARE\BootstrapMate\Settings`. An unelevated GUI asks for administrator approval at that +point and writes through a headless, elevated copy of itself (`--apply-settings `), which +re-reads policy and never writes a managed value. Declining the prompt keeps the edits pending. + ## csharpDialog authorisation key When csharpDialog is managed with an authorisation key, it opens only for a caller that diff --git a/src/BootstrapMate.App/BootstrapMate.App.csproj b/src/BootstrapMate.App/BootstrapMate.App.csproj index a5341a8..f7b5304 100644 --- a/src/BootstrapMate.App/BootstrapMate.App.csproj +++ b/src/BootstrapMate.App/BootstrapMate.App.csproj @@ -25,6 +25,8 @@ $(NoWarn);MVVMTK0045 + + $(DefineConstants);DISABLE_XAML_GENERATED_MAIN diff --git a/src/BootstrapMate.App/MainWindow.xaml.cs b/src/BootstrapMate.App/MainWindow.xaml.cs index ea0256f..c0c4688 100644 --- a/src/BootstrapMate.App/MainWindow.xaml.cs +++ b/src/BootstrapMate.App/MainWindow.xaml.cs @@ -44,11 +44,8 @@ public MainWindow() // Apply Mica backdrop for modern Windows 11 look SystemBackdrop = new MicaBackdrop(); - // Open on Prefs when asked to (the elevated relaunch from Unlock passes --prefs); - // Prefs is also the first tab, so this is the default either way. - NavView.SelectedItem = BootstrapMate.Core.PrefsElevation.OpensOnPrefs(Environment.GetCommandLineArgs().Skip(1)) - ? NavView.MenuItems.OfType().First(i => (string?)i.Tag == "prefs") - : NavView.MenuItems[0]; + // Prefs is the first tab. + NavView.SelectedItem = NavView.MenuItems[0]; } private void NavView_SelectionChanged(NavigationView sender, NavigationViewSelectionChangedEventArgs args) diff --git a/src/BootstrapMate.App/Program.cs b/src/BootstrapMate.App/Program.cs new file mode 100644 index 0000000..7134203 --- /dev/null +++ b/src/BootstrapMate.App/Program.cs @@ -0,0 +1,31 @@ +using BootstrapMate.Core; + +namespace BootstrapMate.App; + +/// +/// Entry point. Replaces the XAML-generated Main (DISABLE_XAML_GENERATED_MAIN) so the elevated +/// settings writer (--apply-settings <file>) runs headless and exits before any window exists. +/// +public static class Program +{ + [STAThread] + private static int Main(string[] args) + { + if (PrefsSettingsFile.IsApplyRequest(args)) + { + return PrefsSettingsFile.ApplyPath(args) is { } path + ? PrefsSettingsFile.Apply(path) + : PrefsSettingsFile.ExitUsage; + } + + WinRT.ComWrappersSupport.InitializeComWrappers(); + Microsoft.UI.Xaml.Application.Start(p => + { + var context = new Microsoft.UI.Dispatching.DispatcherQueueSynchronizationContext( + Microsoft.UI.Dispatching.DispatcherQueue.GetForCurrentThread()); + SynchronizationContext.SetSynchronizationContext(context); + new App(); + }); + return 0; + } +} diff --git a/src/BootstrapMate.App/ViewModels/PrefsViewModel.cs b/src/BootstrapMate.App/ViewModels/PrefsViewModel.cs index a5c7265..a4a348e 100644 --- a/src/BootstrapMate.App/ViewModels/PrefsViewModel.cs +++ b/src/BootstrapMate.App/ViewModels/PrefsViewModel.cs @@ -6,13 +6,12 @@ namespace BootstrapMate.App.ViewModels; /// /// ViewModel for the Prefs tab. Mirrors macOS SettingsViewModel. -/// Loads from ConfigManager and shows management lock state. Settings live in HKLM, so the tab is -/// read-only unless this process is elevated; Unlock relaunches the app elevated on this tab. -/// When elevated, non-managed settings auto-save to HKLM through ConfigManager.SaveMachineSettings. +/// Loads from ConfigManager and shows management lock state. Every setting policy does not manage +/// is editable; edits stay pending until Save writes them to HKLM, directly when this process is +/// elevated and otherwise through an elevated, headless copy of the app (UAC at save time). /// public partial class PrefsViewModel : ObservableObject { - private System.Threading.Timer? _autoSaveTimer; private bool _isLoading; // ── Connection ─────────────────────────────────────────────── @@ -54,14 +53,14 @@ public partial class PrefsViewModel : ObservableObject [ObservableProperty] private SaveState _saveStatus = SaveState.Idle; - public enum SaveState { Idle, Saving, Saved, Failed } + public enum SaveState { Idle, Saving, Saved } partial void OnSaveStatusChanged(SaveState value) { - OnPropertyChanged(nameof(SaveStatusGlyph)); OnPropertyChanged(nameof(SaveStatusMessage)); OnPropertyChanged(nameof(IsSaveStatusVisible)); OnPropertyChanged(nameof(IsSaveEnabled)); + OnPropertyChanged(nameof(IsSaveBarVisible)); } // ── Management State ───────────────────────────────────────────── @@ -115,53 +114,110 @@ public double NetworkTimeoutValue partial void OnNetworkTimeoutChanged(int value) => OnPropertyChanged(nameof(NetworkTimeoutValue)); - // ── Elevation State ───────────────────────────────────────── + // ── Pending Changes and Save ──────────────────────────────── - /// True when this process can write HKLM (elevated administrator token). - public bool IsElevated { get; } = PrefsElevation.IsProcessElevated(); + /// True when this process can write HKLM directly (elevated administrator token). + private static readonly bool IsElevated = PrefsElevation.IsProcessElevated(); - public bool IsReadOnly => !IsElevated; + /// True once a setting is edited and until it is saved or discarded. + [ObservableProperty] private bool _hasPendingChanges; - [ObservableProperty] private string _unlockError = ""; + /// Why the last Save did not write, as "Not saved: …"; empty otherwise. + [ObservableProperty] private string _saveError = ""; - public bool HasUnlockError => !string.IsNullOrEmpty(UnlockError); + public bool HasSaveError => !string.IsNullOrEmpty(SaveError); - partial void OnUnlockErrorChanged(string value) => OnPropertyChanged(nameof(HasUnlockError)); + partial void OnSaveErrorChanged(string value) + { + OnPropertyChanged(nameof(HasSaveError)); + OnPropertyChanged(nameof(IsSaveBarVisible)); + } + + partial void OnHasPendingChangesChanged(bool value) => OnPropertyChanged(nameof(IsSaveBarVisible)); + + /// The save bar shows while there is anything to save or report. + public bool IsSaveBarVisible => HasPendingChanges || HasSaveError || IsSaveStatusVisible; /// - /// Relaunches this app elevated through UAC, opening on the Prefs tab. Returns true when the - /// elevated instance started, so the caller can close this one. A cancelled UAC prompt - /// returns false quietly and leaves the tab read-only. + /// Writes the pending values to the machine settings, skipping anything policy manages. + /// Elevated, it writes directly; otherwise it raises UAC and runs this app's own executable + /// headless with the values in a temp file. A declined prompt keeps the edits pending. /// - public bool TryRelaunchElevated() + public async Task SaveAsync() + { + if (!HasPendingChanges || SaveStatus == SaveState.Saving) + return; + + var payload = BuildPayload(); + if (PrefsSettingsFile.Validate(payload) is { } invalid) + { + SaveError = $"Not saved: {invalid}"; + return; + } + + SaveError = ""; + SaveStatus = SaveState.Saving; + string? error; + try + { + error = IsElevated + ? await Task.Run(() => { PrefsSettingsFile.Save(payload, _managedKeys); return (string?)null; }) + : await SaveElevatedAsync(payload); + } + catch (Exception ex) + { + error = $"Not saved: {ex.Message}"; + } + + if (error is not null) + { + SaveStatus = SaveState.Idle; + SaveError = error; + return; + } + + Load(); + SaveStatus = SaveState.Saved; + } + + /// Drops the pending edits and shows the saved values again. + public void Discard() + { + SaveError = ""; + SaveStatus = SaveState.Idle; + Load(); + } + + private static async Task SaveElevatedAsync(PrefsSettingsPayload payload) { - UnlockError = ""; + var exe = Environment.ProcessPath; + if (string.IsNullOrEmpty(exe)) + return "Not saved: could not find the app's own executable."; + + var path = PrefsSettingsFile.WriteTempFile(payload); try { - var exe = Environment.ProcessPath; - if (string.IsNullOrEmpty(exe)) - { - UnlockError = "Could not find the app's own executable to relaunch."; - return false; - } - - using var process = System.Diagnostics.Process.Start(PrefsElevation.BuildElevatedRelaunch(exe)); - return process is not null; + using var process = System.Diagnostics.Process.Start(PrefsElevation.BuildElevatedApply(exe, path)); + if (process is null) + return "Not saved: the elevated writer did not start."; + await process.WaitForExitAsync(); + return process.ExitCode == PrefsSettingsFile.ExitSaved + ? null + : $"Not saved: {PrefsSettingsFile.DescribeExitCode(process.ExitCode)}"; } catch (Exception ex) when (PrefsElevation.IsElevationCancelled(ex)) { - return false; + return "Not saved: administrator approval was declined."; } - catch (Exception ex) + finally { - UnlockError = $"Could not relaunch as administrator: {ex.Message}"; - return false; + try { File.Delete(path); } catch { } } } - // ── Editability (elevated and not managed by policy) ──────── + // ── Editability (only policy locks a setting) ─────────────── - private bool CanEdit(string field) => PrefsElevation.CanEdit(IsElevated, IsLocked(field)); + private bool CanEdit(string field) => PrefsPolicy.CanEdit(field, _managedKeys); private bool IsLocked(string field) => PrefsPolicy.IsLocked(field, _managedKeys); @@ -180,19 +236,10 @@ public bool TryRelaunchElevated() // ── Save Status Display (for x:Bind) ──────────────────────── - public string SaveStatusGlyph => SaveStatus switch - { - SaveState.Saving => "\uE895", - SaveState.Saved => "\uE73E", - SaveState.Failed => "\uE783", - _ => "" - }; - public string SaveStatusMessage => SaveStatus switch { SaveState.Saving => "Saving...", SaveState.Saved => "Saved", - SaveState.Failed => "Save failed — check permissions", _ => "" }; @@ -233,6 +280,7 @@ public void Load() // Notify all bindings (management locks, computed display properties) OnPropertyChanged(string.Empty); + HasPendingChanges = false; _isLoading = false; } @@ -240,12 +288,12 @@ public void Load() private static readonly HashSet _nonSettingProperties = [ - nameof(SaveStatus), nameof(SaveStatusGlyph), nameof(SaveStatusMessage), + nameof(SaveStatus), nameof(SaveStatusMessage), nameof(HasPendingChanges), + nameof(SaveError), nameof(HasSaveError), nameof(IsSaveBarVisible), nameof(IsSaveStatusVisible), nameof(IsSaveEnabled), nameof(HasExistingAuth), nameof(AuthPlaceholderText), nameof(NetworkTimeoutValue), nameof(VersionDisplay), nameof(IsManifestPreviewLoading), nameof(ManifestPreviewContent), nameof(ManifestPreviewError), nameof(HasManifestPreviewContent), nameof(HasManifestPreviewError), - nameof(UnlockError), nameof(HasUnlockError), nameof(HasPolicySettings), nameof(Services), nameof(IsServicesLoading), "", // string.Empty from Load's bulk notify ]; @@ -254,15 +302,13 @@ protected override void OnPropertyChanged(System.ComponentModel.PropertyChangedE { base.OnPropertyChanged(e); - // Not elevated: HKLM is not writable and the tab is read-only, so never save. - if (_isLoading || !IsElevated || _nonSettingProperties.Contains(e.PropertyName ?? "")) + // A setting changed by the user: hold it until Save or Discard. + if (_isLoading || _nonSettingProperties.Contains(e.PropertyName ?? "")) return; - _autoSaveTimer?.Dispose(); - _autoSaveTimer = new System.Threading.Timer(_ => - { - try { ConfigManager.SaveMachineSettings(BuildConfig(), PageKeys); } catch { } - }, null, 500, System.Threading.Timeout.Infinite); + HasPendingChanges = true; + if (SaveStatus == SaveState.Saved) + SaveStatus = SaveState.Idle; } // ── Build Run Arguments ────────────────────────────────────── @@ -304,18 +350,7 @@ public List BuildRunArguments() // ── Private ────────────────────────────────────────────────── - /// - /// The machine settings this tab edits. Saving writes only these, so values the tab does not - /// show (reporting, signature checks, baseline interval) keep whatever HKLM already holds. - /// - private static readonly string[] PageKeys = - [ - "ManifestUrl", "AuthorizationHeader", "SilentMode", "VerboseMode", "DryRun", - "EnableDialog", "NoDialog", "DialogTitle", "DialogMessage", "DialogIcon", "BlurScreen", - "CustomInstallPath", "NetworkTimeout", - ]; - - private BootstrapMateConfig BuildConfig() => new() + private PrefsSettingsPayload BuildPayload() => new() { ManifestUrl = ManifestUrl, AuthorizationHeader = string.IsNullOrWhiteSpace(AuthorizationHeader) ? null : AuthorizationHeader, @@ -323,7 +358,6 @@ public List BuildRunArguments() VerboseMode = VerboseMode, DryRun = DryRun, EnableDialog = EnableDialog, - NoDialog = !EnableDialog, DialogTitle = DialogTitle, DialogMessage = DialogMessage, DialogIcon = string.IsNullOrWhiteSpace(DialogIcon) ? null : DialogIcon, diff --git a/src/BootstrapMate.App/Views/PrefsPage.xaml b/src/BootstrapMate.App/Views/PrefsPage.xaml index 3098d7e..9c3fac9 100644 --- a/src/BootstrapMate.App/Views/PrefsPage.xaml +++ b/src/BootstrapMate.App/Views/PrefsPage.xaml @@ -60,45 +60,38 @@ Foreground="{ThemeResource TextFillColorSecondaryBrush}" /> - - - - - - - - - - - - - - + + + + + + + + + + Visibility="{x:Bind ViewModel.HasSaveError, Mode=OneWay, Converter={StaticResource BoolToVisibility}}" /> - - - - - - + +