Exemplo n.º 1
0
        private void PromptExportMap(Map map)
        {
            LogTextBox.ClearContent();
            string destinationFolderPath = Path.Combine(Program.customMapsPath, map.Name);

            try {
                if (Directory.Exists(destinationFolderPath))
                {
                    LogTextBox.WriteLine(string.Format(Text.ConfirmExportAndOverwrite, destinationFolderPath));
                    int response = SelectionPrompt.PromptSelection(exportCommands, new GUI.SelectionPrompt.Options()
                    {
                        AllowCancel = true, Index = 2
                    });
                    switch (response)
                    {
                    case 0:                             // Overwrite
                        ExportMap(map, destinationFolderPath, true);
                        break;

                    case 1:                             // Export with Timestamp
                        string timestamp = DateTime.Now.ToString("_yyyy-MM-dd_HH-mm-ss.fffffff");
                        //string timestamp = DateTime.Now.ToString("yyyy’-‘MM’-‘dd’T’HH’:’mm’:’ss.fffffffK");
                        ExportMap(map, destinationFolderPath + timestamp, false);
                        break;
                    }
                }
                else
                {
                    ExportMap(map, destinationFolderPath, false);
                }
            } catch (Exception e) {
                ignoreNextSelectionChangedEvent = true;
                LogTextBox.WriteLine(string.Format(Text.ErrorWithMessage, e.Message));
            }
        }
            private string SelectCsProj()
            {
                var csprojFiles = FileSystem.Directory.GetFiles(".", "*.csproj");

                if (csprojFiles.Length == 1)
                {
                    return(csprojFiles.First());
                }

                if (csprojFiles.Length == 0)
                {
                    AnsiConsole.Write(new Markup($"[bold red]Can't find a project file in current directory![/]"));
                    AnsiConsole.WriteLine();
                    AnsiConsole.Write(new Markup($"[bold red]Please run Sergen in a folder that contains the Asp.Net Core project.[/]"));
                    AnsiConsole.WriteLine();
                    return(null);
                }

                AnsiConsole.WriteLine();
                AnsiConsole.Write(new Spectre.Console.Rule($"[bold orange1]Please select an Asp.Net Core project file[/]")
                {
                    Alignment = Justify.Left
                });
                AnsiConsole.WriteLine();
                var selections = new SelectionPrompt <string>()
                                 .PageSize(10)
                                 .MoreChoicesText("[grey](Move up and down to reveal more project files)[/]")
                                 .AddChoices(csprojFiles);

                return(AnsiConsole.Prompt(selections));
            }
Exemplo n.º 3
0
        public static T Choose <T>(IEnumerable <T> items, string title)
        {
            var selection = new SelectionPrompt <T>()
                            .Title(title)
                            .PageSize(10)
                            .AddChoices(items);

            return(AnsiConsole.Prompt(selection));
        }
Exemplo n.º 4
0
        public void Choose(IAnsiConsole console, int pageSize = 5)
        {
            var prompt = new SelectionPrompt <string>
            {
                Title    = "What is your favorite color?",
                PageSize = pageSize
            }.AddChoices("blue", "purple", "red", "orange", "yellow", "green");
            var answer = console.Prompt(prompt);

            console.WriteLine(answer);
        }
    /// <summary>
    /// Sets the title.
    /// </summary>
    /// <typeparam name="T">The prompt result type.</typeparam>
    /// <param name="obj">The prompt.</param>
    /// <param name="title">The title markup text.</param>
    /// <returns>The same instance so that multiple calls can be chained.</returns>
    public static SelectionPrompt <T> Title <T>(this SelectionPrompt <T> obj, string?title)
        where T : notnull
    {
        if (obj is null)
        {
            throw new ArgumentNullException(nameof(obj));
        }

        obj.Title = title;
        return(obj);
    }
    /// <summary>
    /// Sets the selection mode.
    /// </summary>
    /// <typeparam name="T">The prompt result type.</typeparam>
    /// <param name="obj">The prompt.</param>
    /// <param name="mode">The selection mode.</param>
    /// <returns>The same instance so that multiple calls can be chained.</returns>
    public static SelectionPrompt <T> Mode <T>(this SelectionPrompt <T> obj, SelectionMode mode)
        where T : notnull
    {
        if (obj is null)
        {
            throw new ArgumentNullException(nameof(obj));
        }

        obj.Mode = mode;
        return(obj);
    }
    /// <summary>
    /// Sets the highlight style of the selected choice.
    /// </summary>
    /// <typeparam name="T">The prompt result type.</typeparam>
    /// <param name="obj">The prompt.</param>
    /// <param name="highlightStyle">The highlight style of the selected choice.</param>
    /// <returns>The same instance so that multiple calls can be chained.</returns>
    public static SelectionPrompt <T> HighlightStyle <T>(this SelectionPrompt <T> obj, Style highlightStyle)
        where T : notnull
    {
        if (obj is null)
        {
            throw new ArgumentNullException(nameof(obj));
        }

        obj.HighlightStyle = highlightStyle;
        return(obj);
    }
    /// <summary>
    /// Sets the text that will be displayed if there are more choices to show.
    /// </summary>
    /// <typeparam name="T">The prompt result type.</typeparam>
    /// <param name="obj">The prompt.</param>
    /// <param name="text">The text to display.</param>
    /// <returns>The same instance so that multiple calls can be chained.</returns>
    public static SelectionPrompt <T> MoreChoicesText <T>(this SelectionPrompt <T> obj, string?text)
        where T : notnull
    {
        if (obj is null)
        {
            throw new ArgumentNullException(nameof(obj));
        }

        obj.MoreChoicesText = text;
        return(obj);
    }
    /// <summary>
    /// Sets the function to create a display string for a given choice.
    /// </summary>
    /// <typeparam name="T">The prompt type.</typeparam>
    /// <param name="obj">The prompt.</param>
    /// <param name="displaySelector">The function to get a display string for a given choice.</param>
    /// <returns>The same instance so that multiple calls can be chained.</returns>
    public static SelectionPrompt <T> UseConverter <T>(this SelectionPrompt <T> obj, Func <T, string>?displaySelector)
        where T : notnull
    {
        if (obj is null)
        {
            throw new ArgumentNullException(nameof(obj));
        }

        obj.Converter = displaySelector;
        return(obj);
    }
    /// <summary>
    /// Adds multiple choices.
    /// </summary>
    /// <typeparam name="T">The prompt result type.</typeparam>
    /// <param name="obj">The prompt.</param>
    /// <param name="choices">The choices to add.</param>
    /// <returns>The same instance so that multiple calls can be chained.</returns>
    public static SelectionPrompt <T> AddChoices <T>(this SelectionPrompt <T> obj, IEnumerable <T> choices)
        where T : notnull
    {
        if (obj is null)
        {
            throw new ArgumentNullException(nameof(obj));
        }

        foreach (var choice in choices)
        {
            obj.AddChoice(choice);
        }

        return(obj);
    }
Exemplo n.º 11
0
    public ProjectInformation?Select()
    {
        var examples = _finder.FindExamples();

        if (examples.Count == 0)
        {
            _console.Markup("[yellow]No examples could be found.[/]");
            return(null);
        }

        var prompt = new SelectionPrompt <string>();
        var groups = examples.GroupBy(ex => ex.Group);

        if (groups.Count() == 1)
        {
            prompt.AddChoices(examples.Select(x => x.Name));
        }
        else
        {
            var noGroupExamples = new List <string>();

            foreach (var group in groups)
            {
                if (string.IsNullOrEmpty(group.Key))
                {
                    noGroupExamples.AddRange(group.Select(x => x.Name));
                }
                else
                {
                    prompt.AddChoiceGroup(
                        group.Key,
                        group.Select(x => x.Name));
                }
            }

            if (noGroupExamples.Count > 0)
            {
                prompt.AddChoices(noGroupExamples);
            }
        }

        var example = AnsiConsole.Prompt(prompt
                                         .Title("[yellow]Choose example to run[/]")
                                         .MoreChoicesText("[grey](Move up and down to reveal more examples)[/]")
                                         .Mode(SelectionMode.Leaf));

        return(examples.FirstOrDefault(x => x.Name == example));
    }
Exemplo n.º 12
0
        public GameShell()
        {
            this.MainMenu = new SelectionPrompt <string>()
                            .HighlightStyle(Style.Parse("yellow"))
                            .PageSize(10)
                            .AddChoices(new[] {
                "New", "Load", "Exit",
            });

            this.IngameMenu = new SelectionPrompt <string>()
                              .HighlightStyle(Style.Parse("yellow"))
                              .PageSize(10)
                              .AddChoices(new[] {
                "Manage", "Recruit", "Expand", "Raid", "Save", "Exit"
            });
        }
    /// <summary>
    /// Sets how many choices that are displayed to the user.
    /// </summary>
    /// <typeparam name="T">The prompt result type.</typeparam>
    /// <param name="obj">The prompt.</param>
    /// <param name="pageSize">The number of choices that are displayed to the user.</param>
    /// <returns>The same instance so that multiple calls can be chained.</returns>
    public static SelectionPrompt <T> PageSize <T>(this SelectionPrompt <T> obj, int pageSize)
        where T : notnull
    {
        if (obj is null)
        {
            throw new ArgumentNullException(nameof(obj));
        }

        if (pageSize <= 2)
        {
            throw new ArgumentException("Page size must be greater or equal to 3.", nameof(pageSize));
        }

        obj.PageSize = pageSize;
        return(obj);
    }
    /// <summary>
    /// Adds multiple grouped choices.
    /// </summary>
    /// <typeparam name="T">The prompt result type.</typeparam>
    /// <param name="obj">The prompt.</param>
    /// <param name="group">The group.</param>
    /// <param name="choices">The choices to add.</param>
    /// <returns>The same instance so that multiple calls can be chained.</returns>
    public static SelectionPrompt <T> AddChoiceGroup <T>(this SelectionPrompt <T> obj, T group, IEnumerable <T> choices)
        where T : notnull
    {
        if (obj is null)
        {
            throw new ArgumentNullException(nameof(obj));
        }

        var root = obj.AddChoice(group);

        foreach (var choice in choices)
        {
            root.AddChild(choice);
        }

        return(obj);
    }
        public static Installation?GetTargetInstallation(string?path, string promptTitle)
        {
            var installations = new List <Installation>();

            AnsiConsole
            .Status()
            .Start("Discovering [green]Escape From Tarkov[/] installations...", _ =>
            {
                installations = Installation
                                .DiscoverInstallations()
                                .Distinct()
                                .ToList();
            });

            if (path is not null && Installation.TryDiscoverInstallation(path, out var installation))
            {
                installations.Add(installation);
            }

            installations = installations
                            .Distinct()
                            .OrderBy(i => i.Location)
                            .ToList();

            switch (installations.Count)
            {
            case 0:
                AnsiConsole.MarkupLine("[yellow]No [green]EscapeFromTarkov[/] installation found, please re-run this installer, passing the installation path as argument.[/]");
                return(null);

            case 1:
                var first = installations.First();
                return(AnsiConsole.Confirm($"Continue with [green]EscapeFromTarkov ({first.Version})[/] in [blue]{first.Location}[/] ?") ? first : null);

            default:
                var prompt = new SelectionPrompt <Installation>
                {
                    Converter = i => i.Location,
                    Title     = promptTitle
                };
                prompt.AddChoices(installations);
                return(AnsiConsole.Prompt(prompt));
            }
        }
        private static Installation?GetTargetInstallation(Settings settings)
        {
            var installations = new List <Installation>();

            AnsiConsole
            .Status()
            .Start("Discovering [green]Escape From Tarkov[/] installations...", _ =>
            {
                installations = Installation
                                .DiscoverInstallations()
                                .Distinct()
                                .ToList();
            });

            if (settings.Path is not null && Installation.TryDiscoverInstallation(settings.Path, out var installation))
            {
                installations.Add(installation);
            }

            installations = installations
                            .Distinct()
                            .OrderBy(i => i.Location)
                            .ToList();

            switch (installations.Count)
            {
            case 0:
                AnsiConsole.MarkupLine("[yellow]No [green]EscapeFromTarkov[/] installation found, please re-run this installer, passing the installation path as argument.[/]");
                return(null);

            case 1:
                return(installations.First());

            default:
                var prompt = new SelectionPrompt <Installation>
                {
                    Converter = i => i.Location,
                    Title     = "Please select where to install the trainer"
                };
                prompt.AddChoices(installations);
                return(AnsiConsole.Prompt(prompt));
            }
        }
Exemplo n.º 17
0
        public void Should_Not_Throw_When_Selecting_An_Item_With_Escaped_Markup()
        {
            // Given
            var console = new TestConsole();

            console.Profile.Capabilities.Interactive = true;
            console.Input.PushKey(ConsoleKey.Enter);
            var input = "[red]This text will never be red[/]".EscapeMarkup();

            // When
            var prompt = new SelectionPrompt <string>()
                         .Title("Select one")
                         .AddChoices(input);

            prompt.Show(console);

            // Then
            console.Output.ShouldContain(@"[red]This text will never be red[/]");
        }
Exemplo n.º 18
0
        public static string?RenderPrompt(int uxLevel, Selector selector)
        {
            if (uxLevel == 0)
            {
                DisplayLegacyStyle(selector);
                return(null);
            }
            var prompt = new SelectionPrompt <string>().Title($"Select the {selector.ItemTypeName} you'd like to use")
                         .PageSize(10);
            var selectorItems = selector.Items.Select(x => (x.Common ? "*" : "") + x.Value);

            if (selector.Sorted)
            {
                selectorItems = selectorItems.OrderBy(x => x);
            }
            prompt.AddChoices(selectorItems);
            var selectedItem = AnsiConsole.Prompt(prompt);

            if (selectedItem.StartsWith("*"))
            {
                selectedItem = selectedItem[1..];
Exemplo n.º 19
0
        public void ShowBackups()
        {
            if (backedUpSaves.Count == 0)
            {
                LogTextBox.WriteLine(Text.NoBackedUpSaves);
                return;
            }
            BackedUpSavesList.Clear();
            BackedUpSavesList.Draw();
            BackedUpSavesList.Select(0);
            bool promptQuit = false;

            while (!promptQuit)
            {
                var selection = BackedUpSavesList.PromptSelection();
                if (selection.Command == Properties.Command.Confirm)
                {
                    BackedUpSavesList.HighlightCurrentItem();
                    var response = SelectionPrompt.PromptSelection(new string[] { Text.LoadBackup }, true);
                    if (response == 0)                       // Load Backup
                    {
                        SwapSaves(selection.Text);
                        RefreshInfo();
                        LogTextBox.WriteLine(string.Format(Text.LoadedBackup, selection.Text));
                        promptQuit = true;
                    }
                    else
                    {
                        BackedUpSavesList.SelectCurrentItem();
                    }
                }
                else if (selection.Command == Properties.Command.Cancel)
                {
                    promptQuit = true;
                }
            }

            WriteSummary();
        }
Exemplo n.º 20
0
        public override void Selected(GUI.Selection selection)
        {
            switch (selection.RowIndex)
            {
            case 0:
                ShowOnlyWIPCheckBox.Checked = !ShowOnlyWIPCheckBox.Checked;
                RefreshMapList();
                mapList.NavigateToDefault();
                break;

            case 1:
                if (NewMapNameInput.PromptText())
                {
                    var newMap = new Map(
                        NewMapNameInput.Text,
                        null,
                        null,
                        null,
                        null,
                        new string[0],
                        new string[0],
                        true);
                    Program.installedMaps.Add(newMap);
                    Program.SaveInstalledMaps();
                    RefreshMapList();
                }
                mapList.Select(mapList.Items.Count - 1);
                break;

            case 2:                     // Separator
                break;

            default:
                mapList.HighlightCurrentItem();
                var      selectedMap = (GUI.SelectableMap)(selection.SelectedItem);
                var      map         = selectedMap.Map;
                string[] selections;
                var      options = new GUI.SelectionPrompt.Options()
                {
                    AllowCancel = true,
                };
                if (map.IsValid)
                {
                    selections = mapCommands;
                }
                else
                {
                    selections    = mapCommandsWithIssues;
                    options.Index = 3;
                }

                int response = SelectionPrompt.PromptSelection(selections, options);
                switch (response)
                {
                case 0:                                 // Edit Map Info
                    EditMapInfo(map);
                    break;

                case 1:                                 // Edit Levels
                    EditLevels(map);
                    mapList.Clear();
                    mapList.Draw();
                    break;

                case 2:                                 // Export
                    PromptExportMap(map);
                    break;

                case 3:                                 // Show Issues
                    map.ShowIssues();
                    DrawAll();
                    break;
                }

                mapList.SelectCurrentItem();
                break;
            }
        }
Exemplo n.º 21
0
        private void EditLevels(Map map)
        {
            RefreshLevelList(map);
            levelList.NavigateToDefault();
            bool quitPrompt = false;

            while (!quitPrompt)
            {
                GUI.Selection selection = levelList.PromptSelection();
                switch (selection.Command)
                {
                case Properties.Command.Confirm:
                    switch (selection.RowIndex)
                    {
                    case 0:                                     // Add New Level
                        if (levelNameInput.PromptText())
                        {
                            LogTextBox.ClearContent();
                            string levelName = levelNameInput.Text;
                            // Check if level already exists
                            string levelDestination  = Path.Combine(Program.installedLevelsPath, levelName + Program.LevelFileExtension);
                            string scriptDestination = Path.Combine(Program.installedScriptsPath, levelName + Program.ScriptFileExtension);
                            if (File.Exists(levelDestination) || File.Exists((scriptDestination)))
                            {
                                LogTextBox.WriteLine(string.Format(Text.LevelOrScriptAlreadyExists, levelName + Program.LevelFileExtension, levelName + Program.ScriptFileExtension));
                            }
                            else
                            {
                                File.Copy(Program.emptyLevelTemplatePath, levelDestination);
                                File.Copy(Program.emptyScriptTemplatePath, scriptDestination);
                                map.AddLevel(levelName);
                                Program.SaveInstalledMaps();
                                RefreshLevelList(map);
                                LogTextBox.WriteLine(string.Format(Text.AddedLevel, levelName));
                            }
                        }
                        break;

                    case 1:                                     // Assign Existing Levels
                        LogTextBox.Clear();
                        AssignExistingLevels(map);
                        assignedLevelsList.Clear();
                        LogTextBox.Draw();
                        break;

                    case 2:                                     // Separator
                        break;

                    default:                                     // Level
                        LogTextBox.ClearContent();
                        string selectedLevelName = selection.Text;
                        string currentLevelName  = selectedLevelName + Program.LevelFileExtension;
                        string currentScriptName = selectedLevelName + Program.ScriptFileExtension;
                        string levelSource       = Path.Combine(Program.installedLevelsPath, currentLevelName);
                        string scriptSource      = Path.Combine(Program.installedScriptsPath, currentScriptName);

                        switch (SelectionPrompt.PromptSelection(levelCommands, true))
                        {
                        case 0:                                                 // Rename
                            levelRenameInput.Top = levelList.Top + selection.RowIndex;
                            bool renamed = levelRenameInput.PromptText(new GUI.TextInput.PromptOptions(false, true, false, selectedLevelName));
                            if (renamed)
                            {
                                string newLevelName      = levelRenameInput.Text;
                                string levelDestination  = Path.Combine(Program.installedLevelsPath, newLevelName + Program.LevelFileExtension);
                                string scriptDestination = Path.Combine(Program.installedScriptsPath, newLevelName + Program.ScriptFileExtension);
                                if (File.Exists(levelDestination) || File.Exists((scriptDestination)))
                                {
                                    LogTextBox.WriteLine(string.Format(Text.LevelOrScriptAlreadyExists, newLevelName + Program.LevelFileExtension, newLevelName + Program.ScriptFileExtension));
                                }
                                else
                                {
                                    try {
                                        map.RenameLevel(selectedLevelName, newLevelName);
                                        File.Move(levelSource, levelDestination);
                                        File.Move(scriptSource, scriptDestination);
                                        Program.SaveInstalledMaps();
                                        RefreshLevelList(map);
                                    } catch (Exception e) {
                                        LogTextBox.WriteLine(string.Format(Text.ErrorWithMessage, e.Message));
                                        if (File.Exists(levelDestination))
                                        {
                                            LogTextBox.WriteLine(string.Format(Text.RevertLevelRename, currentLevelName));
                                            File.Move(levelDestination, levelSource);
                                            LogTextBox.AppendLastLine(Text.Renamed);
                                        }
                                        if (File.Exists(scriptDestination))
                                        {
                                            LogTextBox.WriteLine(string.Format(Text.RevertScriptRename, currentScriptName));
                                            File.Move(scriptDestination, scriptSource);
                                            LogTextBox.AppendLastLine(Text.Renamed);
                                        }
                                    }
                                }
                            }
                            break;

                        case 1:                                                 // Delete
                            LogTextBox.WriteLine(string.Format(Text.ConfirmDelete, currentLevelName, currentScriptName));
                            LogTextBox.WriteLine(Text.AreYouSureYouWantToContinue);
                            LogTextBox.WriteLine(Text.UnassignInsteadOfDelteInstructions);
                            int confirmation = SelectionPrompt.PromptSelection(confirmDeleteCommands, new GUI.SelectionPrompt.Options()
                            {
                                AllowCancel = true, Index = 1
                            });
                            if (confirmation == 0)                                                       // Confirmed deletion
                            {
                                try {
                                    LogTextBox.ClearContent();
                                    map.RemoveLevel(selectedLevelName);
                                    Program.SaveInstalledMaps();
                                    LogTextBox.WriteLine(string.Format(Text.Deleting, currentLevelName));
                                    File.Delete(levelSource);
                                    LogTextBox.AppendLastLine(Text.Deleted);
                                    LogTextBox.WriteLine(string.Format(Text.Deleting, currentScriptName));
                                    File.Delete(scriptSource);
                                    LogTextBox.AppendLastLine(Text.Deleted);
                                } catch (Exception e) {
                                    LogTextBox.WriteLine(string.Format(Text.ErrorWithMessage, e.Message));
                                }
                                RefreshLevelList(map);
                            }
                            break;
                        }
                        break;
                    }

                    levelList.SelectCurrentItem();
                    break;

                case Properties.Command.Cancel:
                    quitPrompt = true;
                    break;
                }
            }
        }
Exemplo n.º 22
0
        public override void Selected(GUI.Selection selection)
        {
            selection.SelectedItem.Highlight();

            if (selection.ColumnIndex == 0)               // Installed Maps -> Uninstall
            {
                var selectedMap = Program.installedMaps[selection.RowIndex];
                LogTextBox.ClearContent();
                string[] selections;
                var      options = new GUI.SelectionPrompt.Options()
                {
                    AllowCancel = true,
                };
                if (selectedMap.IsValid)
                {
                    selections = new string[] { Text.Uninstall };
                }
                else
                {
                    selections    = new string[] { Text.Uninstall, Text.ShowIssues };
                    options.Index = 1;
                }
                int response = SelectionPrompt.PromptSelection(selections, options);
                switch (response)
                {
                case 0:
                    if (selectedMap.IsWIP)
                    {
                        LogTextBox.WriteLine(Text.CantUninstallWIP);
                        ignoreNextSelectionChangedEvent = true;
                    }
                    else
                    {
                        var currentRow = Menu.CurrentRow;
                        UninstallMap(selectedMap);
                        bool keepIgnoringSelectionChanged = ignoreNextSelectionChangedEvent;
                        if (InstalledMapsList.CanNavigate)
                        {
                            InstalledMapsList.Select(currentRow);
                        }
                        else
                        {
                            Menu.NavigateToDefault();
                        }
                        ignoreNextSelectionChangedEvent = keepIgnoringSelectionChanged;
                    }
                    break;

                case 1:
                    selectedMap.ShowIssues();
                    DrawAll();
                    break;
                }
            }
            else if (selection.ColumnIndex == 1)                 // Available Maps -> Install/Reinstall/Overwrite
            {
                var selectedLoadableMap = Program.availableMaps[selection.RowIndex];
                var alreadyInstalledMap = FindInstalledMap(selectedLoadableMap.Name);
                if (alreadyInstalledMap != null)                   // If the map is already installed
                {
                    LogTextBox.ClearContent();
                    LogTextBox.WriteLine(string.Format(Text.PromptReinstall, alreadyInstalledMap.Name));
                    string[] selections;
                    var      options = new GUI.SelectionPrompt.Options()
                    {
                        AllowCancel = true,
                    };
                    if (selectedLoadableMap.IsValid)
                    {
                        selections = new string[] { Text.Reinstall };
                    }
                    else
                    {
                        selections    = new string[] { Text.Reinstall, Text.ShowIssues };
                        options.Index = 1;
                    }
                    int response = SelectionPrompt.PromptSelection(selections, options);
                    switch (response)
                    {
                    case 0:
                        ReinstallMap(alreadyInstalledMap, selectedLoadableMap);
                        break;

                    case 1:
                        selectedLoadableMap.ShowIssues();
                        DrawAll();
                        break;

                    default:
                        LogTextBox.WriteShortMapInfo(selectedLoadableMap);
                        break;
                    }
                }
                else if (VerifyNothingOverwritten(selectedLoadableMap))
                {
                    LogTextBox.ClearContent();
                    string[] selections;
                    var      options = new GUI.SelectionPrompt.Options()
                    {
                        AllowCancel = true,
                    };
                    if (selectedLoadableMap.IsValid)
                    {
                        selections = new string[] { Text.Install };
                    }
                    else
                    {
                        selections    = new string[] { Text.Install, Text.ShowIssues };
                        options.Index = 1;
                    }
                    int response = SelectionPrompt.PromptSelection(selections, options);
                    switch (response)
                    {
                    case 0:
                        InstallMap(selectedLoadableMap, false);
                        break;

                    case 1:
                        selectedLoadableMap.ShowIssues();
                        DrawAll();
                        break;

                    default:
                        LogTextBox.WriteShortMapInfo(selectedLoadableMap);
                        break;
                    }
                }
            }
            selection.List.Select(selection.RowIndex);
        }
Exemplo n.º 23
0
        private bool VerifyNothingOverwritten(LoadableMap map)
        {
            // Check which files already exist
            var existingLevels = new List <string>();

            foreach (var level in map.Levels)
            {
                string correspondingLevel = Path.Combine(Program.installedLevelsPath, level);
                if (File.Exists(correspondingLevel))
                {
                    existingLevels.Add(level);
                }
            }
            var existingScripts = new List <string>();

            foreach (var script in map.Scripts)
            {
                string correspondingScript = Path.Combine(Program.installedScriptsPath, script);
                if (File.Exists(correspondingScript))
                {
                    existingScripts.Add(script);
                }
            }
            if (existingLevels.Count > 0 || existingScripts.Count > 0)
            {
                LogTextBox.ClearContent();
                LogTextBox.WriteLine("Map is not marked as installed, but one or more files already exist. Overwrite?");
                LogTextBox.WriteLine(string.Format("Levels: {0}", string.Join(',', existingLevels.ToArray())));
                LogTextBox.WriteLine(string.Format("Scripts: {0}", string.Join(',', existingLevels.ToArray())));
                string[] selections;
                GUI.SelectionPrompt.Options options;
                if (map.IsValid)
                {
                    selections = new string[] { Text.Overwrite, Text.BackupAndInstall };
                    options    = new GUI.SelectionPrompt.Options()
                    {
                        AllowCancel = true,
                        Index       = 2,
                    };
                }
                else
                {
                    selections = new string[] { Text.Overwrite, Text.BackupAndInstall, Text.ShowIssues };
                    options    = new GUI.SelectionPrompt.Options()
                    {
                        AllowCancel = true,
                        Index       = 3,
                    };
                }
                int response = SelectionPrompt.PromptSelection(selections, options);
                LogTextBox.ClearContent();
                switch (response)
                {
                case 0:
                    InstallMap(map, true);
                    break;

                case 1:
                    // TODO: Verify in case backups would be overwritten.
                    LogTextBox.WriteLine(Text.BackingUpFiles);
                    Program.backupsWindow.BackUpInstalledMapFiles(map);
                    LogTextBox.AppendLastLine(" " + Text.BackupFinished);
                    InstallMap(map, true);
                    break;

                default:
                    LogTextBox.WriteShortMapInfo(map);
                    break;
                }

                return(false);
            }
            else
            {
                return(true);
            }
        }
            private (string connectionKey, ISqlConnections sqlConnections) SelectConnectionString(GeneratorConfig config, string csproj)
            {
                var projectDir = Path.GetDirectoryName(csproj);
                var connectionStringOptions = new ConnectionStringOptions();

                foreach (var x in config.Connections.Where(x => !x.ConnectionString.IsEmptyOrNull()))
                {
                    connectionStringOptions[x.Key] = new ConnectionStringEntry
                    {
                        ConnectionString = x.ConnectionString,
                        ProviderName     = x.ProviderName,
                        Dialect          = x.Dialect
                    };
                }

                foreach (var name in config.GetAppSettingsFiles())
                {
                    var path = Path.Combine(projectDir, name);
                    if (File.Exists(name))
                    {
                        var appSettings = JSON.ParseTolerant <AppSettingsFormat>(File.ReadAllText(path).TrimToNull() ?? "{}");
                        if (appSettings.Data != null)
                        {
                            foreach (var data in appSettings.Data)
                            {
                                // not so nice fix for relative paths, e.g. sqlite etc.
                                if (data.Value.ConnectionString.Contains("../../..", StringComparison.Ordinal))
                                {
                                    data.Value.ConnectionString = data.Value
                                                                  .ConnectionString.Replace("../../..", Path.GetDirectoryName(csproj), StringComparison.Ordinal);
                                }
                                else if (data.Value.ConnectionString.Contains(@"..\..\..\", StringComparison.Ordinal))
                                {
                                    data.Value.ConnectionString = data.Value.ConnectionString.Replace(@"..\..\..\",
                                                                                                      Path.GetDirectoryName(csproj), StringComparison.Ordinal);
                                }

                                connectionStringOptions[data.Key] = data.Value;
                            }
                        }
                    }
                }

                if (connectionStringOptions.Count == 0)
                {
                    AnsiConsole.Write(new Markup($"[bold red]No connections in appsettings files or sergen.json![/]"));
                    AnsiConsole.WriteLine();
                    return(null, null);
                }

                var connectionKeys = connectionStringOptions.Keys.OrderBy(x => x).ToArray();

                DbProviderFactories.RegisterFactory("Microsoft.Data.SqlClient",
                                                    Microsoft.Data.SqlClient.SqlClientFactory.Instance);
                DbProviderFactories.RegisterFactory("System.Data.SqlClient",
                                                    Microsoft.Data.SqlClient.SqlClientFactory.Instance);
                DbProviderFactories.RegisterFactory("Microsoft.Data.Sqlite",
                                                    Microsoft.Data.Sqlite.SqliteFactory.Instance);
                DbProviderFactories.RegisterFactory("Npgsql",
                                                    Npgsql.NpgsqlFactory.Instance);
                DbProviderFactories.RegisterFactory("FirebirdSql.Data.FirebirdClient",
                                                    FirebirdSql.Data.FirebirdClient.FirebirdClientFactory.Instance);
                DbProviderFactories.RegisterFactory("MySql.Data.MySqlClient",
                                                    MySqlConnector.MySqlConnectorFactory.Instance);

                var sqlConnections = new DefaultSqlConnections(
                    new DefaultConnectionStrings(connectionStringOptions));

                AnsiConsole.WriteLine();
                var selections = new SelectionPrompt <string>()
                                 .Title("[steelblue1]Available Connections[/]")
                                 .PageSize(10)
                                 .MoreChoicesText("[grey](Move up and down to reveal more connections)[/]")
                                 .AddChoices(connectionKeys);

                return(AnsiConsole.Prompt(selections), sqlConnections);
            }
Exemplo n.º 25
0
        public override void Selected(GUI.Selection selection)
        {
            if (selection.List.IsEmpty)
            {
                return;
            }
            LogTextBox.ClearContent();
            LaunchableMapsList.HighlightCurrentItem();
            Map    map = null;
            string mapName;

            if (selection.RowIndex == 0)
            {
                mapName = Text.MainGame;
            }
            else
            {
                map     = ((GUI.SelectableMap)selection.SelectedItem).Map;
                mapName = map.Name;
            }
            var options = new GUI.SelectionPrompt.Options()
            {
                AllowCancel = true
            };

            if (selection.RowIndex == 0)               // main map
            {
                options.DisabledItems.Add(2);          // Disable "Set Startup Level"
            }
            else
            {
                if (string.IsNullOrEmpty(map.StartupLevel))
                {
                    options.DisabledItems.Add(1);                     // Disable "New Game"
                }
                if (!Program.saveManagerWindow.MapHasSave(map))
                {
                    options.DisabledItems.Add(0);                     // Disable "Continue"
                }
            }
            int response = SelectionPrompt.PromptSelection(
                new string[] { Text.Continue, Text.NewGame, Text.SetStartupLevel },
                options);

            switch (response)
            {
            case 0:                     // Continue
                try {
                    if (Program.manageSaves &&
                        Program.saveManagerWindow.GetCurrentSavedMapName() != mapName)
                    {
                        LogTextBox.WriteLine(Text.PreparingSaveFile);
                        Program.saveManagerWindow.SwapSaves(mapName);
                    }
                    LaunchGame(null);
                } catch (Exception e) {
                    LogTextBox.WriteLine(string.Format(Text.ErrorWithMessage, e.Message));
                }
                break;

            case 1:                     // New Game
                try {
                    if (Program.manageSaves)
                    {
                        LogTextBox.WriteLine(Text.BackingUpCurrentSave);
                        Program.saveManagerWindow.BackupCurrentSave();
                        Program.saveManagerWindow.SetCurrentSave(mapName);
                    }
                    LaunchGame((selection.RowIndex == 0) ? null : map);
                } catch (Exception e) {
                    LogTextBox.WriteLine(string.Format(Text.ErrorWithMessage, e.Message));
                }
                break;

            case 2:                     // Set Startup Level
                SetStartupLevel(map);
                DetailsTextBox.WriteLongMapInfo(map);
                break;
            }
            LaunchableMapsList.SelectCurrentItem();
        }
        public virtual ICollection <string> PromptForArgumentValues(
            CommandContext ctx, IArgument argument, out bool isCancellationRequested)
        {
            isCancellationRequested = false;

            var argumentName = _getPromptTextCallback?.Invoke(ctx, argument) ?? argument.Name;
            var promptText   = $"{argumentName} ({argument.TypeInfo.DisplayName})";
            var isPassword   = argument.TypeInfo.UnderlyingType == typeof(Password);
            var defaultValue = argument.Default?.Value;

            var ansiConsole = ctx.Services.GetOrThrow <IAnsiConsole>();

            // https://spectreconsole.net/prompts/

            if (argument.Arity.AllowsMany())
            {
                if (argument.AllowedValues.Any())
                {
                    // TODO: how to show default? is it the first choice?

                    var p = new MultiSelectionPrompt <string>
                    {
                        MoreChoicesText  = Resources.A.Selection_paging_instructions(argument.Name),
                        InstructionsText = Resources.A.MultiSelection_selection_instructions(argument.Name)
                    }
                    .Title(promptText)
                    .AddChoices(argument.AllowedValues)
                    .PageSize(_pageSize);

                    return(ansiConsole.Prompt(p));
                }
                else
                {
                    return(MultiPrompt(ansiConsole, promptText));
                }
            }
            else
            {
                if (argument.TypeInfo.Type == typeof(bool))
                {
                    var result = defaultValue != null
                        ? ansiConsole.Confirm(promptText, (bool)defaultValue)
                        : ansiConsole.Confirm(promptText);

                    return(new[] { result.ToString() });
                }
                if (argument.AllowedValues.Any())
                {
                    var p = new SelectionPrompt <string>()
                    {
                        Title           = promptText,
                        PageSize        = _pageSize,
                        MoreChoicesText = Resources.A.Selection_paging_instructions(argument.Name)
                    }
                    .AddChoices(argument.AllowedValues);

                    // TODO: how to show default? is it the first choice?

                    return(new [] { ansiConsole.Prompt(p) });
                }
                else
                {
                    var p = new TextPrompt <string>(promptText)
                    {
                        IsSecret         = isPassword,
                        AllowEmpty       = argument.Arity.RequiresNone(),
                        ShowDefaultValue = true
                    };
                    if (defaultValue != null)
                    {
                        p.DefaultValue(defaultValue.ToString() !);
                    }
                    return(new[] { ansiConsole.Prompt(p) });
                }
            }
        }