public virtual void SetupCommand(IShellCommand cmd)
 {
     if (cmd != null)
     {
         commands[cmd.Name] = cmd;
     }
 }
Exemple #2
0
        private static void InvokeTestOptions(Shell shell, IShellCommand shellCommand, string[] args)
        {
            var prefixes = new[] { "--", "-", "/" };

            var optionsArgs = args
                .TakeWhile(x => prefixes.Any(p => x.StartsWith(p) && x.Length > p.Length))
                .ToList();

            var parser = new OptionSet();

            var options = (dynamic)new ExpandoObject();
            options.Verbosity = 0;

            parser
                .Add("c|config=", "Set config path", s => { if (!string.IsNullOrWhiteSpace(s)) options.ConfigPath = s; })
                .Add("v|verbose", "increase verbosity level", s => { if (s != null) options.Verbosity++; });

            var arguments = new List<string>(parser.Parse(optionsArgs));
            arguments.AddRange(args.Skip(optionsArgs.Count));

            options.Arguments = arguments;

            Console.WriteLine("Options:");
            Console.WriteLine(JsonConvert.SerializeObject(options, Formatting.Indented));
        }
Exemple #3
0
 public virtual Shell AddCommand(IShellCommand command)
 {
     lock (_lock)
     {
         _container.AddCommand(command);
     }
     return(this);
 }
        public void AddCommand(IShellCommand command)
        {
            if (command == null) throw new ArgumentNullException(nameof(command));

            TreeAdd(command);

            _commandsDescriptions.Add(command.Pattern, command.Description);
        }
        public void AddCommand(IShellCommand command)
        {
            if (command == null)
            {
                throw new ArgumentNullException(nameof(command));
            }

            TreeAdd(command);

            _commandsDescriptions.Add(command.Pattern, command.Description);
        }
Exemple #6
0
        public void RunShell()
        {
            _readline = new Readline.Readline(History)
            {
                CtrlCInterrupts = CtrlCInterrupts,
                CtrlDIsEOF      = CtrlDIsEOF,
                CtrlZIsEOF      = CtrlZIsEOF
            };

            _readline.WritePrompt       += ReadlineOnWritePrompt;
            _readline.Interrupt         += (sender, args) => ShellInterrupt?.Invoke(this, EventArgs.Empty);
            _readline.TabComplete       += ReadlineOnTabComplete;
            _readline.PrintAlternatives += (sender, args) => OnPrintAlternatives(args);

            while (true)
            {
                var input = _readline.ReadLine();

                if (string.IsNullOrWhiteSpace(input))
                {
                    continue;
                }

                input = input.Trim();


                var allTokens = ShellCommandTokenizer.Tokenize(input);

                foreach (var cmdTokens in allTokens)
                {
                    try
                    {
                        var tokenArr = cmdTokens.ToArray();

                        IShellCommand command = null;
                        lock (_lock)
                        {
                            command = _container.FindCommand(this, tokenArr);
                        }

                        BeforeCommandExecute?.Invoke(this, new CommandExecuteEventArgs(input, null, command));
                        ExecuteCommand(tokenArr);
                        AfterCommandExecute?.Invoke(this, new CommandExecuteEventArgs(input, CommandResult, command));
                    }
                    catch (ShellCommandNotFoundException)
                    {
                        OnShellCommandNotFound(input);
                    }
                }

                History.AddUnique(input);
            }
        }
        private void TreeAdd(IShellCommand command)
        {
            var tokens = new Queue <string>(ShellCommandTokenizer.Tokenize(command.Pattern));

            var treeLevel = _commandsTree;

            while (tokens.Any())
            {
                var token = tokens.Dequeue();

                object leaf;
                treeLevel.TryGetValue(token, out leaf);

                if (tokens.Count == 0)
                {
                    if (leaf == null)
                    {
                        leaf = command;
                        treeLevel.Add(token, leaf);
                    }

                    if (leaf != command)
                    {
                        throw new NotSupportedException("Already have handler for command");
                    }
                }
                else
                {
                    if (leaf == null)
                    {
                        leaf = new SortedDictionary <string, object>(StringComparer.OrdinalIgnoreCase);
                        treeLevel.Add(token, leaf);
                    }

                    treeLevel = leaf as SortedDictionary <string, object>;

                    if (treeLevel == null)
                    {
                        throw new InvalidOperationException("Tree leaf must be Dictionary");
                    }
                }
            }
        }
Exemple #8
0
        private static void InvokeTestOptions(Shell shell, IShellCommand shellCommand, string[] args)
        {
            var prefixes = new[] { "--", "-", "/" };

            var optionsArgs = args
                              .TakeWhile(x => prefixes.Any(p => x.StartsWith(p) && x.Length > p.Length))
                              .ToList();

            var parser = new OptionSet();

            var options = (dynamic) new ExpandoObject();

            options.Verbosity = 0;

            parser
            .Add("c|config=", "Set config path", s => { if (!string.IsNullOrWhiteSpace(s))
                                                        {
                                                            options.ConfigPath = s;
                                                        }
                 })
            .Add("v|verbose", "increase verbosity level", s => { if (s != null)
                                                                 {
                                                                     options.Verbosity++;
                                                                 }
                 });


            var arguments = new List <string>(parser.Parse(optionsArgs));

            arguments.AddRange(args.Skip(optionsArgs.Count));

            options.Arguments = arguments;

            Console.WriteLine("Options:");
            Console.WriteLine(JsonConvert.SerializeObject(options, Formatting.Indented));
        }
 private static object DetermineImageSourceForCommand(IShellCommand shellCommand, ImageStates imageState)
 {
     PlaceholderCommand command = shellCommand as PlaceholderCommand;
     if (command != null)
     {
         return GetIconUriForMethod(command.ScreenMethodName, shellCommand, imageState);
     }
     if (shellCommand == null)
     {
         return null;
     }
     IScreenCommand executableObject = shellCommand.ExecutableObject as IScreenCommand;
     if (executableObject != null)
     {
         return GetIconUriForMethod(executableObject.GetModel().Name, shellCommand, imageState);
     }
     if (shellCommand.Group == ShellCommandGroupNames.Customize)
     {
         return GetIconUriForMethod("CustomizeScreen", shellCommand, imageState);
     }
     if (shellCommand.Image == null)
     {
         return GetIconUriForMethod("Placeholder", shellCommand, imageState);
     }
     return shellCommand.Image;
 }
 public override void ExecuteCommand(IShellCommand command)
 {
 }
Exemple #11
0
        /// <summary>
        /// Executes the command.
        /// Searches the command with its command key on the internal command collection.
        /// Cross checks the result command by verifying its argument count.
        /// Then executes the command.
        /// </summary>
        /// <param name="commandKey">The command key</param>
        /// <param name="parameters">The parameters</param>
        /// <returns>Boolean indicating status of the execution</returns>
        private static async Task <bool> Execute(string commandKey, string[] parameters)
        {
            IShellCommand command = await Init.GetCommandWithKeyAsync <IShellCommand>(commandKey).ConfigureAwait(false);

            if (command == null)
            {
                ShellIO.Error("Command doesn't exist. use 'help' to check all available commands!");
                return(false);
            }

            try {
                if (!command.IsInitSuccess)
                {
                    await command.InitAsync().ConfigureAwait(false);
                }

                if (!command.IsCurrentCommandContext(command.CommandKey, parameters.Length))
                {
                    ShellIO.Error("Command doesn't match the syntax. Please retype.");
                    return(false);
                }

                if (!command.HasParameters && parameters.Length > 0)
                {
                    ShellIO.Info($"'{command.CommandName}' doesn't require any arguments.");

                    string args = string.Empty;
                    for (int i = 0; i < parameters.Length; i++)
                    {
                        if (!string.IsNullOrEmpty(parameters[i]))
                        {
                            args += parameters[i] + ",";
                        }
                    }

                    ShellIO.Info($"Entered arguments '{args}' will be trimmed out.");
                    parameters = new string[0];
                }

                if (parameters.Length > command.MaxParameterCount)
                {
                    ShellIO.Info($"'{command.CommandName}' only supports a maximum of '{command.MaxParameterCount}' arguments. You have entered '{parameters.Length}'");

                    string args = string.Empty;
                    for (int i = (parameters.Length - command.MaxParameterCount) - 1; i > parameters.Length - command.MaxParameterCount; i--)
                    {
                        parameters[i] = null;
                    }

                    ShellIO.Info($"'{parameters.Length - command.MaxParameterCount}' arguments will be trimmed out.");
                    return(false);
                }

                await Notifications.Notify(Notifications.NotificationType.NotifyShort).ConfigureAwait(false);

                await command.ExecuteAsync(new Parameter(commandKey, parameters)).ConfigureAwait(false);

                return(true);
            }
            finally {
                command.Dispose();
            }
        }
 private static void RegisterCommandBuilder(IShellCommand commandBuilder)
 {
     CommandBuilders.Add(commandBuilder.Key.ToUpper(), commandBuilder);
 }
        private void TreeAdd(IShellCommand command)
        {
            var tokens = new Queue<string>(ShellCommandTokenizer.Tokenize(command.Pattern));

            var treeLevel = _commandsTree;
            while (tokens.Any())
            {
                var token = tokens.Dequeue();

                object leaf;
                treeLevel.TryGetValue(token, out leaf);

                if (tokens.Count == 0)
                {
                    if (leaf == null)
                    {
                        leaf = command;
                        treeLevel.Add(token, leaf);
                    }

                    if (leaf != command)
                    {
                        throw new NotSupportedException("Already have handler for command");
                    }
                }
                else
                {
                    if (leaf == null)
                    {
                        leaf = new SortedDictionary<string, object>(StringComparer.OrdinalIgnoreCase);
                        treeLevel.Add(token, leaf);
                    }

                    treeLevel = leaf as SortedDictionary<string, object>;

                    if (treeLevel == null)
                    {
                        throw new InvalidOperationException("Tree leaf must be Dictionary");
                    }
                }
            }
        }
Exemple #14
0
        public async Task ExecuteAsync(Parameter parameter)
        {
            if (!IsInitSuccess)
            {
                return;
            }

            if (parameter.Parameters.Length > MaxParameterCount)
            {
                ShellIO.Error("Too many arguments.");
                return;
            }

            await Sync.WaitAsync().ConfigureAwait(false);

            try {
                if (OnExecuteFunc != null)
                {
                    if (OnExecuteFunc.Invoke(parameter))
                    {
                        return;
                    }
                }

                switch (parameter.ParameterCount)
                {
                case 0:
                    foreach (KeyValuePair <string, IShellCommand> cmd in Interpreter.Commands)
                    {
                        if (string.IsNullOrEmpty(cmd.Value.CommandKey) || string.IsNullOrEmpty(cmd.Value.CommandName))
                        {
                            continue;
                        }

                        cmd.Value.OnHelpExec(true);
                    }
                    return;

                case 1 when !string.IsNullOrEmpty(parameter.Parameters[0]) && parameter.Parameters[0].Equals("all", StringComparison.OrdinalIgnoreCase):
                    PrintAll();
                    return;

                case 1 when !string.IsNullOrEmpty(parameter.Parameters[0]):
                    IShellCommand shellCmd = await Interpreter.Init.GetCommandWithKeyAsync <IShellCommand>(parameter.Parameters[0]).ConfigureAwait(false);

                    if (shellCmd == null)
                    {
                        ShellIO.Error("Command doesn't exist. use ' help -all ' to check all available commands!");
                        return;
                    }

                    shellCmd.OnHelpExec(false);
                    return;

                default:
                    ShellIO.Error("Command seems to be in incorrect syntax.");
                    return;
                }
            }
            catch (Exception e) {
                ShellIO.Exception(e);
                return;
            }
            finally {
                Sync.Release();
            }
        }
Exemple #15
0
 /// <summary>
 /// Executes a command on the context menu.
 /// </summary>
 /// <param name="command"></param>
 public abstract void ExecuteCommand(IShellCommand command);
        private static object GetIconUriForMethod(string methodName, IShellCommand command, ImageStates imageState)
        {
            switch (methodName)
            {
                case "Save":
                    if (imageState == ImageStates.MouseOver)
                    {
                        return IconSaveLargeHover;
                    }
                    if (imageState == ImageStates.SmallMouseOver)
                    {
                        return IconSaveSmallHover;
                    }
                    if ((imageState != ImageStates.Small) && (imageState != ImageStates.SmallDisabled))
                    {
                        return IconSaveLarge;
                    }
                    return IconSaveSmall;

                case "Refresh":
                    if (imageState == ImageStates.MouseOver)
                    {
                        return IconRefreshLargeHover;
                    }
                    if (imageState == ImageStates.SmallMouseOver)
                    {
                        return IconRefreshSmallHover;
                    }
                    if ((imageState != ImageStates.Small) && (imageState != ImageStates.SmallDisabled))
                    {
                        return IconRefreshLarge;
                    }
                    return IconRefreshSmall;

                case "CustomizeScreen":
                    if (imageState == ImageStates.MouseOver)
                    {
                        return IconCustomizeLargeHover;
                    }
                    if (imageState == ImageStates.SmallMouseOver)
                    {
                        return IconCustomizeSmallHover;
                    }
                    if ((imageState != ImageStates.Small) && (imageState != ImageStates.SmallDisabled))
                    {
                        return IconCustomizeLarge;
                    }
                    return IconCustomizeSmall;
            }
            if (command.Image != null)
            {
                return command.Image;
            }
            if (imageState == ImageStates.MouseOver)
            {
                return IconPlaceholderLargeHover;
            }
            if (imageState == ImageStates.SmallMouseOver)
            {
                return IconPlaceholderSmallHover;
            }
            if ((imageState != ImageStates.Small) && (imageState != ImageStates.SmallDisabled))
            {
                return IconPlaceholderLarge;
            }
            return IconPlaceholderSmall;
        }
Exemple #17
0
 public Shell AddCommand(IShellCommand command)
 {
     lock (_lock)
     {
         _container.AddCommand(command);
     }
     return this;
 }
        //SECTION 2 - Command Button Handling Code
        private void GeneralCommandHandler(object sender, RoutedEventArgs e)
        {
            IShellCommand command = (IShellCommand)((Button)sender).DataContext;

            command.ExecutableObject.ExecuteAsync();
        }
Exemple #19
0
 /// <summary>
 /// Adds a new command to the queue.
 /// </summary>
 /// <param name="command">The command to add to the execution queue.</param>
 public void AddCommand(IShellCommand command)
 {
     CommandQueue.Enqueue(command);
 }
 /// <inheritdoc/>
 public override void ExecuteCommand(IShellCommand command)
 {
     command.Execute(null);
     ClearCommands();
 }
 public CommandExecuteEventArgs(string userInput, object result, IShellCommand cmd = null)
 {
     UserInput = userInput;
     Result    = result;
     Command   = cmd;
 }
 private void RegisterCommand(IShellCommand command)
 {
     shellCommands.Add(command.Key, command);
 }
Exemple #23
0
 private static void Exit(Shell shell, IShellCommand shellCommand, string[] strings)
 {
     throw new ApplicationExitException();
 }
Exemple #24
0
 private static void Exit(Shell shell, IShellCommand shellCommand, string[] strings)
 {
     throw new ApplicationExitException();
 }
 static void RegisterCommand(IShellCommand command)
 {
     Commands.Add(command.Key, command);
 }
 private static void RegsiterCommand(IShellCommand command)
 {
     ShellCommands.Add(command.Key, command);
 }