diff --git a/MacUtilGUI.Tests/InstallTabTests.fs b/MacUtilGUI.Tests/InstallTabTests.fs new file mode 100644 index 0000000..023e786 --- /dev/null +++ b/MacUtilGUI.Tests/InstallTabTests.fs @@ -0,0 +1,66 @@ +namespace MacUtilGUI.Tests + +open Xunit +open MacUtilGUI.Services +open MacUtilGUI.ViewModels + +module InstallTabTests = + + let private catalog () = + ConfigLoader.load (ConfigSchemaTests.findConfigDir ()) + + let private makeVm (brew: BrewClientTests.FakeBrew) = + let client = FakeDefaultsClient() + let killer = FakeProcessKiller() + MainWindowViewModel(catalog (), client :> IDefaultsClient, killer :> IProcessKiller, brew.Exec) + + let private findApp (rows: AppRowViewModel seq) id = + rows |> Seq.find (fun row -> row.Id = id) + + let private uncheckAll (vm: MainWindowViewModel) = + for row in vm.AllApps do + row.IsChecked <- false + + [] + let InstallDetectChecksBox () = + let brew = BrewClientTests.FakeBrew([ "visual-studio-code" ], [ "neovim" ]) + let vm = makeVm brew + let vscode = findApp vm.AllApps "visual-studio-code" + let neovim = findApp vm.AllApps "neovim" + let discord = findApp vm.AllApps "discord" + + Assert.Equal("Visual Studio Code", vscode.Content) + Assert.True(BrewClient.installed brew.Exec vscode.App) + Assert.True(vscode.IsChecked) + Assert.True(neovim.IsChecked) + Assert.False(discord.IsChecked) + Assert.Equal(26, Seq.length vm.AllApps) + Assert.Equal(26, vm.Apps.Count) + Assert.NotEmpty(vm.SafeTweaks) + + let pathBar = vm.SafeTweaks |> Seq.find (fun row -> row.Id = "finder-path-bar") + Assert.False(pathBar.IsChecked) + + [] + let EmptyInstallWritesNothing () = + let brew = BrewClientTests.FakeBrew([ "visual-studio-code" ], []) + let vm = makeVm brew + uncheckAll vm + + vm.InstallSelected() + Assert.Empty(brew.InstallCalls) + Assert.Equal("Nothing is selected.", vm.StatusText) + Assert.Empty(vm.SelectedAppIds) + + [] + let SearchFiltersList () = + let brew = BrewClientTests.FakeBrew([], []) + let vm = makeVm brew + + vm.SearchText <- "brave" + Assert.Equal(1, vm.Apps.Count) + Assert.Equal("brave-browser", Seq.exactlyOne vm.Apps |> fun row -> row.Id) + Assert.Equal(26, Seq.length vm.AllApps) + + vm.SearchText <- "" + Assert.Equal(26, vm.Apps.Count) diff --git a/MacUtilGUI.Tests/MacUtilGUI.Tests.fsproj b/MacUtilGUI.Tests/MacUtilGUI.Tests.fsproj index 936d789..776d104 100644 --- a/MacUtilGUI.Tests/MacUtilGUI.Tests.fsproj +++ b/MacUtilGUI.Tests/MacUtilGUI.Tests.fsproj @@ -14,6 +14,7 @@ + diff --git a/MacUtilGUI/App.axaml b/MacUtilGUI/App.axaml index 8beffd1..94ce1c1 100644 --- a/MacUtilGUI/App.axaml +++ b/MacUtilGUI/App.axaml @@ -168,5 +168,13 @@ + + diff --git a/MacUtilGUI/MacUtilGUI.fsproj b/MacUtilGUI/MacUtilGUI.fsproj index d9e1d2f..8789711 100644 --- a/MacUtilGUI/MacUtilGUI.fsproj +++ b/MacUtilGUI/MacUtilGUI.fsproj @@ -39,17 +39,15 @@ - - - + @@ -61,7 +59,6 @@ - @@ -75,11 +72,6 @@ - - - - - diff --git a/MacUtilGUI/Models/ScriptCategory.fs b/MacUtilGUI/Models/ScriptCategory.fs deleted file mode 100644 index 5b4a76d..0000000 --- a/MacUtilGUI/Models/ScriptCategory.fs +++ /dev/null @@ -1,5 +0,0 @@ -namespace MacUtilGUI.Models - -type ScriptCategory = - { Name: string - Scripts: ScriptInfo list } diff --git a/MacUtilGUI/Models/ScriptInfo.fs b/MacUtilGUI/Models/ScriptInfo.fs deleted file mode 100644 index 7555029..0000000 --- a/MacUtilGUI/Models/ScriptInfo.fs +++ /dev/null @@ -1,9 +0,0 @@ -namespace MacUtilGUI.Models - -type ScriptInfo = - { Name: string - Description: string - Script: string - TaskList: string - Category: string - FullPath: string } diff --git a/MacUtilGUI/README.md b/MacUtilGUI/README.md index c16d115..324cfc0 100644 --- a/MacUtilGUI/README.md +++ b/MacUtilGUI/README.md @@ -1,90 +1,11 @@ # MacUtil GUI -A cross-platform GUI application built with F# and Avalonia UI to run the shell scripts from the MacUtil project. +Avalonia UI for MacUtil. The window is opaque `#1C1C1E`. The menu bar name is MacUtil. -## Features +Tweaks binds `config/tweaks.json` checkboxes to `ActionEngine`. Install binds `config/applications.json` checkboxes to `BrewClient`. Search filters the Install list. -- **Script Browser**: Browse and categorize scripts from the `scripts/` directory -- **Script Details**: View detailed information about each script including description, category, and file path -- **One-Click Execution**: Run scripts with a single button click -- **Cross-Platform**: Works on macOS, Windows, and Linux -- **Modern UI**: Built with Avalonia UI using the Fluent theme +Run from the repo root: -## Project Structure - -``` -MacUtilGUI/ -├── MacUtilGUI.fsproj # Project file -├── App.axaml # Application XAML -├── Program.fs # Application entry point -├── Models/ -│ ├── ScriptInfo.fs # Script information model -│ └── ScriptCategory.fs # Script category model -├── Services/ -│ └── ScriptService.fs # Script loading and execution service -├── ViewModels/ -│ ├── ViewModelBase.fs # Base view model class -│ └── MainWindowViewModel.fs # Main window view model -└── Views/ - ├── MainWindow.axaml # Main window XAML - └── MainWindow.axaml.fs # Main window code-behind +```bash +dotnet run --project MacUtilGUI/MacUtilGUI.fsproj ``` - -## Prerequisites - -- .NET 9.0 SDK or later -- F# support - -## Building and Running - -1. Navigate to the MacUtilGUI directory: - ```bash - cd MacUtilGUI - ``` - -2. Restore dependencies: - ```bash - dotnet restore - ``` - -3. Build the project: - ```bash - dotnet build - ``` - -4. Run the application: - ```bash - dotnet run - ``` - -## How It Works - -1. **Script Discovery**: The application scans the `../scripts/` directory for TOML configuration files and shell scripts -2. **TOML Parsing**: Uses the `tab_data.toml` files to organize scripts into categories with descriptions -3. **Dynamic Loading**: Scripts are organized by category and loaded dynamically from the file system -4. **Execution**: When a script is selected and "Run Script" is clicked, it executes the shell script in a new terminal process - -## Configuration - -The application reads configuration from: -- `scripts/tabs.toml` - Main configuration listing script directories -- `scripts/*/tab_data.toml` - Category-specific script configurations - -## Dependencies - -- **Avalonia**: Cross-platform .NET UI framework -- **Tomlyn**: TOML parsing library for .NET - -## Extending - -To add new script categories: -1. Create a new directory under `scripts/` -2. Add the directory name to `scripts/tabs.toml` -3. Create a `tab_data.toml` file in the new directory with script definitions -4. The GUI will automatically discover and display the new scripts - -## Troubleshooting - -- Ensure the `scripts/` directory is one level up from the executable location -- Check that shell scripts have execute permissions (`chmod +x script.sh`) -- Verify TOML files are properly formatted diff --git a/MacUtilGUI/Services/ScriptService.fs b/MacUtilGUI/Services/ScriptService.fs deleted file mode 100644 index 11db559..0000000 --- a/MacUtilGUI/Services/ScriptService.fs +++ /dev/null @@ -1,910 +0,0 @@ -namespace MacUtilGUI.Services - -open System -open System.IO -open System.Diagnostics -open System.Reflection -open System.Threading.Tasks -open System.Text -open Tomlyn -open MacUtilGUI.Models - -module ScriptService = - - let assembly = Assembly.GetExecutingAssembly() - - // Function to check if Terminal has Full Disk Access permission - let checkFullDiskAccess () : bool * string = - try - // Test multiple protected directories that require Full Disk Access - let testPaths = [ - // System directories that require FDA - "/Library/Application Support" - "/Users/Shared/.com.apple.timemachine.supported" - "/System/Library/CoreServices/SystemUIServer.app/Contents" - // User's own protected directories - Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Library", "Mail") - Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Library", "Safari") - ] - - let mutable hasAccess = false - let mutable lastError = "" - - // Try each test path until we find one that works or all fail - for testPath in testPaths do - if not hasAccess && Directory.Exists(testPath) then - try - // Attempt to list contents - this will fail without Full Disk Access - let startInfo = ProcessStartInfo() - startInfo.FileName <- "/bin/ls" - startInfo.Arguments <- sprintf "-la \"%s\"" testPath - startInfo.UseShellExecute <- false - startInfo.RedirectStandardOutput <- true - startInfo.RedirectStandardError <- true - startInfo.CreateNoWindow <- true - - let proc = Process.Start(startInfo) - if proc <> null then - proc.WaitForExit() - let error = proc.StandardError.ReadToEnd() - let output = proc.StandardOutput.ReadToEnd() - - // If we get permission denied, Full Disk Access is not granted - if error.Contains("Operation not permitted") || error.Contains("Permission denied") then - lastError <- sprintf "Access denied to %s" testPath - elif not (String.IsNullOrEmpty(output)) then - // Successfully read directory contents - hasAccess <- true - else - lastError <- sprintf "No output from listing %s" testPath - with ex -> - lastError <- sprintf "Error testing %s: %s" testPath ex.Message - - if hasAccess then - true, "Terminal has Full Disk Access permission" - else - false, sprintf "Terminal does not have Full Disk Access permission. Last error: %s" lastError - - with ex -> - false, sprintf "Error checking Full Disk Access: %s" ex.Message - - // Function to guide user through granting Full Disk Access - let promptForFullDiskAccess (onOutput: string -> unit) : unit = - onOutput "⚠️ IMPORTANT: Terminal needs Full Disk Access permission" - onOutput "" - onOutput "To grant Full Disk Access to Terminal:" - onOutput "1. Open System Preferences/Settings" - onOutput "2. Go to Security & Privacy (or Privacy & Security)" - onOutput "3. Click on 'Full Disk Access' in the sidebar" - onOutput "4. Click the lock icon and enter your password" - onOutput "5. Click the '+' button to add an application" - onOutput "6. Navigate to /Applications/Utilities/Terminal.app" - onOutput "7. Select Terminal and click 'Open'" - onOutput "8. Make sure the checkbox next to Terminal is checked" - onOutput "" - onOutput "📱 Alternative: You can also:" - onOutput " • Open Spotlight (Cmd+Space)" - onOutput " • Type 'Privacy & Security' and press Enter" - onOutput " • Look for 'Full Disk Access' on the left" - onOutput "" - onOutput "After granting permission, restart MacUtil and try again." - onOutput "" - onOutput "🔍 Why is this needed?" - onOutput "Many system configuration scripts need to access protected" - onOutput "system files and directories that require Full Disk Access." - - // Function to open System Preferences to the correct pane - let openPrivacySettings () : unit = - let rec tryOpenSettings attempts = - match attempts with - | 1 -> - // Try to open directly to Privacy & Security Full Disk Access (macOS 13+) - try - let startInfo = ProcessStartInfo() - startInfo.FileName <- "/usr/bin/open" - startInfo.Arguments <- "x-apple.systempreferences:com.apple.preference.security?Privacy_AllFiles" - startInfo.UseShellExecute <- false - startInfo.CreateNoWindow <- true - - let proc = Process.Start(startInfo) - if proc <> null then - proc.WaitForExit() - // If exit code is 0, the URL scheme worked - proc.ExitCode = 0 - else - false - with _ -> - false - | 2 -> - // Fallback 1: Try macOS 12 and earlier URL scheme - try - let startInfo = ProcessStartInfo() - startInfo.FileName <- "/usr/bin/open" - startInfo.Arguments <- "x-apple.systempreferences:com.apple.preference.security?Privacy" - startInfo.UseShellExecute <- false - startInfo.CreateNoWindow <- true - - let proc = Process.Start(startInfo) - if proc <> null then - proc.WaitForExit() - proc.ExitCode = 0 - else - false - with _ -> - false - | 3 -> - // Fallback 2: Open System Preferences/Settings app directly - try - let startInfo = ProcessStartInfo() - startInfo.FileName <- "/usr/bin/open" - // Try System Settings first (macOS 13+), then System Preferences - startInfo.Arguments <- "/System/Applications/System Settings.app" - startInfo.UseShellExecute <- false - startInfo.CreateNoWindow <- true - - let proc = Process.Start(startInfo) - if proc <> null then - proc.WaitForExit() - proc.ExitCode = 0 - else - false - with _ -> - false - | 4 -> - // Final fallback: Open legacy System Preferences (macOS 12 and earlier) - try - let startInfo = ProcessStartInfo() - startInfo.FileName <- "/usr/bin/open" - startInfo.Arguments <- "/System/Applications/System Preferences.app" - startInfo.UseShellExecute <- false - startInfo.CreateNoWindow <- true - - let proc = Process.Start(startInfo) - if proc <> null then - proc.WaitForExit() - true // Last attempt, consider it successful regardless - else - false - with _ -> - false - | _ -> - false - - // Try each method until one succeeds - let mutable currentAttempt = 1 - let mutable success = false - while currentAttempt <= 4 && not success do - success <- tryOpenSettings currentAttempt - if not success then - currentAttempt <- currentAttempt + 1 - - // Modified function to preprocess scripts for non-TTY environments - let preprocessScriptForNonTTY (scriptContent: string) : string = - let lines = scriptContent.Split([| '\n'; '\r' |], StringSplitOptions.None) - let processedLines = - lines - |> Array.map (fun line -> - let trimmed = line.Trim() - - // Skip TTY checks that cause issues in .app bundles - if trimmed.Contains("tty -s") || - trimmed.Contains("[ -t 0 ]") || - trimmed.Contains("[[ -t 0 ]]") || - trimmed.Contains("if tty") || - trimmed.Contains("test -t 0") || - trimmed.Contains("[ -t 1 ]") || - trimmed.Contains("[[ -t 1 ]]") || - trimmed.Contains("test -t 1") || - trimmed.Contains("isatty") || - trimmed.Contains("stdin is not a TTY") then - "# TTY check disabled for .app bundle execution: " + line - - // Force non-interactive mode for package managers - elif trimmed.StartsWith("brew install") && not (trimmed.Contains("--help")) then - // Add --quiet flag to reduce output and avoid prompts - if not (trimmed.Contains("--quiet")) then - line.Replace("brew install", "brew install --quiet") - else - line - elif trimmed.StartsWith("brew ") && not (trimmed.Contains("--help")) && not (trimmed.Contains("install")) then - // For other brew commands, just ensure they run quietly - if not (trimmed.Contains("--quiet")) && (trimmed.Contains("update") || trimmed.Contains("upgrade")) then - line + " --quiet" - else - line - - // Add --yes flag to apt commands (if any) - elif trimmed.Contains("apt-get ") && not (trimmed.Contains("-y")) && not (trimmed.Contains("--yes")) then - line.Replace("apt-get ", "apt-get -y ") - - // Disable Homebrew's automatic checking - elif trimmed.Contains("command -v brew") then - line + " 2>/dev/null" - - // Handle common non-interactive mode messages - elif trimmed.Contains("Running in non-interactive mode") then - "# " + line + " # Suppressed for GUI execution" - - else - line) - - // Add comprehensive non-interactive environment setup at the beginning - let header = """#!/bin/bash -# Force non-interactive mode for GUI execution -export TERM=${TERM:-xterm-256color} -export DEBIAN_FRONTEND=noninteractive -export CI=true -export NONINTERACTIVE=0 -export FORCE_NONINTERACTIVE=0 -export HOMEBREW_NO_ENV_HINTS=1 -export HOMEBREW_NO_INSTALL_CLEANUP=1 -export HOMEBREW_NO_AUTO_UPDATE=1 -export HOMEBREW_NO_ANALYTICS=1 -export HOMEBREW_NO_INSECURE_REDIRECT=1 - -# Override TTY-related functions and commands that cause issues -function tty() { - return 1 # Always return "not a TTY" -} - -function isatty() { - return 1 # Always return "not a TTY" -} - -# Redirect stdin from /dev/null to ensure non-interactive behavior -exec < /dev/null - -# Set bash options for non-interactive execution -set +o posix # Disable POSIX mode which can cause TTY issues -set +m # Disable job control - -""" - - // Combine header with processed script content - let processedScript = String.Join("\n", processedLines) - - // If script already has a shebang, replace it; otherwise add header - if processedScript.StartsWith("#!") then - let firstNewLine = processedScript.IndexOf('\n') - if firstNewLine > 0 then - header + processedScript.Substring(firstNewLine + 1) - else - header + processedScript - else - header + processedScript - - // Function to check if a script needs elevation (contains sudo, $ESCALATION_TOOL, etc.) - let needsElevation (scriptContent: string) : bool = - scriptContent.Contains("$ESCALATION_TOOL") - || scriptContent.Contains("${ESCALATION_TOOL}") - - let getEmbeddedResource (resourcePath: string) : string option = - try - // How F# handles embedded resources: - // 1. Resource names are case-sensitive. - // 2. They use the format "Namespace.Folder.FileName" with folders separated by dots. - // 3. Hyphens in the directories are converted to underscores in the resource name. - // 4. Hyphens in the filename are kept as-is. - // For example, "script-common/common-script.sh" becomes "MacUtilGUI.scripts_common.common-script.sh". - // 5. The namespace is typically the assembly name, so we prefix it with "MacUtilGUI.". - - let pathParts = resourcePath.Replace("\\", "/").Split('/') - - let convertedParts = - pathParts - |> Array.mapi (fun i part -> - if i = pathParts.Length - 1 then - // Last part is filename - keep hyphens - part - else - // Directory parts - convert hyphens to underscores - part.Replace("-", "_")) - - let convertedPath = String.Join(".", convertedParts) - let resourceName = sprintf "MacUtilGUI.%s" convertedPath - - printfn "DEBUG: Resource path '%s' -> '%s'" resourcePath resourceName - - use stream = assembly.GetManifestResourceStream(resourceName) - - if stream <> null then - use reader = new StreamReader(stream) - Some(reader.ReadToEnd()) - else - printfn "Resource not found: %s" resourceName - None - with ex -> - printfn "Error reading embedded resource %s: %s" resourcePath ex.Message - None - - let listEmbeddedResources () = - let resourceNames = assembly.GetManifestResourceNames() - printfn "Available embedded resources:" - - for name in resourceNames do - printfn " %s" name - - let scriptsBasePath = "" - - let loadScriptsFromDirectory (directoryPath: string) : ScriptCategory list = - let mutable categories = [] - - try - let tabDataPath = sprintf "%s/tab_data.toml" directoryPath - - match getEmbeddedResource tabDataPath with - | Some content -> - try - let tomlDoc = Toml.Parse(content) - - // Parse the TOML as a dynamic table - if tomlDoc.Diagnostics.Count > 0 then - printfn "TOML parsing warnings/errors for %s:" tabDataPath - - for diag in tomlDoc.Diagnostics do - printfn " %s" (diag.ToString()) - - let table = tomlDoc.ToModel() - - // Look for 'data' array in the table - if table.ContainsKey("data") then - match table.["data"] with - | :? Tomlyn.Model.TomlTableArray as dataArray -> - for dataGroup in dataArray do - if dataGroup.ContainsKey("name") && dataGroup.ContainsKey("entries") then - let groupName = dataGroup.["name"].ToString() - - match dataGroup.["entries"] with - | :? Tomlyn.Model.TomlTableArray as entriesArray -> - let scripts = - [ for entry in entriesArray do - if - entry.ContainsKey("name") - && entry.ContainsKey("description") - && entry.ContainsKey("script") - then - let name = entry.["name"].ToString() - let description = entry.["description"].ToString() - let script = entry.["script"].ToString() - let fullPath = sprintf "%s/%s" directoryPath script - - yield - { Name = name - Description = description - Script = script - TaskList = "I" - Category = groupName - FullPath = fullPath } ] - - if not scripts.IsEmpty then - let category = { Name = groupName; Scripts = scripts } - categories <- category :: categories - | _ -> () - | _ -> () - with ex -> - printfn "Error parsing TOML file %s: %s" tabDataPath ex.Message - | None -> - printfn "ERROR: Embedded resource not found: %s" tabDataPath - printfn "This should not happen if resources are properly embedded!" - with ex -> - printfn "Error loading scripts from %s: %s" directoryPath ex.Message - - categories |> List.rev - - let loadAllScripts () : ScriptCategory list = - let mutable allCategories = [] - - try - // Quick check of embedded resources - let resourceNames = assembly.GetManifestResourceNames() - - printfn - "INFO: Found %d embedded resources including common-script.sh: %b" - resourceNames.Length - (resourceNames |> Array.exists (fun name -> name.EndsWith("common-script.sh"))) - - let mainTabsPath = "tabs.toml" - - match getEmbeddedResource mainTabsPath with - | Some content -> - let tomlDoc = Toml.Parse(content) - let table = tomlDoc.ToModel() - - if table.ContainsKey("directories") then - match table.["directories"] with - | :? Tomlyn.Model.TomlArray as dirArray -> - for dir in dirArray do - let directory = dir.ToString() - let categories = loadScriptsFromDirectory directory - allCategories <- allCategories @ categories - | _ -> () - | None -> - printfn "ERROR: Main tabs.toml not found in embedded resources!" - printfn "This should not happen if resources are properly embedded!" - with ex -> - printfn "Error loading scripts: %s" ex.Message - - allCategories - - // Main script execution function with Full Disk Access check - let runScript (scriptInfo: ScriptInfo) (onOutput: string -> unit) (onError: string -> unit) : Task = - Task.Run(fun () -> - try - // First, check if Terminal has Full Disk Access - let hasAccess, accessMessage = checkFullDiskAccess() - - if not hasAccess then - onError "❌ Full Disk Access Required" - onError "" - promptForFullDiskAccess onOutput - onError "" - onError "Click the button below to open Privacy Settings:" - - // Open Privacy Settings automatically - openPrivacySettings() - - -2 // Special exit code for permission issue - else - onOutput "" - - // Get the script content from embedded resources - match getEmbeddedResource scriptInfo.FullPath with - | Some scriptContent -> - // Check if script sources common-script.sh - let needsCommonScript = - scriptContent.Contains(". ../common-script.sh") - || scriptContent.Contains(". ../../common-script.sh") - - let finalScriptContent = - if needsCommonScript then - onOutput "DEBUG: Script needs common-script.sh, checking embedded resources..." - - // Get common script content - match getEmbeddedResource "common-script.sh" with - | Some commonContent -> - onOutput "DEBUG: Successfully found common-script.sh in embedded resources" - // Remove sourcing line and combine scripts - let cleanedScript = - scriptContent - .Replace(". ../common-script.sh", "") - .Replace(". ../../common-script.sh", "") - .Trim() - - // Combine: shebang + common functions + original script (without sourcing) - let shebang = "#!/bin/sh -e\n\n" - - let commonFunctions = - commonContent - .Replace("#!/bin/sh -e", "") - .Replace("# shellcheck disable=SC2034", "") - .Trim() - - sprintf - "%s# Embedded common script functions\n%s\n\n# Original script content\n%s" - shebang - commonFunctions - cleanedScript - | None -> - onError - "Warning: common-script.sh not found in embedded resources, using original script" - - scriptContent - else - scriptContent - - // Preprocess the script for non-TTY execution - let preprocessedScript = preprocessScriptForNonTTY finalScriptContent - - // Check if script needs elevation - if needsElevation finalScriptContent then - onOutput "Script requires administrator privileges..." - - // Replace $ESCALATION_TOOL with empty string since we'll handle elevation via osascript - let cleanedScript = - preprocessedScript - .Replace("$ESCALATION_TOOL ", "") - .Replace("${ESCALATION_TOOL} ", "") - .Replace("sudo ", "") - - // Create a temporary script file for elevation - let tempDir = Path.GetTempPath() - let scriptFileName = Path.GetFileName(scriptInfo.Script) - - let tempFileName = - sprintf "%s_%s" (Guid.NewGuid().ToString("N").Substring(0, 8)) scriptFileName - - let tempFilePath = Path.Combine(tempDir, tempFileName) - - try - // Write script content to temporary file - File.WriteAllText(tempFilePath, cleanedScript) - - // Make the temporary file executable - let chmodStartInfo = ProcessStartInfo() - chmodStartInfo.FileName <- "/bin/chmod" - chmodStartInfo.Arguments <- sprintf "+x \"%s\"" tempFilePath - chmodStartInfo.UseShellExecute <- false - chmodStartInfo.CreateNoWindow <- true - let chmodProc = Process.Start(chmodStartInfo) - - if chmodProc <> null then - chmodProc.WaitForExit() - - onOutput "Prompting for administrator password..." - - // Use osascript to run the script with elevated privileges - // Note: osascript doesn't provide real-time output, so we'll get all output at the end - - // Create a wrapper script that sets comprehensive environment and runs the main script - let wrapperScript = - "#!/bin/bash\n" + - "export TERM=xterm-256color\n" + - "export DEBIAN_FRONTEND=noninteractive\n" + - "export CI=true\n" + - "export NONINTERACTIVE=0\n" + - "export FORCE_NONINTERACTIVE=0\n" + - "export HOMEBREW_NO_ENV_HINTS=1\n" + - "export HOMEBREW_NO_INSTALL_CLEANUP=1\n" + - "export HOMEBREW_NO_AUTO_UPDATE=1\n" + - "export HOMEBREW_NO_ANALYTICS=1\n" + - "export HOMEBREW_NO_INSECURE_REDIRECT=1\n" + - "\n" + - "# Override TTY functions for elevated execution\n" + - "function tty() { return 1; }\n" + - "function isatty() { return 1; }\n" + - "\n" + - "# Redirect stdin from /dev/null\n" + - "exec < /dev/null\n" + - "\n" + - sprintf "exec \"%s\"\n" tempFilePath - - let wrapperPath = tempFilePath + "_wrapper.sh" - File.WriteAllText(wrapperPath, wrapperScript) - - // Make wrapper executable - let chmodWrapperInfo = ProcessStartInfo() - chmodWrapperInfo.FileName <- "/bin/chmod" - chmodWrapperInfo.Arguments <- sprintf "+x \"%s\"" wrapperPath - chmodWrapperInfo.UseShellExecute <- false - chmodWrapperInfo.CreateNoWindow <- true - let chmodWrapperProc = Process.Start(chmodWrapperInfo) - if chmodWrapperProc <> null then - chmodWrapperProc.WaitForExit() - - let osascriptCommand = - sprintf """osascript -e 'do shell script "\"%s\"" with prompt \"MacUtil needs your permission to make changes to your computer\" with administrator privileges'""" wrapperPath - - let startInfo = ProcessStartInfo() - startInfo.FileName <- "/bin/sh" - startInfo.Arguments <- sprintf "-c \"%s\"" osascriptCommand - startInfo.UseShellExecute <- false - startInfo.CreateNoWindow <- true - startInfo.RedirectStandardOutput <- true - startInfo.RedirectStandardError <- true - - let proc = Process.Start(startInfo) - - if proc <> null then - onOutput "Script is running with administrator privileges..." - onOutput "Note: Output will appear when script completes (osascript limitation)" - - // Wait for the process to complete - proc.WaitForExit() - - // Get all output at once (osascript limitation) - let output = proc.StandardOutput.ReadToEnd() - let error = proc.StandardError.ReadToEnd() - - // Display output line by line for better readability - if not (String.IsNullOrEmpty(output)) then - let lines = output.Split([| '\n'; '\r' |], StringSplitOptions.RemoveEmptyEntries) - - for line in lines do - onOutput line - - if not (String.IsNullOrEmpty(error)) then - let lines = error.Split([| '\n'; '\r' |], StringSplitOptions.RemoveEmptyEntries) - - for line in lines do - onError line - - onOutput (sprintf "Script completed: %s (Exit Code: %d)" scriptInfo.Name proc.ExitCode) - proc.ExitCode - else - let errorMsg = sprintf "Failed to start elevated script: %s" scriptInfo.Name - onError errorMsg - -1 - finally - // Clean up temporary files - if File.Exists(tempFilePath) then - try - File.Delete(tempFilePath) - with _ -> - () // Ignore cleanup errors - - let wrapperPath = tempFilePath + "_wrapper.sh" - if File.Exists(wrapperPath) then - try - File.Delete(wrapperPath) - with _ -> - () // Ignore cleanup errors - else - // Script doesn't need elevation, run normally - let tempDir = Path.GetTempPath() - let scriptFileName = Path.GetFileName(scriptInfo.Script) - - let tempFileName = - sprintf "%s_%s" (Guid.NewGuid().ToString("N").Substring(0, 8)) scriptFileName - - let tempFilePath = Path.Combine(tempDir, tempFileName) - - try - // Write script content to temporary file - File.WriteAllText(tempFilePath, preprocessedScript) - - // Make the temporary file executable - let chmodStartInfo = ProcessStartInfo() - chmodStartInfo.FileName <- "/bin/chmod" - chmodStartInfo.Arguments <- sprintf "+x \"%s\"" tempFilePath - chmodStartInfo.UseShellExecute <- false - chmodStartInfo.CreateNoWindow <- true - - let chmodProc = Process.Start(chmodStartInfo) - - if chmodProc <> null then - chmodProc.WaitForExit() - - // Execute the script with real-time output - let startInfo = ProcessStartInfo() - startInfo.FileName <- "/bin/bash" - startInfo.Arguments <- sprintf "\"%s\"" tempFilePath - startInfo.UseShellExecute <- false - startInfo.CreateNoWindow <- true - startInfo.RedirectStandardOutput <- true - startInfo.RedirectStandardError <- true - - // Set comprehensive environment variables to handle non-TTY execution - startInfo.EnvironmentVariables.["TERM"] <- "xterm-256color" - startInfo.EnvironmentVariables.["DEBIAN_FRONTEND"] <- "noninteractive" - startInfo.EnvironmentVariables.["CI"] <- "true" - startInfo.EnvironmentVariables.["NONINTERACTIVE"] <- "1" - startInfo.EnvironmentVariables.["FORCE_NONINTERACTIVE"] <- "1" - startInfo.EnvironmentVariables.["HOMEBREW_NO_ENV_HINTS"] <- "1" - startInfo.EnvironmentVariables.["HOMEBREW_NO_INSTALL_CLEANUP"] <- "1" - startInfo.EnvironmentVariables.["HOMEBREW_NO_AUTO_UPDATE"] <- "1" - startInfo.EnvironmentVariables.["HOMEBREW_NO_ANALYTICS"] <- "1" - startInfo.EnvironmentVariables.["HOMEBREW_NO_INSECURE_REDIRECT"] <- "1" - - let proc = Process.Start(startInfo) - - if proc <> null then - // Set up async reading of output streams - let outputBuilder = StringBuilder() - let errorBuilder = StringBuilder() - - // Handle output data received events - proc.OutputDataReceived.Add(fun args -> - if not (String.IsNullOrEmpty(args.Data)) then - outputBuilder.AppendLine(args.Data) |> ignore - onOutput args.Data) - - proc.ErrorDataReceived.Add(fun args -> - if not (String.IsNullOrEmpty(args.Data)) then - errorBuilder.AppendLine(args.Data) |> ignore - onError args.Data) - - // Start async reading - proc.BeginOutputReadLine() - proc.BeginErrorReadLine() - - // Wait for the process to complete - proc.WaitForExit() - - onOutput (sprintf "Script completed: %s (Exit Code: %d)" scriptInfo.Name proc.ExitCode) - proc.ExitCode - else - let errorMsg = sprintf "Failed to start script: %s" scriptInfo.Name - onError errorMsg - -1 - finally - // Clean up temporary file - if File.Exists(tempFilePath) then - try - File.Delete(tempFilePath) - with _ -> - () // Ignore cleanup errors - | None -> - let errorMsg = - sprintf "Script content not found in embedded resources: %s" scriptInfo.FullPath - - onError errorMsg - -1 - with ex -> - let errorMsg = sprintf "Error running script %s: %s" scriptInfo.Name ex.Message - onError errorMsg - -1) - - // Helper function to handle Full Disk Access check and notification - let private handleFullDiskAccessCheck (observer: IObserver>) : bool = - let hasAccess, accessMessage = checkFullDiskAccess() - - if not hasAccess then - observer.OnNext(Choice2Of3 "❌ Full Disk Access Required") - observer.OnNext(Choice2Of3 "") - promptForFullDiskAccess (fun msg -> observer.OnNext(Choice2Of3 msg)) - observer.OnNext(Choice2Of3 "") - observer.OnNext(Choice2Of3 "Click the button below to open Privacy Settings:") - - // Open Privacy Settings automatically - openPrivacySettings() - - observer.OnNext(Choice3Of3 -2) // Special exit code for permission issue - observer.OnCompleted() - false - else - observer.OnNext(Choice1Of3 "✅ Terminal has Full Disk Access - proceeding with script execution") - observer.OnNext(Choice1Of3 "") - true - - // Helper function to resolve script content with common script handling - let private resolveScriptContent (scriptInfo: ScriptInfo) (observer: IObserver>) : string option = - match getEmbeddedResource scriptInfo.FullPath with - | Some scriptContent -> - // Check if script sources common-script.sh - let needsCommonScript = - scriptContent.Contains(". ../common-script.sh") - || scriptContent.Contains(". ../../common-script.sh") - - if needsCommonScript then - observer.OnNext(Choice1Of3 "DEBUG: Script needs common-script.sh, checking embedded resources...") - - // Get common script content - match getEmbeddedResource "common-script.sh" with - | Some commonContent -> - observer.OnNext(Choice1Of3 "DEBUG: Successfully found common-script.sh in embedded resources") - - // Remove sourcing line and combine scripts - let cleanedScript = - scriptContent - .Replace(". ../common-script.sh", "") - .Replace(". ../../common-script.sh", "") - .Trim() - - // Combine: shebang + common functions + original script (without sourcing) - let shebang = "#!/bin/sh -e\n\n" - let commonFunctions = - commonContent - .Replace("#!/bin/sh -e", "") - .Replace("# shellcheck disable=SC2034", "") - .Trim() - - let combinedScript = - shebang + "# Embedded common script functions\n" + - commonFunctions + "\n\n# Original script content\n" + - cleanedScript - - Some combinedScript - | None -> - observer.OnNext(Choice2Of3 "Warning: common-script.sh not found in embedded resources, using original script") - Some scriptContent - else - Some scriptContent - | None -> - let errorMsg = sprintf "Script content not found in embedded resources: %s" scriptInfo.FullPath - observer.OnNext(Choice2Of3 errorMsg) - observer.OnCompleted() - None - - // Helper function to setup environment variables for non-TTY execution - let private setupEnvironmentVariables (startInfo: ProcessStartInfo) : unit = - startInfo.EnvironmentVariables.["TERM"] <- "xterm-256color" - startInfo.EnvironmentVariables.["DEBIAN_FRONTEND"] <- "noninteractive" - startInfo.EnvironmentVariables.["CI"] <- "true" - startInfo.EnvironmentVariables.["HOMEBREW_NO_ENV_HINTS"] <- "1" - startInfo.EnvironmentVariables.["HOMEBREW_NO_INSTALL_CLEANUP"] <- "1" - startInfo.EnvironmentVariables.["HOMEBREW_NO_AUTO_UPDATE"] <- "1" - startInfo.EnvironmentVariables.["HOMEBREW_NO_ANALYTICS"] <- "1" - startInfo.EnvironmentVariables.["HOMEBREW_NO_INSECURE_REDIRECT"] <- "1" - startInfo.EnvironmentVariables.["NONINTERACTIVE"] <- "1" - startInfo.EnvironmentVariables.["FORCE_NONINTERACTIVE"] <- "1" - - // Helper function to execute script and handle output - let private executeScript (tempFilePath: string) (scriptInfo: ScriptInfo) (observer: IObserver>) : unit = - // Make the temporary file executable - let chmodStartInfo = ProcessStartInfo() - chmodStartInfo.FileName <- "/bin/chmod" - chmodStartInfo.Arguments <- sprintf "+x \"%s\"" tempFilePath - chmodStartInfo.UseShellExecute <- false - chmodStartInfo.CreateNoWindow <- true - - let chmodProc = Process.Start(chmodStartInfo) - if chmodProc <> null then - chmodProc.WaitForExit() - - // Execute the script with real-time output - let startInfo = ProcessStartInfo() - startInfo.FileName <- "/bin/bash" - startInfo.Arguments <- sprintf "\"%s\"" tempFilePath - startInfo.UseShellExecute <- false - startInfo.CreateNoWindow <- true - startInfo.RedirectStandardOutput <- true - startInfo.RedirectStandardError <- true - - // Set comprehensive environment variables to handle non-TTY execution - setupEnvironmentVariables startInfo - - let proc = Process.Start(startInfo) - - match proc with - | null -> - let errorMsg = sprintf "Failed to start script: %s" scriptInfo.Name - observer.OnNext(Choice2Of3 errorMsg) - observer.OnCompleted() - | _ -> - // Handle output data received events - proc.OutputDataReceived.Add(fun args -> - if not (String.IsNullOrEmpty(args.Data)) then - observer.OnNext(Choice1Of3 args.Data)) - - proc.ErrorDataReceived.Add(fun args -> - if not (String.IsNullOrEmpty(args.Data)) then - observer.OnNext(Choice2Of3 args.Data)) - - // Start async reading - proc.BeginOutputReadLine() - proc.BeginErrorReadLine() - - // Wait for the process to complete - proc.WaitForExit() - - observer.OnNext(Choice3Of3 proc.ExitCode) - observer.OnCompleted() - - // Helper function to clean up temporary files - let private cleanupTempFile (tempFilePath: string) : unit = - if File.Exists(tempFilePath) then - try - File.Delete(tempFilePath) - with _ -> - () // Ignore cleanup errors - - // Alternative version that returns an IObservable for reactive programming - simplified - let runScriptObservable (scriptInfo: ScriptInfo) : IObservable> = - { new IObservable> with - member __.Subscribe(observer) = - let task = - Task.Run(fun () -> - try - // Step 1: Check Full Disk Access (early return if failed) - if not (handleFullDiskAccessCheck observer) then - () // Already handled in the helper function - else - // Step 2: Resolve script content (early return if failed) - match resolveScriptContent scriptInfo observer with - | None -> () // Already handled in the helper function - | Some finalScriptContent -> - // Step 3: Preprocess the script for non-TTY execution - let preprocessedScript = preprocessScriptForNonTTY finalScriptContent - - // Step 4: Create temporary file and execute - let tempDir = Path.GetTempPath() - let scriptFileName = Path.GetFileName(scriptInfo.Script) - let tempFileName = sprintf "%s_%s" (Guid.NewGuid().ToString("N").Substring(0, 8)) scriptFileName - let tempFilePath = Path.Combine(tempDir, tempFileName) - - try - // Write script content to temporary file - File.WriteAllText(tempFilePath, preprocessedScript) - - // Execute the script - executeScript tempFilePath scriptInfo observer - finally - // Clean up temporary file - cleanupTempFile tempFilePath - with ex -> - let errorMsg = sprintf "Error running script %s: %s" scriptInfo.Name ex.Message - observer.OnNext(Choice2Of3 errorMsg) - observer.OnCompleted()) - - { new IDisposable with - member __.Dispose() = () } } diff --git a/MacUtilGUI/TTY_FIXES.md b/MacUtilGUI/TTY_FIXES.md deleted file mode 100644 index c61b6fc..0000000 --- a/MacUtilGUI/TTY_FIXES.md +++ /dev/null @@ -1,137 +0,0 @@ -# TTY/Non-Interactive Execution Fixes for macOS App Bundle - -## Problem -When running the MacUtil GUI as a `.app` bundle in macOS, scripts were failing because: - -1. **No TTY Available**: App bundles don't run in a terminal, so `stdin` is not a TTY -2. **Interactive Prompts**: Scripts expecting user input would hang or fail -3. **Homebrew Installation Issues**: Homebrew installer would try to reinstall even when already present -4. **TTY Detection Failures**: Scripts checking `tty -s` or `[ -t 0 ]` would fail - -## Solution Implemented - -### 1. Environment Variables -Added comprehensive environment variable setup for all script execution paths: - -```bash -export TERM=xterm-256color -export DEBIAN_FRONTEND=noninteractive -export CI=true -export HOMEBREW_NO_ENV_HINTS=1 -export HOMEBREW_NO_INSTALL_CLEANUP=1 -export HOMEBREW_NO_AUTO_UPDATE=1 -export NONINTERACTIVE=1 -export FORCE_NONINTERACTIVE=1 -``` - -### 2. Script Preprocessing Function -Created `preprocessScriptForNonTTY()` that: - -- **Disables TTY checks**: Comments out lines containing `tty -s`, `[ -t 0 ]`, etc. -- **Forces non-interactive mode**: Adds `--force` flag to brew commands -- **Adds safety headers**: Includes environment setup and TTY function override -- **Handles package managers**: Adds `-y` flags to apt commands where needed - -### 3. TTY Function Override -Added a fake `tty()` function that always returns "not a TTY": - -```bash -function tty() { - return 1 # Always return "not a TTY" -} -``` - -### 4. ProcessStartInfo Environment Setup -Updated all three script execution paths in `ScriptService.fs`: -- Regular script execution -- Elevated (sudo) script execution via osascript -- Async script execution - -## Files Modified - -### `/Services/ScriptService.fs` -- Added `preprocessScriptForNonTTY()` function -- Updated all `ProcessStartInfo` instances with environment variables -- Updated osascript command to include environment variable exports -- Applied preprocessing to all script execution paths - -## Testing the Fixes - -### Before the Fix -``` -ERROR: stdin is not a TTY -ERROR: Checking for sudo access... -ERROR: Homebrew installation attempted when already installed -``` - -### After the Fix -Scripts should now run smoothly in the `.app` bundle environment without TTY-related errors. - -## What Each Environment Variable Does - -| Variable | Purpose | -|----------|---------| -| `TERM=xterm-256color` | Provides a valid terminal type | -| `DEBIAN_FRONTEND=noninteractive` | Prevents apt from prompting for input | -| `CI=true` | Signals automated environment to many tools | -| `HOMEBREW_NO_ENV_HINTS=1` | Disables Homebrew environment hints | -| `HOMEBREW_NO_INSTALL_CLEANUP=1` | Skips automatic cleanup | -| `HOMEBREW_NO_AUTO_UPDATE=1` | Prevents automatic updates | -| `NONINTERACTIVE=1` | Custom flag for scripts to detect non-interactive mode | -| `FORCE_NONINTERACTIVE=1` | Additional flag for scripts | - -## Script Preprocessing Examples - -### TTY Check Disabling -**Before:** -```bash -if tty -s; then - echo "Running in terminal" -fi -``` - -**After:** -```bash -# TTY check disabled for .app bundle execution: if tty -s; then -# echo "Running in terminal" -# fi -``` - -### Brew Command Enhancement -**Before:** -```bash -brew install package -``` - -**After:** -```bash -brew install --quiet package -``` - -**For update/upgrade commands:** -```bash -brew update --quiet -brew upgrade --quiet -``` - -## Verification Steps - -1. **Build new app bundle**: `./deploy_macos.sh` -2. **Test in .app environment**: `open dist/MacUtil-Intel.app` -3. **Run scripts that previously failed**: Check for TTY-related errors -4. **Monitor script output**: Should see environment variables being set - -## Future Considerations - -- **Add more package manager support**: Handle `dnf`, `yum`, `pacman` etc. -- **Enhanced script detection**: Better detection of interactive prompts -- **Logging improvements**: Add debug output for preprocessing steps -- **Custom script flags**: Allow scripts to opt-out of preprocessing if needed - -## Benefits - -✅ **No more TTY errors** when running as .app bundle -✅ **Homebrew installs work correctly** without re-installation attempts -✅ **Scripts run non-interactively** without hanging on prompts -✅ **Backward compatibility** - still works in terminal environments -✅ **Comprehensive coverage** - all execution paths updated diff --git a/MacUtilGUI/ViewModels/AppRowViewModel.fs b/MacUtilGUI/ViewModels/AppRowViewModel.fs new file mode 100644 index 0000000..2e34d29 --- /dev/null +++ b/MacUtilGUI/ViewModels/AppRowViewModel.fs @@ -0,0 +1,21 @@ +namespace MacUtilGUI.ViewModels + +open MacUtilGUI.Models + +type AppRowViewModel(app: AppEntry, isChecked: bool) = + inherit ViewModelBase() + + let mutable isChecked = isChecked + + member _.Id = app.Id + member _.Content = app.Content + member _.Description = app.Description + member _.Category = app.Category + member _.App = app + + member this.IsChecked + with get () = isChecked + and set v = + if isChecked <> v then + isChecked <- v + this.OnPropertyChanged("IsChecked") diff --git a/MacUtilGUI/ViewModels/MainWindowViewModel.fs b/MacUtilGUI/ViewModels/MainWindowViewModel.fs index a265524..e32667d 100644 --- a/MacUtilGUI/ViewModels/MainWindowViewModel.fs +++ b/MacUtilGUI/ViewModels/MainWindowViewModel.fs @@ -4,8 +4,6 @@ open System open System.IO open System.Collections.ObjectModel open System.Windows.Input -open System.Threading.Tasks -open Avalonia.Threading open MacUtilGUI.Models open MacUtilGUI.Services @@ -21,16 +19,15 @@ type RelayCommand(canExecute: obj -> bool, execute: obj -> unit) = new(execute: obj -> unit) = RelayCommand((fun _ -> true), execute) -type MainWindowViewModel(catalog: Catalog, client: IDefaultsClient, killer: IProcessKiller) as this = +type MainWindowViewModel(catalog: Catalog, client: IDefaultsClient, killer: IProcessKiller, brew: BrewExec) as this = inherit ViewModelBase() - let mutable selectedScript: ScriptInfo option = None - let mutable scriptOutput: string = "" - let mutable isScriptRunning: bool = false let mutable statusText: string = "" - let categories = ObservableCollection() + let mutable searchText: string = "" let safeTweaks = ObservableCollection() let cautionTweaks = ObservableCollection() + let allApps = ResizeArray() + let apps = ObservableCollection() let allRows () = Seq.append safeTweaks cautionTweaks @@ -41,90 +38,80 @@ type MainWindowViewModel(catalog: Catalog, client: IDefaultsClient, killer: IPro let selectedRows () = allRows () |> Seq.filter (fun row -> row.IsChecked) |> Seq.toList + let selectedAppRows () = + allApps |> Seq.filter (fun row -> row.IsChecked) |> Seq.toList + + let setStatus text = + statusText <- text + this.OnPropertyChanged("StatusText") + let applySelected () = let selected = selectedRows () if selected.IsEmpty then - statusText <- "Nothing is selected." - this.OnPropertyChanged("StatusText") + setStatus "Nothing is selected." else for row in selected do ActionEngine.apply client killer row.Tweak refreshDetect () - statusText <- sprintf "Applied %d tweak(s)." selected.Length - this.OnPropertyChanged("StatusText") + setStatus (sprintf "Applied %d tweak(s)." selected.Length) let undoSelected () = let selected = selectedRows () if selected.IsEmpty then - statusText <- "Nothing is selected." - this.OnPropertyChanged("StatusText") + setStatus "Nothing is selected." else for row in selected do ActionEngine.undo client killer row.Tweak refreshDetect () - statusText <- sprintf "Undid %d tweak(s)." selected.Length - this.OnPropertyChanged("StatusText") + setStatus (sprintf "Undid %d tweak(s)." selected.Length) + + let refreshAppDetect () = + for row in allApps do + row.IsChecked <- BrewClient.installed brew row.App + + let matches (row: AppRowViewModel) (query: string) = + if String.IsNullOrWhiteSpace query then + true + else + let hit (value: string) = + value.IndexOf(query.Trim(), StringComparison.OrdinalIgnoreCase) >= 0 + + hit row.Content || hit row.Id || hit row.Category || hit row.Description + + let applyFilter () = + apps.Clear() + + for row in allApps do + if matches row searchText then + apps.Add(row) + + let installSelected () = + let selected = selectedAppRows () + + if selected.IsEmpty then + setStatus "Nothing is selected." + else + let mutable errors = [] + + for row in selected do + match BrewClient.install brew row.App with + | Ok() -> () + | Error msg -> errors <- msg :: errors + + refreshAppDetect () + + if errors.IsEmpty then + setStatus (sprintf "Installed %d app(s)." selected.Length) + else + setStatus (String.concat "\n" (List.rev errors)) let applyCommand = RelayCommand(fun _ -> applySelected ()) let undoCommand = RelayCommand(fun _ -> undoSelected ()) - - let selectScriptCommand = - RelayCommand(fun parameter -> - match parameter with - | :? ScriptInfo as script -> - selectedScript <- Some script - scriptOutput <- "" - this.OnPropertyChanged("SelectedScript") - this.OnPropertyChanged("ScriptOutput") - this.OnPropertyChanged("CanRunScript") - this.OnPropertyChanged("SelectedScriptName") - this.OnPropertyChanged("SelectedScriptDescription") - this.OnPropertyChanged("SelectedScriptCategory") - this.OnPropertyChanged("SelectedScriptFile") - | _ -> ()) - - let runScriptCommand = - RelayCommand(fun _ -> - match selectedScript with - | Some script when not isScriptRunning -> - isScriptRunning <- true - scriptOutput <- "Starting script...\n" - this.OnPropertyChanged("ScriptOutput") - this.OnPropertyChanged("CanRunScript") - this.OnPropertyChanged("IsScriptRunning") - - let onOutput (line: string) = - Dispatcher.UIThread.InvokeAsync(fun () -> - scriptOutput <- scriptOutput + line + "\n" - this.OnPropertyChanged("ScriptOutput")) - |> ignore - - let onError (line: string) = - Dispatcher.UIThread.InvokeAsync(fun () -> - scriptOutput <- scriptOutput + "[ERROR] " + line + "\n" - this.OnPropertyChanged("ScriptOutput")) - |> ignore - - let scriptTask = ScriptService.runScript script onOutput onError - - scriptTask.ContinueWith(fun (task: Task) -> - Dispatcher.UIThread.InvokeAsync(fun () -> - isScriptRunning <- false - - scriptOutput <- - scriptOutput - + sprintf "\n=== Script completed with exit code: %d ===" task.Result - - this.OnPropertyChanged("ScriptOutput") - this.OnPropertyChanged("CanRunScript") - this.OnPropertyChanged("IsScriptRunning")) - |> ignore) - |> ignore - | _ -> ()) + let installCommand = RelayCommand(fun _ -> installSelected ()) let categoryRank category = match category with @@ -135,6 +122,16 @@ type MainWindowViewModel(catalog: Catalog, client: IDefaultsClient, killer: IPro | "Privacy" -> 4 | _ -> 5 + let appCategoryRank category = + match category with + | "Communication Apps" -> 0 + | "Developer Tools" -> 1 + | "Web Browsers" -> 2 + | "Terminal" -> 3 + | "Shell" -> 4 + | "Utilities" -> 5 + | _ -> 6 + do catalog.Tweaks |> Map.toSeq @@ -147,13 +144,17 @@ type MainWindowViewModel(catalog: Catalog, client: IDefaultsClient, killer: IPro | Risk.Safe -> safeTweaks.Add(row) | Risk.Caution -> cautionTweaks.Add(row)) - for category in ScriptService.loadAllScripts () do - let fromSystemSetup = - category.Scripts - |> List.exists (fun script -> script.FullPath.StartsWith("system-setup")) + catalog.Apps + |> Map.toSeq + |> Seq.map snd + |> Seq.sortBy (fun app -> appCategoryRank app.Category, app.Content) + |> Seq.iter (fun app -> + allApps.Add(AppRowViewModel(app, BrewClient.installed brew app))) + + applyFilter () - if not fromSystemSetup then - categories.Add(category) + new(catalog, client, killer) = + MainWindowViewModel(catalog, client, killer, fun _ -> 0, "", "") new() = let dir = Path.Combine(AppContext.BaseDirectory, "config") @@ -161,57 +162,42 @@ type MainWindowViewModel(catalog: Catalog, client: IDefaultsClient, killer: IPro MainWindowViewModel( ConfigLoader.load dir, UnixDefaultsClient() :> IDefaultsClient, - UnixProcessKiller() :> IProcessKiller + UnixProcessKiller() :> IProcessKiller, + BrewClient.unixExec ) member _.SafeTweaks = safeTweaks member _.CautionTweaks = cautionTweaks + member _.Apps = apps + + member _.AllApps = allApps :> seq + member _.StatusText = statusText + member this.SearchText + with get () = searchText + and set v = + if searchText <> v then + searchText <- if isNull v then "" else v + applyFilter () + this.OnPropertyChanged("SearchText") + member _.SelectedIds = selectedRows () |> List.map (fun row -> row.Id) + member _.SelectedAppIds = selectedAppRows () |> List.map (fun row -> row.Id) + member _.ApplySelected() = applySelected () member _.UndoSelected() = undoSelected () + member _.InstallSelected() = installSelected () + member _.ApplyCommand = applyCommand member _.UndoCommand = undoCommand - member _.Categories = categories - - member _.SelectedScript = selectedScript - - member _.ScriptOutput = scriptOutput - - member _.SelectedScriptName = - match selectedScript with - | Some script -> script.Name - | None -> "" - - member _.SelectedScriptDescription = - match selectedScript with - | Some script -> script.Description - | None -> "" - - member _.SelectedScriptCategory = - match selectedScript with - | Some script -> script.Category - | None -> "" - - member _.SelectedScriptFile = - match selectedScript with - | Some script -> script.Script - | None -> "" - - member _.CanRunScript = selectedScript.IsSome && not isScriptRunning - - member _.IsScriptRunning = isScriptRunning - - member _.SelectScriptCommand = selectScriptCommand - - member _.RunScriptCommand = runScriptCommand + member _.InstallCommand = installCommand member _.Title = "MacUtil" diff --git a/MacUtilGUI/Views/MainWindow.axaml b/MacUtilGUI/Views/MainWindow.axaml index d08b3cc..dbe317d 100644 --- a/MacUtilGUI/Views/MainWindow.axaml +++ b/MacUtilGUI/Views/MainWindow.axaml @@ -1,7 +1,6 @@ - - - - - - - - - - - - - -