{"repo_name": "CrapFixer", "file_name": "/CrapFixer/CFixer/MainForm.cs", "inference_info": {"prefix_code": "using CFixer;\nusing CFixer.Properties;\nusing CFixer.Views;\nusing System;\nusing System.Diagnostics;\nusing System.Drawing;\nusing System.Drawing.Drawing2D;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing System.Windows.Forms;\n\nnamespace CrapFixer\n{\n public partial class MainForm : Form\n {\n private NavigationManager _navigationManager;\n private NavigationHandler _navigationHandler;\n private LogActions _logActions;\n private LogActionsController _logActionsController;\n private readonly AppManagerService _appManager = new AppManagerService();\n\n public MainForm()\n {\n InitializeComponent();\n IniStateManager.ApplyWindowState(this);\n\n // Set up the main navigation manager and logger\n _navigationManager = new NavigationManager(panelContainer);\n Logger.OutputBox = rtbLogger;\n\n // Set up log actions controller\n _logActions = new LogActions(rtbLogger);\n }\n\n private async void MainForm_Shown(object sender, EventArgs e)\n {\n await InitializeUI(); // _ = InitializeUI();\n InitializeAppState();\n }\n\n private void InitializeAppState()\n {\n // Load features and plugins into the tree view\n FeatureNodeManager.LoadFeatures(treeFeatures);\n PluginManager.LoadPlugins(treeFeatures);\n\n // Load settings from INI file if enabled\n IniStateManager.LoadFeaturesIfEnabled(treeFeatures);\n }\n\n private async Task InitializeUI()\n {\n // Initialize the navigation handler with buttons\n _navigationHandler = new NavigationHandler(btnFixer, btnRestore, btnTools, btnGitHub);\n\n // Load navigation icons\n await _navigationHandler.LoadNavigationIcons();\n\n // Register navigation handler\n _navigationHandler.NavigationButtonClicked += NavigationHandler_NavigationButtonClicked;\n\n // Register click handlers for GitHub links\n pictureHeader.Click += PictureHeader_Click;\n lblHeader.Click += PictureHeader_Click;\n\n // Re-initialize log actions controller (optional if not changed)\n _logActionsController = new LogActionsController(comboLogActions, _logActions);\n\n // Set version and OS info\n lblVersionInfo.Text = $\"v{Program.GetAppVersion()} \";\n lblOSInfo.Text = await OSHelper.OSHelper.GetWindowsVersion();\n }\n\n // Handles navigation button clicks and switches views accordingly\n ", "suffix_code": "\n\n private async void btnAnalyze_Click(object sender, EventArgs e)\n {\n // Analyze features\n await FeatureNodeManager.AnalyzeAll(treeFeatures.Nodes);\n\n // Analyze plugins\n await PluginManager.AnalyzeAllPlugins(treeFeatures.Nodes);\n\n // Analyze apps\n await AnalyzeApps();\n\n // Show log actions combo box\n comboLogActions.Visible = true;\n }\n\n /// \n /// Analyzes the apps and logs the results.\n /// \n private async Task AnalyzeApps()\n {\n checkedListBoxApps.Items.Clear();\n\n // Try loading patterns from CFEnhancer.txt (located in Plugins folder)\n var (bloatwarePatterns, whitelistPatterns, scanAll) = _appManager.LoadExternalBloatwarePatterns();\n\n if (bloatwarePatterns.Length == 0 && !scanAll)\n {\n // Fallback to internal resource if external file not found or empty and scanAll is not enabled\n bloatwarePatterns = Resources.PredefinedApps?\n .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)\n .Select(s => s.Trim().ToLower()).ToArray() ?? Array.Empty();\n\n whitelistPatterns = Array.Empty();\n Logger.Log(\"Using built-in bloatware list.\", LogLevel.Info);\n }\n else\n {\n Logger.Log(\"🔎 Plugin ready: CFEnhancer (external bloatware list)\", LogLevel.Info);\n }\n\n // Analyze installed apps based on patterns and whitelist, and optionally scan all\n var apps = await _appManager.AnalyzeAndLogAppsAsync(bloatwarePatterns, whitelistPatterns, scanAll);\n\n foreach (var app in apps)\n {\n checkedListBoxApps.Items.Add(app.FullName);\n }\n }\n\n private async void btnFix_Click(object sender, EventArgs e)\n {\n rtbLogger.Clear();\n\n // Fix all features\n foreach (TreeNode node in treeFeatures.Nodes)\n await FeatureNodeManager.FixChecked(node);\n\n // Fix all plugins\n foreach (TreeNode node in treeFeatures.Nodes)\n await PluginManager.FixChecked(node);\n\n // Fix selected Store apps\n var selectedApps = checkedListBoxApps.CheckedItems.Cast().ToList();\n if (selectedApps.Count == 0)\n return;\n\n var appService = new AppManagerService();\n var removedApps = await appService.UninstallSelectedAppsAsync(selectedApps);\n\n // Update UI after uninstall\n foreach (var app in removedApps)\n {\n checkedListBoxApps.Items.Remove(app);\n }\n }\n\n private void btnRestore_Click(object sender, EventArgs e)\n {\n var result = MessageBox.Show(\n \"⚠️ This will restore all selected features to their original state.\\n\" +\n \"Changes made by previous configurations may be reverted.\\n\\n\" +\n \"Are you sure you want to proceed?\",\n \"Restore Selected Features\",\n MessageBoxButtons.YesNo,\n MessageBoxIcon.Warning);\n\n if (result == DialogResult.Yes)\n {\n rtbLogger.Clear();\n foreach (TreeNode node in treeFeatures.Nodes)\n FeatureNodeManager.RestoreChecked(node);\n\n Logger.Log(\"↩️ All selected features have been restored.\", LogLevel.Info);\n }\n }\n\n /// \n /// Analyzes all plugins and features starting from the selected node from the context menu.\n /// \n private async void analyzeMarkedFeatureToolStripMenuItem_Click(object sender, EventArgs e)\n {\n if (treeFeatures.SelectedNode is TreeNode selectedNode)\n {\n Logger.Log($\"🔎 Analyzing Feature: {selectedNode.Text}\", LogLevel.Info);\n\n // If a single node is selected (leaf node with no children),\n // always analyze this node regardless of its Checked state.\n if (selectedNode.Nodes.Count == 0)\n {\n await PluginManager.AnalyzePlugin(selectedNode);\n }\n else\n {\n // If a parent node is selected (has children),\n // recursively analyze only the checked plugin nodes.\n await PluginManager.AnalyzeAll(selectedNode);\n }\n\n // Perform feature-specific analysis (non-plugin)\n FeatureNodeManager.AnalyzeFeature(selectedNode);\n }\n }\n\n /// \n /// Fixes all checked plugin and feature nodes starting from the selected node from the context menu.\n /// \n private async void fixMarkedFeatureToolStripMenuItem_Click(object sender, EventArgs e)\n {\n if (treeFeatures.SelectedNode is TreeNode selectedNode)\n {\n Logger.Log($\"🔧 Fixing Feature: {selectedNode.Text}\", LogLevel.Info);\n\n // Recursively fix all checked feature nodes (non-plugin)\n await FeatureNodeManager.FixFeature(selectedNode);\n\n // Recursively fix all checked plugin nodes starting from the selected node\n await PluginManager.FixPlugin(selectedNode);\n }\n }\n\n /// \n /// Restores the selected plugin or feature to its previous state from the context menu.\n /// \n private async void restoreMarkedFeatureToolStripMenuItem_Click(object sender, EventArgs e)\n {\n if (treeFeatures.SelectedNode is TreeNode selectedNode)\n {\n if (PluginManager.IsPluginNode(selectedNode))\n // Restore the plugin using its Undo command if available!\n await PluginManager.RestorePlugin(selectedNode);\n else\n Logger.Log($\"↩️ Restoring Feature: {selectedNode.Text}\", LogLevel.Info);\n\n // Perform feature-specific restore (non-plugin)\n FeatureNodeManager.RestoreFeature(selectedNode);\n }\n }\n\n private void helpMarkedFeatureToolStripMenuItem_Click(object sender, EventArgs e)\n {\n if (treeFeatures.SelectedNode is TreeNode selectedNode)\n {\n FeatureNodeManager.ShowHelp(selectedNode);\n }\n }\n\n /// \n /// Checks or unchecks all child nodes when a parent node is checked/unchecked.\n /// \n /// \n /// \n private void treeFeatures_AfterCheck(object sender, TreeViewEventArgs e)\n {\n if (e.Action != TreeViewAction.Unknown)\n {\n foreach (TreeNode child in e.Node.Nodes)\n child.Checked = e.Node.Checked;\n }\n }\n\n private void treeFeatures_MouseDown(object sender, MouseEventArgs e)\n {\n if (e.Button == MouseButtons.Right)\n {\n // Get the node under the mouse cursor\n TreeNode nodeUnderMouse = treeFeatures.GetNodeAt(e.X, e.Y);\n\n if (nodeUnderMouse != null)\n {\n treeFeatures.SelectedNode = nodeUnderMouse;\n\n // Show the context menu at the mouse position\n contextMenuStrip.Show(treeFeatures, e.Location);\n }\n }\n }\n\n /// \n /// Handles the link click event for selecting or deselecting all items in the list.\n /// \n /// \n /// \n private bool treeChecked = false;\n\n private void linkSelection_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)\n {\n if (tabControl.SelectedTab == Windows)\n {\n foreach (TreeNode node in treeFeatures.Nodes)\n {\n node.Checked = treeChecked;\n foreach (TreeNode child in node.Nodes)\n {\n child.Checked = treeChecked;\n foreach (TreeNode grandChild in child.Nodes)\n grandChild.Checked = treeChecked;\n }\n }\n\n treeChecked = !treeChecked;\n }\n else if (tabControl.SelectedTab == Apps)\n {\n bool shouldCheck = checkedListBoxApps.Items.Cast()\n .Any(item => checkedListBoxApps.GetItemChecked(checkedListBoxApps.Items.IndexOf(item)) == false);\n\n for (int i = 0; i < checkedListBoxApps.Items.Count; i++)\n {\n checkedListBoxApps.SetItemChecked(i, shouldCheck);\n }\n }\n }\n\n private void panelHeader_Paint(object sender, PaintEventArgs e)\n {\n var panel = sender as Panel;\n var g = e.Graphics;\n\n // Solid background: #4D4D4D\n g.Clear(Color.FromArgb(77, 77, 77));\n\n // Inset line effect (3D-like): light line + shadow line\n Color baseColor = Color.FromArgb(80, 80, 80); // inset base\n\n using (var topLine = new Pen(ControlPaint.Light(baseColor, 0.0f)))\n using (var bottomLine = new Pen(ControlPaint.Dark(baseColor, 0.2f)))\n {\n g.SmoothingMode = SmoothingMode.None;\n g.DrawLine(topLine, 0, panel.Height - 2, panel.Width, panel.Height - 2);\n g.DrawLine(bottomLine, 0, panel.Height - 1, panel.Width, panel.Height - 1);\n }\n }\n\n // Handles click on the header image to open the GitHub page\n private void PictureHeader_Click(object sender, EventArgs e)\n {\n Utils.OpenGitHubPage(sender, e);\n }\n\n // Handles link click to check for updates\n private void linkUpdateCheck_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)\n {\n var updateUrl = $\"https://builtbybel.github.io/CrapFixer/update-check.html?version={Program.GetAppVersion()}\";\n\n var psi = new ProcessStartInfo\n {\n FileName = updateUrl,\n UseShellExecute = true\n };\n Process.Start(psi);\n }\n\n private void MainForm_FormClosing(object sender, FormClosingEventArgs e)\n {\n if (IniStateManager.IsViewSettingEnabled(\"SETTINGS\", \"checkSaveToINI\"))\n {\n IniStateManager.Save(treeFeatures, this);\n }\n\n Logger.OutputBox = null; // Remove reference\n }\n\n private void btnGitHub_Click(object sender, EventArgs e)\n {\n _navigationManager.SwitchView(new OptionsView());\n }\n }\n}", "middle_code": "private void NavigationHandler_NavigationButtonClicked(Button button)\n {\n if (button == btnFixer)\n {\n _navigationManager.GoToMain();\n }\n else if (button == btnTools)\n {\n _navigationManager.SwitchView(new OptionsView());\n }\n }", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "c_sharp", "sub_task_type": null}, "context_code": [["/CrapFixer/CFixer/Features/FeatureManager.cs", "using Features;\nusing System;\nusing System.Diagnostics;\nusing System.Drawing;\nusing System.Threading.Tasks;\nusing System.Windows.Forms;\n\nnamespace CrapFixer\n{\n /// \n /// Provides operations to load, analyze, fix, restore, and show help for FeatureNodes.\n /// \n public static class FeatureNodeManager\n {\n private static int totalChecked;\n private static int issuesFound;\n\n // Public properties to access the analysis results\n public static int TotalChecked => totalChecked;\n\n public static int IssuesFound => issuesFound;\n\n public static void ResetAnalysis()\n {\n totalChecked = 0;\n issuesFound = 0;\n Logger.Clear();\n }\n\n /// \n /// Loads all features into the TreeView.\n /// \n public static void LoadFeatures(TreeView tree)\n {\n // Hide the TreeView to avoid flickering and visible scroll jump\n tree.Visible = false;\n\n var features = FeatureLoader.Load();\n tree.Nodes.Clear();\n\n foreach (var feature in features)\n AddNode(tree.Nodes, feature);\n\n // root nodes (categories)\n foreach (TreeNode root in tree.Nodes)\n {\n root.NodeFont = new Font(tree.Font, FontStyle.Bold);\n root.ForeColor = Color.RoyalBlue; // category color\n }\n\n tree.ExpandAll(); // expand all nodes\n\n // Set scroll to top and make TreeView visible\n tree.BeginInvoke(new Action(() =>\n {\n // Ensure the first node is shown at the top (prevents auto-scroll to bottom)\n if (tree.Nodes.Count > 0) tree.TopNode = tree.Nodes[0];\n tree.Visible = true;\n }));\n }\n\n /// \n /// Recursively adds a FeatureNode and its children into the TreeView.\n /// \n private static void AddNode(TreeNodeCollection treeNodes, FeatureNode featureNode)\n {\n string text = featureNode.IsCategory\n ? \" \" + featureNode.Name + \" \" // add extra space to avoid clipping\n : featureNode.Name;\n\n TreeNode node = new TreeNode(text)\n {\n Tag = featureNode,\n Checked = featureNode.DefaultChecked,\n };\n treeNodes.Add(node);\n\n foreach (var child in featureNode.Children)\n AddNode(node.Nodes, child);\n }\n\n /// \n /// Analyzes all checked features recursively and logs only issues.\n /// \n public static async Task AnalyzeAll(TreeNodeCollection nodes)\n {\n ResetAnalysis();\n\n // Iterate through all nodes and analyze each one recursively\n foreach (TreeNode node in nodes)\n {\n // Recursively analyze each node and ensure async tasks are awaited\n await AnalyzeCheckedRecursive(node);\n }\n\n Logger.Log(\"🔎 ANALYSIS COMPLETE\", LogLevel.Info);\n Logger.Log(new string('=', 50), LogLevel.Info);\n\n int ok = totalChecked - issuesFound;\n Logger.Log($\"Summary: {ok} of {totalChecked} checked settings are OK; {issuesFound} require attention.\",\n issuesFound > 0 ? LogLevel.Warning : LogLevel.Info);\n }\n\n /// \n /// Recursively checks all features and logs misconfigurations.\n /// \n private static async Task AnalyzeCheckedRecursive(TreeNode node)\n {\n if (node.Tag is FeatureNode fn)\n {\n // If the node is not a category, is checked, and has a feature to check\n if (!fn.IsCategory && node.Checked && fn.Feature != null)\n {\n totalChecked++;\n bool isOk = await fn.Feature.CheckFeature(); // Await the async operation\n\n if (!isOk)\n {\n issuesFound++;\n node.ForeColor = Color.Red; // Mark as misconfigured\n string category = node.Parent?.Text ?? \"General\";\n Logger.Log($\"❌ [{category}] {fn.Name} - Not configured as recommended.\");\n Logger.Log($\" ➤ {fn.Feature.GetFeatureDetails()}\");\n // Log a separator when an issue was found\n Logger.Log(new string('-', 50), LogLevel.Info);\n }\n else\n {\n node.ForeColor = Color.Gray; // Mark as properly configured\n }\n }\n\n // Recursively process child nodes and ensure awaiting the tasks\n foreach (TreeNode child in node.Nodes)\n {\n await AnalyzeCheckedRecursive(child); // Recursively call and await the result\n }\n }\n }\n\n /// \n /// Fixes all checked features recursively.\n /// \n public static async Task FixChecked(TreeNode node)\n {\n if (node.Tag is FeatureNode fn)\n {\n if (!fn.IsCategory && node.Checked && fn.Feature != null)\n {\n bool result = await fn.Feature.DoFeature();\n Logger.Log(result\n ? $\"🔧 {fn.Name} - Fixed\"\n : $\"❌ {fn.Name} - ⚠️ Fix failed (This feature may require admin privileges)\",\n result ? LogLevel.Info : LogLevel.Error);\n }\n\n foreach (TreeNode child in node.Nodes)\n await FixChecked(child);\n }\n }\n\n /// \n /// Restores all checked features recursively.\n /// \n public static void RestoreChecked(TreeNode node)\n {\n if (node.Tag is FeatureNode fn)\n {\n if (!fn.IsCategory && node.Checked && fn.Feature != null)\n {\n bool ok = fn.Feature.UndoFeature();\n string category = node.Parent?.Text ?? \"General\";\n Logger.Log(ok\n ? $\"↩️ [{category}] {fn.Name} - Restored\"\n : $\"❌ [{category}] {fn.Name} - Restore failed\",\n ok ? LogLevel.Info : LogLevel.Error);\n }\n\n foreach (TreeNode child in node.Nodes)\n RestoreChecked(child);\n }\n }\n /// \n /// Analyzes a selected feature or, if it's a category, analyzes only checked child features.\n /// \n public static async void AnalyzeFeature(TreeNode node)\n {\n // Analyze this node if it's a leaf node (not a category)\n if (node.Tag is FeatureNode fn && !fn.IsCategory && fn.Feature != null)\n {\n bool isOk = await fn.Feature.CheckFeature();\n node.ForeColor = isOk ? Color.Gray : Color.Red;\n\n if (isOk)\n {\n Logger.Log($\"✅ Feature: {fn.Name} is properly configured.\", LogLevel.Info);\n }\n else\n {\n string category = node.Parent?.Text ?? \"General\";\n Logger.Log($\"❌ Feature: {fn.Name} requires attention.\", LogLevel.Warning);\n Logger.Log($\" ➤ {fn.Feature.GetFeatureDetails()}\");\n Logger.Log(new string('-', 50), LogLevel.Info);\n }\n }\n else\n {\n // If it's a category node, analyze only checked child nodes\n foreach (TreeNode child in node.Nodes)\n {\n if (child.Checked)\n AnalyzeFeature(child);\n }\n }\n }\n\n\n /// \n /// Attempts to fix the selected feature or, if it is a category, fixes only checked child features.\n /// \n public static async Task FixFeature(TreeNode node)\n {\n // Try to fix this node if it is NOT a category (i.e., a leaf node)\n if (node.Tag is FeatureNode fn && !fn.IsCategory && fn.Feature != null)\n {\n // Always fix the selected leaf node, regardless of Checked\n bool result = await fn.Feature.DoFeature();\n Logger.Log(result\n ? $\"🔧 {fn.Name} - Fixed\"\n : $\"❌ {fn.Name} - ⚠️ Fix failed (This feature may require admin privileges)\",\n result ? LogLevel.Info : LogLevel.Error);\n }\n else\n {\n // If it's a category node, fix only checked child nodes (recursively)\n foreach (TreeNode child in node.Nodes)\n {\n if (child.Checked)\n await FixFeature(child);\n }\n }\n }\n\n\n /// \n /// Restores a selected feature (always) or, if it's a category, only restores checked child features.\n /// Logs success or failure.\n /// \n public static void RestoreFeature(TreeNode node)\n {\n // Restore feature node regardless of Checked state\n if (node.Tag is FeatureNode fn && !fn.IsCategory && fn.Feature != null)\n {\n bool ok = fn.Feature.UndoFeature();\n Logger.Log(ok\n ? $\"↩️ {fn.Name} - Restored\"\n : $\"❌ {fn.Name} - Restore failed\",\n ok ? LogLevel.Info : LogLevel.Error);\n }\n else\n {\n // For category nodes, only restore checked children\n foreach (TreeNode child in node.Nodes)\n {\n if (child.Checked)\n RestoreFeature(child);\n }\n }\n }\n\n\n /// \n /// Displays help information for the selected feature or plugin.\n /// If a feature is selected, also offers to search online.\n /// \n public static void ShowHelp(TreeNode node)\n {\n // Show help for features\n if (node?.Tag is FeatureNode fn && fn.Feature != null)\n {\n string info = fn.Feature.Info();\n MessageBox.Show(\n !string.IsNullOrEmpty(info) ? info : \"No additional information available.\",\n $\"Help: {fn.Name}\",\n MessageBoxButtons.OK,\n MessageBoxIcon.Information);\n\n // Optional online help\n var result = MessageBox.Show(\n \"Would you like to search online for more information about this feature?\",\n \"Online Help\",\n MessageBoxButtons.YesNo,\n MessageBoxIcon.Question);\n\n if (result == DialogResult.Yes)\n {\n string searchQuery = Uri.EscapeDataString(fn.Feature.GetFeatureDetails());\n string webUrl = $\"https://www.google.com/search?q={searchQuery}\";\n System.Diagnostics.Process.Start(new ProcessStartInfo\n {\n FileName = webUrl,\n UseShellExecute = true\n });\n }\n\n return;\n }\n\n // Show help for plugins\n if (!PluginManager.ShowHelp(node))\n {\n MessageBox.Show(\"⚠️ No feature or plugin selected, or help info unavailable.\",\n \"Help\",\n MessageBoxButtons.OK,\n MessageBoxIcon.Warning);\n }\n }\n }\n}"], ["/CrapFixer/CFixer/AppManagerService.cs", "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Windows.Foundation;\nusing Windows.Management.Deployment;\n\nnamespace CrapFixer\n{\n public class AppAnalysisResult\n {\n public string AppName { get; set; }\n public string FullName { get; set; }\n }\n\n public class AppManagerService\n {\n private Dictionary _appDirectory = new Dictionary();\n\n // Loads all apps and stores them in the directory (name -> fullName)\n private async Task LoadAppsAsync()\n {\n _appDirectory.Clear();\n\n var pm = new PackageManager();\n var packages = await Task.Run(() =>\n pm.FindPackagesForUserWithPackageTypes(string.Empty, PackageTypes.Main));\n\n foreach (var p in packages)\n {\n string name = p.Id.Name;\n string fullName = p.Id.FullName;\n\n if (!_appDirectory.ContainsKey(name))\n {\n _appDirectory[name] = fullName;\n }\n }\n Logger.Log($\"(Checked against {_appDirectory.Count} apps from the system)\");\n }\n\n /// \n /// Analyzes the installed apps against provided bloatware patterns and whitelist,\n /// logs the results, and returns the matches.\n /// \n /// List of bloatware keywords to check against\n /// List of app names to ignore\n /// If true, scans all apps regardless of bloatware patterns\n public async Task> AnalyzeAndLogAppsAsync(\n string[] bloatwarePatterns,\n string[] whitelistPatterns,\n bool scanAll)\n {\n var apps = await AnalyzeAppsAsync(bloatwarePatterns, whitelistPatterns, scanAll);\n\n if (apps.Count > 0)\n {\n Logger.Log(\"Bloatware apps detected:\", LogLevel.Info);\n foreach (var app in apps)\n {\n Logger.Log($\"❌ [ Bloatware ] {app.AppName} ({app.FullName})\", LogLevel.Warning);\n }\n }\n else\n {\n Logger.Log(\"✅ No Microsoft Store bloatware apps found.\", LogLevel.Info);\n }\n\n Logger.Log(\"\"); // Add a blank line for spacing\n\n return apps;\n }\n\n /// \n /// Analyzes the apps based on predefined apps (from resources) and returns matching apps.\n /// \n /// \n /// \n public async Task> AnalyzeAppsAsync(string[] bloatwarePatterns, string[] whitelistPatterns, bool scanAll = false)\n {\n Logger.Log(\"\\n🧩 APPS ANALYSIS\", LogLevel.Info);\n Logger.Log(new string('=', 50), LogLevel.Info);\n\n await LoadAppsAsync(); // Load all installed apps\n\n var result = new List();\n\n foreach (var app in _appDirectory)\n {\n string appName = app.Key.ToLower();\n\n // Always skip whitelisted apps\n if (whitelistPatterns.Any(w => appName.Contains(w)))\n continue;\n\n if (scanAll)\n {\n // If wildcard is set, include everything not whitelisted\n result.Add(new AppAnalysisResult\n {\n AppName = app.Key,\n FullName = app.Value\n });\n }\n else\n {\n // Only match against provided patterns\n foreach (var pattern in bloatwarePatterns)\n {\n if (appName.Contains(pattern))\n {\n result.Add(new AppAnalysisResult\n {\n AppName = app.Key,\n FullName = app.Value\n });\n break;\n }\n }\n }\n }\n\n return result;\n }\n\n // Uninstall an app by its full name\n public async Task UninstallApp(string fullName)\n {\n try\n {\n var pm = new PackageManager();\n var operation = pm.RemovePackageAsync(fullName);\n\n var resetEvent = new ManualResetEvent(false);\n operation.Completed = (o, s) => resetEvent.Set();\n await Task.Run(() => resetEvent.WaitOne());\n\n if (operation.Status == AsyncStatus.Completed)\n {\n Logger.Log($\"Successfully uninstalled app: {fullName}\");\n return true;\n }\n else\n {\n Logger.Log($\"Failed to uninstall appe: {fullName}\", LogLevel.Warning);\n return false;\n }\n }\n catch (Exception ex)\n {\n Logger.Log($\"Error during uninstalling app {fullName}: {ex.Message}\", LogLevel.Warning);\n return false;\n }\n }\n\n /// \n /// Uninstalls the selected apps and logs the results.\n /// \n /// \n /// \n public async Task> UninstallSelectedAppsAsync(List selectedApps)\n {\n List removedApps = new List();\n\n foreach (var fullName in selectedApps)\n {\n Logger.Log($\"🗑️ Removing app: {fullName}...\");\n\n // Uninstall the app using its full name\n var success = await UninstallApp(fullName);\n if (success)\n {\n removedApps.Add(fullName);\n }\n }\n\n // Log results for apps that were successfully removed\n foreach (var app in removedApps)\n {\n Logger.Log($\"🗑️ Removed Store App: {app}\");\n }\n\n // Log failed attempts\n var failedApps = selectedApps.Except(removedApps).ToList();\n foreach (var app in failedApps)\n {\n Logger.Log($\"⚠️ Failed to remove Store App: {app}\", LogLevel.Warning);\n }\n\n Logger.Log(\"App cleanup complete.\");\n\n return removedApps; // Return removed apps to update the UI\n }\n\n\n /// \n /// Loads external bloatware and whitelist patterns from a text file (e.g., CFEnhancer.txt).\n /// Also checks if wildcard (*) is set to scan all apps.\n /// \n /// Name of the file to load from (must be in Plugins folder)\n /// \n /// A tuple containing:\n /// - bloatwarePatterns: List of apps to flag as bloatware\n /// - whitelistPatterns: List of apps to ignore/exclude from detection\n /// - scanAll: Whether all apps should be shown regardless of matching patterns\n /// \n public (string[] bloatwarePatterns, string[] whitelistPatterns, bool scanAll) LoadExternalBloatwarePatterns(string fileName = \"CFEnhancer.txt\")\n {\n try\n {\n string exeDir = AppDomain.CurrentDomain.BaseDirectory;\n string fullPath = Path.Combine(exeDir, \"Plugins\", fileName);\n\n if (!File.Exists(fullPath))\n {\n Logger.Log($\"⚠️ The bloatware radar stays basic for now 🧠. Get the enhanced detection list from Options > Plugins > CFEnhancer plugin\", LogLevel.Warning);\n return (Array.Empty(), Array.Empty(), false);\n }\n\n var lines = File.ReadAllLines(fullPath);\n var bloatware = new List(); // Apps to detect as bloatware\n var whitelist = new List(); // Apps to ignore completely\n bool scanAll = false; // Set to true if wildcard (*) is present\n\n foreach (var line in lines)\n {\n // Strip comments after \"#\" and trim whitespace\n var entry = line.Split('#')[0].Trim();\n\n // Skip empty lines or lines with only comments\n if (string.IsNullOrWhiteSpace(entry))\n continue;\n\n // Wildcard entry means: show all installed apps\n if (entry == \"*\" || entry == \"*.*\")\n {\n scanAll = true;\n continue;\n }\n\n // Entries starting with \"!\" go to the whitelist (excluded apps)\n if (entry.StartsWith(\"!\"))\n whitelist.Add(entry.Substring(1).Trim().ToLower());\n else\n bloatware.Add(entry.ToLower()); // All other entries are bloatware patterns\n }\n\n return (bloatware.ToArray(), whitelist.ToArray(), scanAll);\n }\n catch (Exception ex)\n {\n Logger.Log($\"Error reading external bloatware file: {ex.Message}\", LogLevel.Warning);\n return (Array.Empty(), Array.Empty(), false);\n }\n }\n\n\n /// \n /// OPTIONALLY!Returns all installed apps in the system.\n /// \n /// \n public async Task> GetAllInstalledAppsAsync()\n {\n await LoadAppsAsync();\n\n return _appDirectory.Select(kvp => new AppAnalysisResult\n {\n AppName = kvp.Key,\n FullName = kvp.Value\n }).ToList();\n }\n }\n}"], ["/CrapFixer/CFixer/PluginManager.cs", "using System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Drawing;\nusing System.IO;\nusing System.Text;\nusing System.Text.RegularExpressions;\nusing System.Threading.Tasks;\nusing System.Windows.Forms;\n\n/// \n/// Provides functionality to load, execute, analyze, and fix external PowerShell-based plugins.\n/// \n///\npublic static class PluginManager\n{\n /// 1. Execute a PowerShell script asynchronously and log output/errors.\n public static async Task ExecutePlugin(string pluginPath)\n {\n try\n {\n using (var process = new Process())\n {\n process.StartInfo.FileName = \"powershell.exe\";\n process.StartInfo.Arguments = $\"-NoProfile -ExecutionPolicy Bypass -File \\\"{pluginPath}\\\"\";\n process.StartInfo.RedirectStandardOutput = true;\n process.StartInfo.RedirectStandardError = true;\n process.StartInfo.UseShellExecute = false;\n process.StartInfo.CreateNoWindow = true;\n\n process.OutputDataReceived += (s, e) =>\n {\n if (!string.IsNullOrEmpty(e.Data))\n Logger.Log($\"[PS Output] {e.Data}\");\n };\n\n process.ErrorDataReceived += (s, e) =>\n {\n if (!string.IsNullOrEmpty(e.Data))\n Logger.Log($\"[PS Error] {e.Data}\", LogLevel.Error);\n };\n\n process.Start();\n process.BeginOutputReadLine();\n process.BeginErrorReadLine();\n\n await Task.Run(() => process.WaitForExit());\n Logger.Log($\"✅ Script executed: {Path.GetFileName(pluginPath)}\");\n }\n }\n catch (Exception ex)\n {\n Logger.Log($\"❌ Error executing script: {ex.Message}\", LogLevel.Error);\n }\n }\n\n /// 2. Load all .ps1 plugin files from the 'plugins' folder into a TreeView.\n public static void LoadPlugins(TreeView treeView)\n {\n string pluginsFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, \"plugins\");\n\n if (!Directory.Exists(pluginsFolder))\n {\n Directory.CreateDirectory(pluginsFolder);\n return;\n }\n\n var pluginsNode = new TreeNode(\"Plugins\")\n {\n BackColor = Color.Magenta,\n ForeColor = Color.White\n };\n\n foreach (var scriptPath in Directory.GetFiles(pluginsFolder, \"*.ps1\"))\n {\n var scriptName = Path.GetFileNameWithoutExtension(scriptPath);\n var scriptNode = new TreeNode\n {\n Text = $\"{scriptName}\", // [PS]\n ToolTipText = scriptPath,\n Tag = scriptPath,\n Checked = false\n };\n pluginsNode.Nodes.Add(scriptNode);\n }\n\n treeView.Nodes.Add(pluginsNode);\n treeView.ExpandAll();\n }\n\n /// 3. Parse the [Commands] section from plugin content.\n private static Dictionary ParseCommands(string pluginContent)\n {\n return ParseSection(pluginContent, \"Commands\");\n }\n\n /// 4. Parse the [Expect] section from plugin content.\n private static Dictionary ParseExpect(string pluginContent)\n {\n return ParseSection(pluginContent, \"Expect\");\n }\n\n /// 5. Generic parser for named sections like [Commands] or [Expect].\n /// Lines must be in 'key = value' format.\n private static Dictionary ParseSection(string content, string sectionName)\n {\n var result = new Dictionary(StringComparer.OrdinalIgnoreCase);\n var lines = content.Split(new[] { '\\r', '\\n' }, StringSplitOptions.RemoveEmptyEntries);\n\n bool insideSection = false;\n foreach (var line in lines)\n {\n var trimmed = line.Trim();\n if (trimmed.Equals($\"[{sectionName}]\", StringComparison.OrdinalIgnoreCase))\n {\n insideSection = true;\n continue;\n }\n // Exit the section when another section begins\n if (insideSection)\n {\n if (trimmed.StartsWith(\"[\") && trimmed.EndsWith(\"]\"))\n break;\n\n // Parse lines of form: key = value\n var idx = trimmed.IndexOf('=');\n if (idx > 0)\n {\n var key = trimmed.Substring(0, idx).Trim();\n var val = trimmed.Substring(idx + 1).Trim();\n result[key] = val;\n }\n }\n }\n\n return result;\n }\n\n /// 6. Execute a shell command (CMD) and return exit code and output.\n private static async Task<(int exitCode, string output)> ExecuteCommand(string command)\n {\n var process = new Process();\n var outputBuilder = new StringBuilder();\n\n process.StartInfo.FileName = \"cmd.exe\";\n process.StartInfo.Arguments = $\"/c \\\"{command}\\\"\";\n process.StartInfo.RedirectStandardOutput = true;\n process.StartInfo.RedirectStandardError = true;\n process.StartInfo.UseShellExecute = false;\n process.StartInfo.CreateNoWindow = true;\n\n process.OutputDataReceived += (s, e) => { if (e.Data != null) outputBuilder.AppendLine(e.Data); };\n process.ErrorDataReceived += (s, e) => { if (e.Data != null) outputBuilder.AppendLine(e.Data); };\n\n process.Start();\n process.BeginOutputReadLine();\n process.BeginErrorReadLine();\n\n await Task.Run(() => process.WaitForExit());\n\n return (process.ExitCode, outputBuilder.ToString());\n }\n\n /// \n /// 7. Analyzes a single plugin node by running its 'Check' command\n /// and comparing the output against expected values defined in the [Expect] section.\n /// Logs a summary indicating success if all checks pass, or warnings if mismatches occur.\n /// Only the specified plugin node is analyzed, regardless of its checked state.\n /// \n /// The TreeNode representing the plugin to analyze, with script path stored in Tag.\n public static async Task AnalyzePlugin(TreeNode node)\n {\n if (node == null || node.Tag == null || !File.Exists(node.Tag.ToString()))\n {\n // Logger.Log($\"❌ Script file not found for plugin: {node?.Text}\", LogLevel.Error);\n Logger.Log(new string('-', 50), LogLevel.Info);\n }\n else\n {\n string pluginName = node.Text;\n string path = node.Tag.ToString();\n string content = File.ReadAllText(path);\n\n Dictionary commands = ParseCommands(content);\n Dictionary expected = ParseExpect(content);\n\n if (!commands.ContainsKey(\"Check\"))\n {\n Logger.Log($\"🔎 Plugin ready: [PS] {Path.GetFileName(path)}\");\n Logger.Log(new string('-', 50), LogLevel.Info);\n }\n else\n {\n string checkCmd = commands[\"Check\"];\n var result = await ExecuteCommand(checkCmd);\n string output = result.Item2;\n\n bool allMatched = true;\n StringBuilder mismatchDetails = new StringBuilder();\n\n foreach (var entry in expected)\n {\n string key = entry.Key;\n string expectedVal = entry.Value;\n\n var match = Regex.Match(output, $@\"{Regex.Escape(key)}\\s+REG_\\w+\\s+(\\S+)\", RegexOptions.IgnoreCase);\n\n if (match.Success)\n {\n string actual = match.Groups[1].Value;\n\n if (!expectedVal.Equals(actual, StringComparison.OrdinalIgnoreCase))\n {\n allMatched = false;\n mismatchDetails.AppendLine($\" ➤ {key}: expected '{expectedVal}', found '{actual}'\");\n }\n }\n else\n {\n allMatched = false;\n mismatchDetails.AppendLine(\n $\" ➤ Warning: The registry key '{key}' could not be located in the output. \" +\n \"This usually means the key is missing and the tweak will have to add it. \" +\n \"[InternalCode: Could not be parsed from output]\");\n }\n }\n\n if (allMatched)\n {\n Logger.Log($\"✅ Plugin: {pluginName} is properly configured.\", LogLevel.Info);\n node.ForeColor = Color.Gray;\n }\n else\n {\n Logger.Log($\"❌ Plugin: {pluginName} requires attention.\\n{mismatchDetails}\", LogLevel.Warning);\n node.ForeColor = Color.Red;\n }\n\n Logger.Log(new string('-', 50), LogLevel.Info);\n }\n }\n }\n\n /// \n /// 8. Applies the fix to a single plugin node.\n /// This method processes only the specified node regardless of its checked state.\n /// It attempts to run the \"Do\" command from the plugin script, or falls back to executing the entire script.\n /// \n public static async Task FixPlugin(TreeNode node)\n {\n if (node?.Tag is string path && File.Exists(path))\n {\n var content = File.ReadAllText(path);\n var commands = ParseCommands(content);\n\n if (commands.TryGetValue(\"Do\", out string doCmd))\n {\n Logger.Log($\"🔧 Running Do command for plugin: {node.Text}\");\n var (exitCode, output) = await ExecuteCommand(doCmd);\n Logger.Log($\"Do Output:\\n{output}\");\n\n Logger.Log(exitCode == 0 ? \"✅ Fix applied successfully.\" : \"❌ Fix failed.\");\n }\n else\n {\n Logger.Log($\"🔧 No Do command found, executing full script.\");\n await ExecutePlugin(path);\n }\n }\n }\n\n /// \n /// 9. Reverts changes for a single plugin node.\n /// \n public static async Task RestorePlugin(TreeNode node)\n {\n if (node?.Tag is string path && File.Exists(path))\n {\n var content = File.ReadAllText(path);\n var commands = ParseCommands(content);\n\n if (commands.TryGetValue(\"Undo\", out string undoCmd))\n {\n Logger.Log($\"♻️ Running Undo command for plugin: {node.Text}\");\n var (exitCode, output) = await ExecuteCommand(undoCmd);\n Logger.Log($\"Undo Output:\\n{output}\");\n\n Logger.Log(exitCode == 0 ? \"✅ Restore successful.\" : \"❌ Restore failed.\");\n }\n else\n {\n Logger.Log($\"⚠️ No Undo command found. Restore not possible.\");\n MessageBox.Show(\"Restore is not possible for this plugin.\", \"Information\", MessageBoxButtons.OK, MessageBoxIcon.Information);\n }\n }\n }\n\n /// 10. Recursively analyze all checked plugin nodes.\n public static async Task AnalyzeAll(TreeNode node)\n {\n if (node.Checked && node.Tag is string path && File.Exists(path))\n await AnalyzePlugin(node);\n\n foreach (TreeNode child in node.Nodes)\n await AnalyzeAll(child);\n }\n\n public static async Task AnalyzeAllPlugins(TreeNodeCollection nodes)\n {\n Logger.Log(\"\\n🔌 PLUGIN ANALYSIS\", LogLevel.Info);\n Logger.Log(new string('=', 50), LogLevel.Info);\n\n foreach (TreeNode node in nodes)\n await AnalyzeAll(node);\n }\n\n /// 11. Recursively apply fixes for all checked plugin nodes.\n public static async Task FixChecked(TreeNode node)\n {\n if (node.Checked && node.Tag is string pluginPath)\n {\n var pluginName = Path.GetFileName(pluginPath);\n var proceed = ShowPluginWarning(pluginName);\n if (!proceed) return;\n await FixPlugin(node);\n }\n\n foreach (TreeNode child in node.Nodes)\n await FixChecked(child);\n }\n\n /// 12. Return true if the node represents a PowerShell plugin file.\n public static bool IsPluginNode(TreeNode node)\n {\n return node?.Tag is string path && path.EndsWith(\".ps1\", StringComparison.OrdinalIgnoreCase);\n }\n\n /// 13. Show a warning before executing external plugin code.\n public static bool ShowPluginWarning(string pluginName)\n {\n var result = MessageBox.Show(\n $\"⚠️ WARNING: The plugin '{pluginName}' is an external script. Its execution is outside this app's responsibility and at your own risk.\\n\" +\n \"Proceed only if you trust the source of this plugin. Do you want to continue?\",\n \"Plugin Activation Warning\",\n MessageBoxButtons.YesNo,\n MessageBoxIcon.Warning\n );\n\n return result == DialogResult.Yes;\n }\n\n public static bool ShowHelp(TreeNode node)\n {\n string info = GetPluginHelpInfo(node);\n if (!string.IsNullOrEmpty(info))\n {\n MessageBox.Show(info, $\"Plugin Help: {node.Text}\", MessageBoxButtons.OK, MessageBoxIcon.Information);\n return true;\n }\n return false;\n }\n\n /// \n /// Returns the help/info string from the plugin commands section for the given node.\n /// Assumes node.Tag contains the script path as string.\n /// \n public static string GetPluginHelpInfo(TreeNode node)\n {\n if (node?.Tag is string path && File.Exists(path))\n {\n string content = File.ReadAllText(path);\n // Simple parsing to find line starting with \"Info=\" under [Commands]\n bool inCommandsSection = false;\n foreach (var line in content.Split(new[] { '\\r', '\\n' }, StringSplitOptions.RemoveEmptyEntries))\n {\n var trimmed = line.Trim();\n\n if (trimmed.StartsWith(\"[Commands]\", StringComparison.OrdinalIgnoreCase))\n {\n inCommandsSection = true;\n continue;\n }\n if (trimmed.StartsWith(\"[\") && trimmed.EndsWith(\"]\") && inCommandsSection)\n {\n // Left commands section\n break;\n }\n if (inCommandsSection && trimmed.StartsWith(\"Info=\", StringComparison.OrdinalIgnoreCase))\n {\n return trimmed.Substring(5).Trim(); // Return the text after \"Info=\"\n }\n }\n }\n\n return null; // No info found or invalid node\n }\n}"], ["/CrapFixer/CFixer/Views/PluginsView.cs", "using System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Linq;\nusing System.Net;\nusing System.Threading.Tasks;\nusing System.Windows.Forms;\n\nnamespace CFixer.Views\n{\n public partial class PluginsView : UserControl\n {\n private List plugins = new List(); // All plugins from the manifest, so full squad\n private List visiblePlugins = new List(); // Plugins currently shown in the UI (filtered or not)\n private HashSet installedPlugins = new HashSet(); // Names of plugins already installed on disk\n\n private const string manifestUrl = \"https://raw.githubusercontent.com/builtbybel/CrapFixer/main/plugins/plugins_manifest.txt\";\n\n public class PluginEntry\n {\n public string Name { get; set; }\n public string Description { get; set; }\n public string Url { get; set; }\n }\n\n public PluginsView()\n {\n InitializeComponent();\n }\n\n private async void PluginsView_Load(object sender, EventArgs e)\n {\n await LoadPlugins();\n }\n\n /// \n /// Loads the currently installed plugins from disk into memory.\n /// \n private void LoadInstalledPlugins()\n {\n var pluginPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, \"plugins\");\n if (Directory.Exists(pluginPath))\n {\n foreach (var file in Directory.GetFiles(pluginPath))\n {\n installedPlugins.Add(Path.GetFileName(file));\n }\n }\n }\n\n /// \n /// Loads plugins from the remote manifest and displays them.\n /// \n private async Task LoadPlugins()\n {\n try\n {\n LoadInstalledPlugins(); // Load the plugins already installed on disk, gotta know whats up\n\n using (var client = new WebClient())\n {\n // Download the plugin manifest\n string content = await Task.Run(() => client.DownloadString(manifestUrl));\n\n // Parse the manifest into our plugins list — all the available plugins decoded!\n plugins = ParseManifest(content);\n\n // Sync visiblePlugins with the full list to keep UI and data in perfect harmony\n visiblePlugins = plugins.ToList();\n\n // Update the ListBox so it shows all the plugins we're tracking right now\n UpdateVisiblePlugins();\n }\n }\n catch (Exception ex)\n {\n MessageBox.Show(\"Error loading plugins: \" + ex.Message);\n }\n }\n\n /// \n /// Parses the remote plugin manifest into a list of PluginEntry objects.\n /// \n private List ParseManifest(string content)\n {\n var result = new List();\n var lines = content.Split(new[] { \"\\r\\n\", \"\\n\" }, StringSplitOptions.None);\n PluginEntry current = null;\n string currentKey = null;\n\n foreach (var line in lines)\n {\n var trimmedLine = line.Trim();\n\n if (trimmedLine.StartsWith(\"[\") && trimmedLine.EndsWith(\"]\"))\n {\n if (current != null)\n result.Add(current);\n\n var name = trimmedLine.Substring(1, trimmedLine.Length - 2).Trim();\n current = new PluginEntry { Name = name };\n currentKey = null;\n }\n else if (!string.IsNullOrWhiteSpace(trimmedLine))\n {\n if (trimmedLine.Contains(\"=\") && current != null)\n {\n var parts = trimmedLine.Split(new[] { '=' }, 2);\n var key = parts[0].Trim();\n var value = parts[1].Trim();\n\n switch (key)\n {\n case \"description\":\n current.Description = value;\n currentKey = \"description\";\n break;\n\n case \"url\":\n current.Url = value;\n currentKey = \"url\";\n break;\n\n default:\n currentKey = null;\n break;\n }\n }\n else if (currentKey == \"description\" && current != null)\n {\n // This line handles multi-line description values.\n // If the previous key was \"description\" and the current line does not contain a new key=value pair,\n // it is considered a continuation of the description.\n // We append the new line to the existing description, preserving line breaks with \"\\n\".\n current.Description += \"\\n\" + trimmedLine;\n }\n }\n }\n\n if (current != null)\n result.Add(current);\n\n return result;\n }\n\n /// \n /// Downloads and installs checked plugins.\n /// If force is true, existing files will be overwritten.\n /// \n private async Task InstallPlugins(bool force = false)\n {\n var checkedItems = listPlugins.CheckedItems.Cast().ToList();\n if (checkedItems.Count == 0)\n {\n MessageBox.Show(\"Please check one or more plugins to download.\");\n return;\n }\n\n string savePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, \"plugins\");\n Directory.CreateDirectory(savePath);\n\n progressBarDownload.Visible = true;\n progressBarDownload.Value = 0;\n progressBarDownload.Maximum = checkedItems.Count;\n\n int done = 0;\n\n using (var client = new WebClient())\n {\n foreach (var item in checkedItems)\n {\n var plugin = item.Tag as PluginEntry;\n if (plugin == null)\n continue;\n\n string file = Path.Combine(savePath, Path.GetFileName(plugin.Url));\n\n // Skip download if file exists and not forcing overwrite\n if (!force && File.Exists(file))\n {\n progressBarDownload.Value = ++done;\n continue;\n }\n\n try\n {\n await client.DownloadFileTaskAsync(new Uri(plugin.Url), file);\n installedPlugins.Add(Path.GetFileName(plugin.Url));\n item.SubItems[1].Text = \"Yes\"; // Update Installed column\n //item.Checked = true; // Ensure checked\n }\n catch (Exception ex)\n {\n MessageBox.Show($\"Failed to download {plugin.Name}: {ex.Message}\");\n }\n\n progressBarDownload.Value = ++done;\n }\n }\n\n progressBarDownload.Visible = false;\n }\n\n private async void btnPluginInstall_Click(object sender, EventArgs e)\n {\n await InstallPlugins(force: false); // skip installed\n }\n\n /// \n /// Updates all plugins by selecting all and force-downloading them.\n /// \n private async void btnPluginUpdateAll_Click(object sender, EventArgs e)\n {\n // Check all items in the list\n foreach (ListViewItem item in listPlugins.Items)\n {\n item.Checked = true;\n }\n\n // Force install (overwrite even if already installed)\n await InstallPlugins(force: true);\n\n // Update the status of all plugins to \"Updated\"\n foreach (ListViewItem item in listPlugins.Items)\n {\n item.SubItems[1].Text = \"Updated\";\n }\n\n MessageBox.Show(\"All plugins updated.\");\n }\n\n private void btnPluginRemove_Click(object sender, EventArgs e)\n {\n string pluginPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, \"plugins\");\n\n var checkedItems = listPlugins.CheckedItems.Cast().ToList();\n\n if (checkedItems.Count == 0)\n {\n MessageBox.Show(\"No plugins selected.\");\n return;\n }\n\n foreach (var item in checkedItems)\n {\n var plugin = item.Tag as PluginEntry;\n if (plugin == null)\n continue;\n\n string path = Path.Combine(pluginPath, Path.GetFileName(plugin.Url));\n\n if (File.Exists(path))\n File.Delete(path);\n\n installedPlugins.Remove(Path.GetFileName(plugin.Url));\n item.SubItems[1].Text = \"No\";\n item.Checked = false;\n }\n\n MessageBox.Show(\"Selected plugins removed.\");\n }\n\n private void btnPluginEdit_Click(object sender, EventArgs e)\n {\n if (listPlugins.SelectedItems.Count == 0)\n {\n MessageBox.Show(\"Please select a plugin first.\");\n return;\n }\n\n var plugin = listPlugins.SelectedItems[0].Tag as PluginEntry;\n if (plugin == null) return;\n\n var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, \"plugins\", Path.GetFileName(plugin.Url));\n\n if (!File.Exists(path))\n {\n MessageBox.Show(\"Plugin file not found. Please install the plugin first.\");\n return;\n }\n\n try\n {\n var ext = Path.GetExtension(path).ToLower();\n var editor = ext == \".ps1\" ? \"powershell_ise.exe\" : \"notepad.exe\";\n Process.Start(editor, $\"\\\"{path}\\\"\");\n }\n catch (Exception ex)\n {\n MessageBox.Show(\"Could not open plugin: \" + ex.Message);\n }\n }\n\n /// \n /// Shows plugin information in a MessageBox.\n /// \n private void btnHelp_Click(object sender, EventArgs e)\n {\n if (listPlugins.SelectedItems.Count == 0)\n {\n MessageBox.Show(\"Please select a plugin first.\");\n return;\n }\n\n var plugin = listPlugins.SelectedItems[0].Tag as PluginEntry;\n if (plugin != null)\n {\n MessageBox.Show(plugin.Description, $\"Info: {plugin.Name}\");\n }\n }\n\n private void listPlugins_SelectedIndexChanged(object sender, EventArgs e)\n {\n if (listPlugins.SelectedItems.Count == 0)\n return;\n\n var plugin = listPlugins.SelectedItems[0].Tag as PluginEntry;\n if (plugin != null)\n {\n btnDescription.Text = plugin.Description;\n }\n }\n\n /// \n /// Updates the ListView with filtered plugin entries,\n /// including name, install status, and plugin type.\n /// Type is determined by plugin name (\"(NX)\" means native plugin),\n /// or file extension (.ps1 = Powershell; others = Other).\n /// \n private void UpdateVisiblePlugins(string query = \"\")\n {\n visiblePlugins = plugins\n .Where(p =>\n p.Name.ToLower().Contains(query) ||\n (p.Description?.ToLower() ?? \"\").Contains(query))\n .ToList();\n\n listPlugins.Items.Clear();\n\n foreach (var plugin in visiblePlugins)\n {\n var fileName = Path.GetFileName(plugin.Url);\n bool isInstalled = installedPlugins.Contains(fileName);\n\n // Determine plugin type\n string type;\n if (plugin.Name.Trim().EndsWith(\"(NX)\", StringComparison.OrdinalIgnoreCase))\n {\n type = \"NX\";\n }\n else if (Path.GetExtension(plugin.Url).Equals(\".ps1\", StringComparison.OrdinalIgnoreCase))\n {\n type = \"Powershell\";\n }\n else\n {\n type = \"Other\";\n }\n\n var item = new ListViewItem(plugin.Name);\n item.SubItems.Add(isInstalled ? \"Yes\" : \"No\");\n item.SubItems.Add(type);\n item.Tag = plugin;\n item.Checked = isInstalled;\n\n listPlugins.Items.Add(item);\n }\n\n // Auto-resize columns to fit header and content\n foreach (ColumnHeader column in listPlugins.Columns)\n {\n column.Width = -2;\n }\n }\n\n\n private void textSearch_TextChanged(object sender, EventArgs e)\n {\n string query = textSearch.Text.Trim().ToLower();\n UpdateVisiblePlugins(query);\n }\n\n private void textSearch_Click(object sender, EventArgs e)\n {\n textSearch.Text = string.Empty;\n }\n\n private void btnPluginSubmit_Click(object sender, EventArgs e)\n {\n System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo\n {\n FileName = \"https://github.com/builtbybel/CrapFixer/blob/main/plugins/plugins_manifest.txt\",\n UseShellExecute = true\n });\n }\n\n private void linkPluginUsage_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)\n {\n Process.Start(\"https://github.com/builtbybel/CrapFixer/blob/main/plugins/DemoPluginPack.ps1\");\n }\n }\n}"], ["/CrapFixer/CFixer/Views/ViveView.cs", "using System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Diagnostics;\nusing System.Drawing;\nusing System.IO;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing System.Windows.Forms;\n\nnamespace CFixer.Views\n{\n public partial class ViveView : UserControl\n {\n private List featureList;\n private string viveToolPath;\n\n public ViveView()\n {\n InitializeComponent();\n IsViveToolAvailable();\n InitFeatureList();\n LoadFeaturesToGrid();\n\n // Fire and forget async call\n _ = UpdateFeatureStatusFromSystem();\n }\n\n private void IsViveToolAvailable()\n {\n string pluginsDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, \"plugins\");\n\n var viveFolder = Directory.GetDirectories(pluginsDir)\n .FirstOrDefault(dir => Path.GetFileName(dir).ToLower().StartsWith(\"vive\"));\n\n if (viveFolder == null)\n {\n viveToolPath = null;\n btnDescription.Text = \"Enable experimental and hidden features (Disabled)\";\n return;\n }\n\n string exePath = Path.Combine(viveFolder, \"ViVeTool.exe\");\n if (File.Exists(exePath))\n {\n viveToolPath = exePath;\n btnDescription.Text = \"Enable experimental and hidden features (Enabled)\";\n }\n }\n\n /// \n /// Initializes hardcoded feature list with names, IDs and default states.\n /// \n private void InitFeatureList()\n {\n featureList = new List\n {\n new ViveFeature\n {\n Ids = new List {47205210, 49221331, 49381526, 49402389, 49820095, 55495322, 48433719},\n Name = \"Enable the redesigned Windows 11 Start menu\",\n InfoUrl = \"https://www.neowin.net/guides/how-to-enable-the-redesigned-windows-11-start-menu/\",\n Enabled = false\n },\n new ViveFeature\n {\n Ids = new List {52467192,53079680},\n Name = \"Enable Text extractor in Snipping Tool\",\n InfoUrl = \"https://blogs.windows.com/windows-insider/2025/04/15/text-extractor-in-snipping-tool-begins-rolling-out-to-windows-insiders/\",\n Enabled = false\n }\n ,new ViveFeature\n {\n Ids = new List {45624564},\n Name = \"Enable Drag Tray Share UI\",\n InfoUrl = \"https://www.neowin.net/news/windows-11-is-getting-a-quirky-new-way-to-share-files/\",\n Enabled = false\n }\n };\n }\n\n /// \n /// Loads the feature list into the DataGridView UI.\n /// \n private void LoadFeaturesToGrid()\n {\n dataGridView.Rows.Clear();\n\n foreach (var feature in featureList)\n {\n int rowIndex = dataGridView.Rows.Add();\n var row = dataGridView.Rows[rowIndex];\n\n row.Cells[\"EnabledColumn\"].Value = feature.Enabled;\n row.Cells[\"NameColumn\"].Value = feature.Name;\n row.Cells[\"IdColumn\"].Value = feature.IdsAsString;\n row.Cells[\"InfoColumn\"].Value = feature.InfoUrl;\n row.Cells[\"StatusColumn\"].Value = \"Unknown\";\n }\n }\n\n /// \n /// Executes ViVeTool with given feature IDs and state.\n /// \n private void ApplyFeature(List ids, bool enable)\n {\n if (string.IsNullOrEmpty(viveToolPath))\n {\n MessageBox.Show(\"ViVeTool not found. Please ensure it is installed in the plugins folder.\", \"Error\", MessageBoxButtons.OK, MessageBoxIcon.Error);\n return;\n }\n\n string action = enable ? \"/enable\" : \"/disable\";\n string idArg = string.Join(\",\", ids);\n string args = $\"{action} /id:{idArg}\";\n\n Process.Start(new ProcessStartInfo\n {\n FileName = viveToolPath,\n Arguments = args,\n UseShellExecute = true,\n CreateNoWindow = true,\n Verb = \"runas\" // Run as administrator\n });\n }\n\n /// \n /// Applies the currently selected states from the DataGridView to the system using ViVeTool.\n /// \n private async void btnViveApply_Click(object sender, EventArgs e)\n {\n for (int i = 0; i < dataGridView.Rows.Count; i++)\n {\n var row = dataGridView.Rows[i];\n if (row.IsNewRow) continue;\n\n bool isEnabled = Convert.ToBoolean(row.Cells[\"EnabledColumn\"].Value);\n string idText = row.Cells[\"IdColumn\"].Value.ToString();\n List ids = idText.Split(',').Select(s => int.Parse(s.Trim())).ToList();\n\n ApplyFeature(ids, isEnabled);\n }\n\n Task.Delay(1000).Wait();\n await UpdateFeatureStatusFromSystem(); // Refresh the status after applying changes\n\n MessageBox.Show(\"Features have been applied.\", \"Done\", MessageBoxButtons.OK, MessageBoxIcon.Information);\n }\n\n /// \n /// Queries the current system state using ViVeTool and returns a map of ID => isEnabled.\n /// \n // Pro ID ein Query machen, um den Status exakt zu ermitteln\n private Dictionary QueryCurrentFeatureStates()\n {\n var statusMap = new Dictionary();\n\n if (string.IsNullOrEmpty(viveToolPath))\n {\n MessageBox.Show(\"ViVeTool not found. Please ensure it is installed in the plugins folder.\", \"Error\", MessageBoxButtons.OK, MessageBoxIcon.Error);\n return statusMap;\n }\n\n var allIds = featureList.SelectMany(f => f.Ids).Distinct();\n\n foreach (int id in allIds)\n {\n ProcessStartInfo psi = new ProcessStartInfo\n {\n FileName = viveToolPath,\n Arguments = $\"/query /id:{id}\",\n UseShellExecute = false,\n RedirectStandardOutput = true,\n CreateNoWindow = true\n };\n\n using (Process proc = Process.Start(psi))\n {\n string output = proc.StandardOutput.ReadToEnd();\n proc.WaitForExit();\n\n bool enabled = output.Contains(\"Enabled\");\n statusMap[id] = enabled;\n }\n }\n\n return statusMap;\n }\n\n /// \n /// Asynchronously updates the grid checkboxes and status labels to reflect actual feature states on the system.\n /// \n private async Task UpdateFeatureStatusFromSystem()\n {\n // Run QueryCurrentFeatureStates on a background thread\n var systemStatus = await Task.Run(() => QueryCurrentFeatureStates());\n\n // Update UI on the UI thread\n if (dataGridView.InvokeRequired)\n {\n dataGridView.Invoke(new Action(() =>\n {\n UpdateGridWithStatus(systemStatus);\n }));\n }\n else\n {\n UpdateGridWithStatus(systemStatus);\n }\n }\n\n /// \n /// Updates the grid rows with the given status dictionary.\n /// \n private void UpdateGridWithStatus(Dictionary systemStatus)\n {\n foreach (DataGridViewRow row in dataGridView.Rows)\n {\n if (row.IsNewRow) continue;\n\n string idText = row.Cells[\"IdColumn\"].Value.ToString();\n var ids = idText.Split(',').Select(s => int.Parse(s.Trim())).ToList();\n\n int enabledCount = ids.Count(id => systemStatus.ContainsKey(id) && systemStatus[id]);\n\n string status = \"Disabled\";\n if (enabledCount == ids.Count)\n status = \"All Enabled\";\n else if (enabledCount > 0)\n status = \"Partially Enabled\";\n\n row.Cells[\"StatusColumn\"].Value = status;\n }\n }\n\n private void dataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)\n {\n if (e.ColumnIndex == dataGridView.Columns[\"InfoColumn\"].Index && e.RowIndex >= 0)\n {\n var url = dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value?.ToString();\n if (!string.IsNullOrEmpty(url))\n {\n try\n {\n Process.Start(new ProcessStartInfo\n {\n FileName = url,\n UseShellExecute = true\n });\n }\n catch (Exception ex)\n {\n MessageBox.Show($\"Failed to open link:\\n{ex.Message}\", \"Error\", MessageBoxButtons.OK, MessageBoxIcon.Error);\n }\n }\n }\n }\n\n /// \n /// Represents a single ViVe feature group.\n /// \n public class ViveFeature\n {\n public List Ids { get; set; }\n public string Name { get; set; }\n public bool Enabled { get; set; }\n public string InfoUrl { get; set; }\n\n public string IdsAsString => string.Join(\",\", Ids);\n }\n\n private void linkPluginUsage_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)\n {\n MessageBox.Show(\"This plugin uses ViVeTool to enable hidden Windows features.\\n\" +\n \"Please download ViVeTool (e.g. 'ViVeTool-v0.3.x-IntelAmd') from:\\n\" +\n \"https://github.com/thebookisclosed/ViVe/releases\\n\" +\n \"Extract it and place the contents into a subfolder inside the 'plugins' directory.\\n\\n\");\n }\n\n private void btnApplyCustom_Click(object sender, EventArgs e)\n {\n string input = txtCustomIds.Text;\n\n if (string.IsNullOrWhiteSpace(input))\n {\n MessageBox.Show(\"Please enter one or more feature IDs.\", \"Invalid Input\", MessageBoxButtons.OK, MessageBoxIcon.Warning);\n return;\n }\n\n // Parse input (e.g., \"123,456,789\")\n var idList = new List();\n var parts = input.Split(',');\n\n foreach (var part in parts)\n {\n if (int.TryParse(part.Trim(), out int id))\n {\n idList.Add(id);\n }\n else\n {\n MessageBox.Show($\"Invalid ID: '{part}'\", \"Error\", MessageBoxButtons.OK, MessageBoxIcon.Error);\n return;\n }\n }\n\n if (idList.Count == 0)\n {\n MessageBox.Show(\"No valid IDs found.\", \"Error\", MessageBoxButtons.OK, MessageBoxIcon.Error);\n return;\n }\n\n // Ask whether to enable or disable\n var result = MessageBox.Show(\n $\"Do you want to ENABLE these features?\\n\\n{string.Join(\", \", idList)}\\n\\n\" +\n \"Yes = Enable\\nNo = Disable\\nCancel = Abort\",\n \"Confirm Action\",\n MessageBoxButtons.YesNoCancel,\n MessageBoxIcon.Question);\n\n if (result == DialogResult.Cancel) return;\n\n bool enable = (result == DialogResult.Yes);\n\n ApplyFeature(idList, enable);\n\n MessageBox.Show(\"Custom feature action sent to ViVeTool.\", \"Done\", MessageBoxButtons.OK, MessageBoxIcon.Information);\n }\n }\n}"], ["/CrapFixer/CFixer/NavigationHandler.cs", "using System;\nusing System.Collections.Generic;\nusing System.Drawing;\nusing System.IO;\nusing System.Threading.Tasks;\nusing System.Windows.Forms;\n\nnamespace CFixer\n{\n /// \n /// Handles navigation button highlighting for a set of UI buttons.\n /// \n public class NavigationHandler\n {\n // List of all buttons managed by the navigation handler\n private readonly List