Exemplo n.º 1
0
        public static unsafe int ExecuteGOACommand(IntPtr clientData, IntPtr interp, int objc, IntPtr *argv)
        {
            string command = TclAPI.GetCsString(argv[0]);

            for (int i = 1; i < objc; i++)
            {
                command += " " + TclAPI.GetCsString(argv[i]);
            }
            command += ";";

            CommandStringParser parser = new CommandStringParser(command);

            foreach (string cmdstr in parser.Parse())
            {
                bool valid = parser.ParseCommand(cmdstr, true, out Command cmd, out string errorDescr);
                if (valid)
                {
                    CommandExecuter.Instance.Execute(cmd);
                    Objects.CommandStackManager.Instance.Execute();
                    if (Program.mainInterpreter.context != null)
                    {
                        Program.mainInterpreter.context.Invalidate();
                    }
                }
                else
                {
                    MessageBox.Show("Could not parse command " + Environment.NewLine + cmdstr + Environment.NewLine + "Error: " + errorDescr, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return(1);
                }
            }

            return(0);
        }
        protected void UserDefinedAction(object sender, EventArgs e)
        {
            CommandStringParser parser = new CommandStringParser(Command);
            bool cmdFound = false;

            foreach (string subComd in parser.Parse())
            {
                cmdFound = true;
                Command cmd = null;
                string  errorDescr;
                bool    valid = parser.ParseCommand(subComd, true, out cmd, out errorDescr);
                if (valid)
                {
                    CommandExecuter.Instance.Execute(cmd);
                }
                else
                {
                    MessageBox.Show(errorDescr + " when parsing " + Command, "Error during command parsing", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }

            if (!cmdFound && !string.IsNullOrEmpty(Command))
            {
                MessageBox.Show("Could not extract a command from " + Command + ". Missing semicolon after the last command?", "No commands executed", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        /// <summary>
        /// Start the shell and run until exit command
        /// </summary>
        public void Run()
        {
            Console.WriteLine("GoAhead shell mode. Enter your command:");
            Console.Write(">");

            string cmdString = "";

            while (true)
            {
                ConsoleKeyInfo info = Console.ReadKey();

                if (info.Key.Equals(ConsoleKey.Enter))
                {
                    // clear command for command trace
                    Console.WriteLine("");
                    // remove trailing ;
                    cmdString = cmdString.Replace(";", "");
                    Command             cmd;
                    string              errorDescr;
                    CommandStringParser parser = new CommandStringParser(cmdString);
                    bool valid = parser.ParseCommand(cmdString, true, out cmd, out errorDescr);

                    if (valid)
                    {
                        CommandExecuter.Instance.Execute(cmd);
                        CommandStackManager.Instance.Execute();

                        // new line printed by CommandExecuter already
                        Console.Write(">");
                        cmdString = "";
                    }
                    else
                    {
                        Console.WriteLine(errorDescr);
                        Console.Write(">");
                        cmdString = "";
                    }
                }
                else if (info.Key.Equals(ConsoleKey.Backspace))
                {
                    if (cmdString.Length > 0)
                    {
                        cmdString = cmdString.Substring(0, cmdString.Length - 1);
                    }
                }
                else if (info.Key.Equals(ConsoleKey.Escape))
                {
                    Console.WriteLine("");
                    Console.Write(">");
                    cmdString = "";
                }
                else
                {
                    cmdString += info.KeyChar;

                    //Console.Write(info.KeyChar);
                }
            }
        }
Exemplo n.º 4
0
        private void UpdateParameters(string cmdTag)
        {
            // clear previous data
            m_dataGrdArguments.Columns.Clear();
            m_dataGrdArguments.Columns.Add("Name", "Name");
            m_dataGrdArguments.Columns.Add("Value", "Value");
            m_dataGrdArguments.Columns.Add("Type", "Type");

            m_dataGrdArguments.Columns[0].ReadOnly = true;
            // the user will edit this column
            m_dataGrdArguments.Columns[1].ReadOnly = false;
            m_dataGrdArguments.Columns[2].ReadOnly = true;

            m_dataGrdArguments.Rows.Clear();

            // clear action text, otherwise the previos text would remain in case the selected command provides no action
            m_txtAction.Text = "";

            Type type = CommandStringParser.GetAllCommandTypes().FirstOrDefault(t => t.Name.ToString().Equals(cmdTag));

            if (type == null)
            {
                return;
            }

            // create instance to get default value
            Command cmd = (Command)Activator.CreateInstance(type);

            // do not show unpublished commands
            if (!cmd.PublishCommand)
            {
                return;
            }

            // print command action to text box
            m_txtAction.Text = cmd.GetCommandDescription();

            // arguments
            foreach (FieldInfo fi in type.GetFields())
            {
                foreach (object obj in fi.GetCustomAttributes(true).Where(o => o is Parameter))
                {
                    Parameter pf = (Parameter)obj;
                    // skip e.g. Profile
                    if (pf.PrintParameter)
                    {
                        // argument name, default value, type
                        m_dataGrdArguments.Rows.Add(fi.Name, fi.GetValue(cmd), fi.FieldType.Name);
                        int index = m_dataGrdArguments.Rows.Count - 2;
                        if (index < m_dataGrdArguments.Rows.Count)
                        {
                            m_dataGrdArguments.Rows[index].Cells[0].ToolTipText = pf.Comment;
                            m_dataGrdArguments.Rows[index].Cells[1].ToolTipText = pf.Comment;
                            m_dataGrdArguments.Rows[index].Cells[2].ToolTipText = pf.Comment;
                        }
                    }
                }
            }
        }
        public void Parse_CommandString_ParsedCommandNameZeroArgs()
        {
            var parsedCommand = CommandStringParser.Parse("command");

            Assert.That(parsedCommand, Is.Not.Null);
            Assert.That(parsedCommand.Name, Is.EqualTo("command"));
            Assert.That(parsedCommand.Arguments, Is.Empty);
        }
        public void Parse_CommandString_ParsedCommandNameCorrectArgs()
        {
            var parsedCommand = CommandStringParser.Parse("command Arg0 Arg1");

            Assert.That(parsedCommand, Is.Not.Null);
            Assert.That(parsedCommand.Name, Is.EqualTo("command"));
            Assert.That(parsedCommand.Arguments, Is.EqualTo(new[] { "Arg0", "Arg1" }));
        }
Exemplo n.º 7
0
        void handle(string commandMessage)
        {
            var msg         = CommandMessage.New(commandMessage);
            var command     = new CommandStringParser().GetArgumentString(msg.Arguments.ToArray());
            var fullCommand = msg.Command + " " + command;

            handle(new MessageArgs(Guid.Empty, fullCommand.Trim()));
        }
Exemplo n.º 8
0
        public void AddToCommandTrace(Command cmd)
        {
            CommandStringParser parser = new CommandStringParser("");

            bool valid = parser.SplitCommand(cmd.ToString(), out string cmdTag, out string argumentPart);

            int offset = m_txtCommandTrace.TextLength;

            string cmdString = cmd.ToString() + Environment.NewLine;

            // dump command
            m_txtCommandTrace.AppendText(cmdString);

            if (!valid)
            {
                return;
            }

            // color command name red
            m_txtCommandTrace.Select(offset, offset + cmdTag.Length);
            m_txtCommandTrace.SelectionColor = Color.Red;

            // let offset point right behind the command
            offset += cmdTag.Length;

            // color argument names blue and argument values black
            if (!string.IsNullOrEmpty(argumentPart))
            {
                foreach (NameValuePair nameValuePair in parser.GetNameValuePairs(argumentPart))
                {
                    m_txtCommandTrace.Select(offset + nameValuePair.NameFrom, offset + nameValuePair.NameTo);
                    m_txtCommandTrace.SelectionColor = Color.Blue;

                    m_txtCommandTrace.Select(offset + nameValuePair.ValueFrom, offset + nameValuePair.ValueTo);
                    m_txtCommandTrace.SelectionColor = Color.Black;
                }
            }
            m_txtCommandTrace.DeselectAll();
            m_txtCommandTrace.ScrollToCaret();
            return;

            /*
             * int index = 0;
             * while (index < cmdString.Length && cmdString[index] != ' ' && cmdString[index] != ';')
             * {
             *  index++;
             * }
             * this.m_txtCommandTrace.Select(offset, offset + index);
             * this.m_txtCommandTrace.SelectionColor = Color.Red;
             *
             * this.m_txtCommandTrace.Select(offset + index, this.m_txtCommandTrace.TextLength);
             * this.m_txtCommandTrace.SelectionColor = Color.Blue;
             * this.m_txtCommandTrace.DeselectAll();
             * this.m_txtCommandTrace.ScrollToCaret();*/
        }
Exemplo n.º 9
0
        public void Run(int portNumber)
        {
            TcpListener serverSocket = new TcpListener(portNumber);
            TcpClient   clientSocket = default(TcpClient);

            serverSocket.Start();
            Console.WriteLine(">> GoAhead Command Server Started");
            clientSocket = serverSocket.AcceptTcpClient();

            CommandStringParser parser = new CommandStringParser("");

            while ((true))
            {
                try
                {
                    NetworkStream networkStream = clientSocket.GetStream();
                    byte[]        bytesFrom     = new byte[10025];
                    networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);

                    string dataFromClient = Encoding.ASCII.GetString(bytesFrom);
                    dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf('$'));
                    string[] atoms = dataFromClient.Split(';');

                    foreach (string commandString in atoms.Where(s => !string.IsNullOrEmpty(s)))
                    {
                        string  errorDescription = "";
                        Command cmd = null;

                        bool valid = parser.ParseCommand(commandString, true, out cmd, out errorDescription);
                        if (valid)
                        {
                            CommandExecuter.Instance.Execute(cmd);
                            byte[] sendBytes = Encoding.ASCII.GetBytes("result=" + cmd.OutputManager.GetOutput() + "$");
                            networkStream.Write(sendBytes, 0, sendBytes.Length);
                            networkStream.Flush();
                        }
                        else
                        {
                            byte[] sendBytes = Encoding.ASCII.GetBytes(errorDescription);
                            networkStream.Write(sendBytes, 0, sendBytes.Length);
                            networkStream.Flush();
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                    break;
                }
            }

            clientSocket.Close();
            serverSocket.Stop();
            Console.ReadLine();
        }
Exemplo n.º 10
0
        public void AddAlias(string aliasName, string commands)
        {
            bool nameConflict = CommandStringParser.GetAllCommandTypes().Where(t => t.Name.Equals(aliasName)).Any();

            if (nameConflict)
            {
                throw new ArgumentException(aliasName + " is an invalid alias name as it overwrites an existing command name");
            }

            m_aliases[aliasName] = commands;
        }
Exemplo n.º 11
0
        protected override void DoCommandAction()
        {
            FileStream fs = File.OpenRead(OverlayScript);

            byte[] byteBuffer = new byte[fs.Length];
            int    length     = Convert.ToInt32(fs.Length);

            fs.Read(byteBuffer, 0, length);
            fs.Close();

            CommandExecuter.Instance.MuteCommandTrace = true;

            CommandStringParser parser = new CommandStringParser(byteBuffer, length);

            TextWriter sl    = new StreamWriter(SearchLoad, false);
            TextWriter fence = new StreamWriter(Fence, false);

            foreach (string cmdString in parser.Parse())
            {
                Command resolvedCommand = null;
                string  errorDescr;

                bool valid = parser.ParseCommand(cmdString, true, out resolvedCommand, out errorDescr);

                if (resolvedCommand is Set)
                {
                    CommandExecuter.Instance.Execute(resolvedCommand);

                    Set    setCmd = (Set)resolvedCommand;
                    string value  = setCmd.Value;
                    if (Objects.IdentifierManager.Instance.IsMatch(value, Objects.IdentifierManager.RegexTypes.CLB))
                    {
                        AddToSelectionLoc addCmd = new AddToSelectionLoc();
                        addCmd.Location = value;
                        fence.WriteLine(addCmd.ToString());
                    }
                }
                else if (resolvedCommand is PathSearchOnFPGA)
                {
                    CommandExecuter.Instance.MuteCommandTrace = false;
                    PathSearchOnFPGA searchCmd = (PathSearchOnFPGA)resolvedCommand;
                    //String from
                    //this.OutputManager.WriteOutput(searchCmd.StartLocation + "." + searchCmd.StartPort + "-" + searchCmd.TargetLocation + "." + searchCmd.TargetPort);
                    sl.WriteLine(searchCmd.StartLocation + "." + searchCmd.StartPort + "-" + searchCmd.TargetLocation + "." + searchCmd.TargetPort);
                }
                else
                {
                }
            }

            sl.Close();
            fence.Close();
        }
        public override void CommandTrace(Command cmd)
        {
            string output = cmd.ToString();

            if (!CommandExecuter.Instance.ColorOutput)
            {
                Console.WriteLine(output);
            }
            else
            {
                int index = 0;
                // print command name in red
                Console.ForegroundColor = ConsoleColor.Red;
                while (index < output.Length && output[index] != ' ' && output[index] != ';')
                {
                    Console.Write(output[index]);
                    index++;
                }
                Console.ResetColor();
                // print blank
                Console.Write(output[index++]);

                string argumentPart = cmd.ToString();
                argumentPart = argumentPart.Substring(index, argumentPart.Length - index);

                CommandStringParser parser = new CommandStringParser("");

                foreach (NameValuePair nameValuePair in parser.GetNameValuePairs(argumentPart))
                {
                    // next command starts
                    Console.ForegroundColor = ConsoleColor.Cyan;
                    for (int i = 0; i < nameValuePair.Name.Length; i++)
                    {
                        Console.Write(output[index++]);
                    }
                    Console.ResetColor();
                    Console.Write(output[index++]);
                    for (int i = 0; i < nameValuePair.Value.Length; i++)
                    {
                        Console.Write(output[index++]);
                    }
                    if (index < output.Length)
                    {
                        Console.Write(output[index++]);
                    }
                }
                Console.WriteLine("");
                // restore console color for next output (after end of program)
                Console.ResetColor();
                return;
            }
        }
Exemplo n.º 13
0
        private void userSelect(MessageArgs message, Editor editor)
        {
            var state = new ConfigReader(_endpoint.Token).Get("oi.userselect.ui.fallback");

            if (state == "disabled")
            {
                return;
            }
            _ctx.Post((s) =>
            {
                try {
                    var args  = new CommandStringParser().Parse(message.Message).ToArray();
                    var items = new List <string>();
                    var keys  = new List <string>();
                    foreach (var item in args[3].Split(new[] { ',' }))
                    {
                        var chunks = item.Split(new[] { "||" }, StringSplitOptions.None);
                        if (chunks.Length > 1)
                        {
                            keys.Add(chunks[0]);
                            items.Add(chunks[1]);
                        }
                        else
                        {
                            keys.Add(item);
                            items.Add(item);
                        }
                    }
                    var command = "user-selected";
                    if (message.Message.StartsWith("user-select-at-caret "))
                    {
                        command = "user-selected-at-caret";
                    }
                    var form = new UserSelectForm(items, keys, (item) => {
                        if (item != null)
                        {
                            _endpoint.PublishEvent(command + " '" + args[2] + "' '" + item + "'");
                        }
                        else
                        {
                            _endpoint.PublishEvent(command + " '" + args[2] + "' 'user-cancelled'");
                        }
                        editor.SetFocus();
                    });
                    form.Show(this);
                    setToForeground(form);
                } catch {
                }
            }, null);
        }
Exemplo n.º 14
0
 public void Execute(string[] arguments)
 {
     using (var instance = _codeEngineFactory.GetInstance(Environment.CurrentDirectory)) {
         if (instance == null)
         {
             return;
         }
         var args = "";
         if (arguments.Length == 1)
         {
             args = arguments[0];
         }
         else
         {
             args = new CommandStringParser().GetArgumentString(arguments);
         }
         run(instance, args);
     }
 }
Exemplo n.º 15
0
        private void ShowToolTipAfterTimerFired(object sender, EventArgs e)
        {
            if (StoredPreferences.Instance.ShowToolTips)
            {
                Point p = (Point)m_timer.Tag;

                // only show a new tool tip, if the position changes
                if (m_lastToolTipLocation.Equals(p))
                {
                    return;
                }

                m_lastToolTipLocation = p;

                int cmdIndex = GetCommandIndex(p);
                if (cmdIndex == -1)
                {
                    return;
                }

                int from   = m_commandIndeces[cmdIndex].Item1;
                int length = m_commandIndeces[cmdIndex].Item2 - m_commandIndeces[cmdIndex].Item1;

                string commandString = m_txtCmds.Text.Substring(from, length);

                Command             cmd = null;
                string              errorDescription = "";
                CommandStringParser parser           = new CommandStringParser(commandString);
                bool valid = parser.ParseCommand(commandString, false, out cmd, out errorDescription);
                if (valid)
                {
                    // print command action to text box
                    foreach (Attribute attr in Attribute.GetCustomAttributes(cmd.GetType()).Where(a => a is CommandDescription))
                    {
                        CommandDescription descr   = (CommandDescription)attr;
                        string             toolTip = descr.Description;

                        m_toolTip.Show(toolTip, this, p.X, p.Y + 20, 10000);
                        break;
                    }
                }
            }
        }
Exemplo n.º 16
0
 private void CommandInterfaceCtrl_Load(object sender, EventArgs e)
 {
     m_cmdBoxCommands.Items.Clear();
     foreach (Type t in CommandStringParser.GetAllCommandTypes())
     {
         bool publish = true;
         foreach (Attribute attr in Attribute.GetCustomAttributes(t))
         {
             if (attr is CommandDescription)
             {
                 CommandDescription descr = (CommandDescription)attr;
                 publish = descr.Publish;
             }
         }
         if (!publish)
         {
             continue;
         }
         m_cmdBoxCommands.Items.Add(t.Name);
     }
 }
Exemplo n.º 17
0
        private void userInput(MessageArgs message, Editor editor)
        {
            Logger.Write("Getting state for userinput fallback");
            var state = new ConfigReader(_endpoint.Token).Get("oi.userinput.ui.fallback");

            Logger.Write("State is " + state);
            if (state == "disabled")
            {
                return;
            }
            _ctx.Post((s) =>
            {
                Logger.Write("Launching user input form");
                try {
                    var args         = new CommandStringParser().Parse(message.Message).ToArray();
                    var defaultValue = "";
                    if (args.Length > 3)
                    {
                        defaultValue = args[3];
                    }
                    var form = new UserInputForm(defaultValue, (item) => {
                        if (item != null)
                        {
                            _endpoint.PublishEvent("user-inputted '" + args[2] + "' '" + item + "'");
                        }
                        else
                        {
                            _endpoint.PublishEvent("user-inputted '" + args[2] + "' 'user-cancelled'");
                        }
                        editor.SetFocus();
                    });
                    form.Show(this);
                    setToForeground(form);
                } catch (Exception ex) {
                    Logger.Write(ex);
                }
            }, null);
        }
Exemplo n.º 18
0
        /// <summary>
        /// handle user cmds
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void m_txtInputTrace_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Return)
            {
                try
                {
                    CommandStringParser parser = new CommandStringParser(m_txtInput.Text);
                    foreach (string cmdString in parser.Parse())
                    {
                        Command cmd;
                        string  errorDescr;
                        bool    valid = parser.ParseCommand(cmdString, true, out cmd, out errorDescr);
                        if (valid)
                        {
                            CommandExecuter.Instance.Execute(cmd);
                        }
                        else
                        {
                            MessageBox.Show("Could not parse command " + Environment.NewLine + cmdString + Environment.NewLine + "Error: " + errorDescr, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }

                        // update shell
                        Objects.CommandStackManager.Instance.Execute();

                        if (Parent != null)
                        {
                            Parent.Invalidate();
                        }
                    }
                }
                catch (Exception error)
                {
                    MessageBox.Show(error.Message, "Error", MessageBoxButtons.OK);
                }
                m_txtInput.Clear();
            }
        }
Exemplo n.º 19
0
        private void parseLine(string line)
        {
            var check = line
                        .Replace(" ", "")
                        .Replace("\t", "");
            var space = line.IndexOf("=");

            if (check.StartsWith("//"))
            {
                return;
            }
            if (space == -1)
            {
                return;
            }
            space += 1;

            if (check.StartsWith(DEFAULT_EDITOR_SETTING))
            {
                DefaultEditor = line.Substring(space, line.Length - space).Trim();
            }
            if (check.StartsWith(DEFAULT_LANGUAGE_SETTING))
            {
                DefaultLanguage = line.Substring(space, line.Length - space).Trim();
            }
            if (check.StartsWith(ENABLED_LANGUAGES_SETTING))
            {
                EnabledLanguages =
                    new CommandStringParser(',')
                    .Parse(line
                           .Substring(space, line.Length - space).Trim()).ToArray();
            }
            if (check.StartsWith("editor."))
            {
                _editorSettings.Add(check.Trim(new[] { ' ', '\t' }));
            }
        }
Exemplo n.º 20
0
        public string[] Parse(string[] args)
        {
            var newArgs = new List <string>();

            foreach (var arg in args)
            {
                if (arg.StartsWith(DEFAULT_LANGUAGE))
                {
                    DefaultLanguage = arg
                                      .Substring(DEFAULT_LANGUAGE.Length, arg.Length - DEFAULT_LANGUAGE.Length);
                    continue;
                }
                else if (arg.StartsWith(ENABLED_LANGUAGES))
                {
                    EnabledLanguages =
                        new CommandStringParser(',')
                        .Parse(arg
                               .Substring(
                                   ENABLED_LANGUAGES.Length,
                                   arg.Length - ENABLED_LANGUAGES.Length)).ToArray();
                    continue;
                }
                else if (arg == ENABLE_LOGGING)
                {
                    LoggingEnabled = true;
                    continue;
                }
                else if (arg == RAW_OUTPUT)
                {
                    RawOutput = true;
                    continue;
                }

                newArgs.Add(arg);
            }
            return(newArgs.ToArray());
        }
Exemplo n.º 21
0
 public void Setup()
 {
     _parser = new CommandStringParser();
 }
Exemplo n.º 22
0
        private void ReloadScript()
        {
            string scriptFile = m_lblScriptFiled.Text;

            if (!File.Exists(scriptFile))
            {
                MessageBox.Show("Script file not found", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            m_txtCmds.Clear();
            m_txtLineNumber.Clear();
            m_commandIndeces.Clear();
            m_commandIndex = 0;
            m_form         = 0;
            m_length       = 0;
            m_lblCmd.Text  = "No command selected";

            // copy file into text box
            StreamReader sr   = new StreamReader(scriptFile);
            string       line = "";

            int lineCount = 0;

            while ((line = sr.ReadLine()) != null)
            {
                m_txtCmds.AppendText(line + Environment.NewLine);
                m_txtLineNumber.AppendText((lineCount + 1).ToString() + Environment.NewLine);
                lineCount++;
            }
            sr.Close();

            m_context = new CommandExecutionContext();

            CommandStringParser parser = new CommandStringParser(m_txtCmds.Text);

            foreach (string cmdStr in parser.Parse())
            {
                Command cmd;
                string  errorDescr;
                bool    valid = parser.ParseCommand(cmdStr, false, out cmd, out errorDescr);
                if (valid)
                {
                    m_context.Parsed(cmdStr, cmd);
                }
                else
                {
                    MessageBox.Show(errorDescr + Environment.NewLine + parser.State.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
            }
            m_context.SetLabels();

            foreach (Tuple <int, int> range in parser.Topology.GetBorders(CommandStringTopology.TopologyType.Comment))
            {
                m_txtCmds.Select(range.Item1, (range.Item2 - range.Item1) + 1);
                m_txtCmds.SelectionColor = Color.Green;
            }
            foreach (Tuple <int, int> range in parser.Topology.GetBorders(CommandStringTopology.TopologyType.CommandTag))
            {
                m_txtCmds.Select(range.Item1, (range.Item2 - range.Item1) + 1);
                m_txtCmds.SelectionColor = Color.Red;
            }
            foreach (Tuple <int, int> range in parser.Topology.GetBorders(CommandStringTopology.TopologyType.ArgumentNames))
            {
                m_txtCmds.Select(range.Item1, (range.Item2 - range.Item1) + 1);
                m_txtCmds.SelectionColor = Color.Blue;
            }
            foreach (Tuple <int, int> range in parser.Topology.GetBorders(CommandStringTopology.TopologyType.ArgumentValues))
            {
                m_txtCmds.Select(range.Item1, (range.Item2 - range.Item1) + 1);
                m_txtCmds.SelectionColor = Color.Black;
            }
            foreach (Tuple <int, int> range in parser.Topology.GetBorders(CommandStringTopology.TopologyType.CompleteCommand))
            {
                m_commandIndeces.Add(new Tuple <int, int>(range.Item1, range.Item2));
            }

            SetSelectedItemToNextCommandListView();
        }
        public void Parse_NullCommandString_ArgumentNullException()
        {
            var ex = Assert.Throws <ArgumentNullException>(() => CommandStringParser.Parse(null));

            Assert.That(ex.ParamName, Is.EqualTo(ParseCommandStringParam));
        }
Exemplo n.º 24
0
        private void dispatchAndCompleteMessage(string command, Action onCommandCompleted)
        {
            Logger.Write("Dispatching " + command);
            if (command.Length == 0)
            {
                Console.WriteLine();
            }
            else if (isError(command))
            {
                printError(command);
            }
            else if (isWarning(command))
            {
                printWarning(command);
            }
            else if (isColorized(command))
            {
                printColorized(command);
            }
            else if (isCommand(command) || isEvent(command))
            {
                lock (_commandProcessLock) {
                    _commandsInProcessing++;
                }
                ThreadPool.QueueUserWorkItem((m) => {
                    Logger.Write("Handling command in background thread");
                    if (isCommand(command))
                    {
                        Logger.Write("Handling as command");
                        var prefix = getCommandPrefix(command);
                        var parser = new CommandStringParser();
                        var args   =
                            parser.Parse(
                                command.Substring(prefix.Length, command.Length - prefix.Length))
                            .ToArray();
                        if (args.Length == 0)
                        {
                            Logger.Write("No commands specified for " + command);
                        }
                        DefinitionCacheItem cmd = null;
                        if (prefix == "command|")
                        {
                            cmd = GetDefinitionBuilder().Get(args);
                        }
                        else if (prefix == "command-builtin|")
                        {
                            cmd = GetDefinitionBuilder().GetBuiltIn(args);
                        }
                        else if (prefix == "command-language|")
                        {
                            cmd = GetDefinitionBuilder().GetLanguage(args);
                        }
                        else if (prefix == "command-languagescript|")
                        {
                            cmd = GetDefinitionBuilder().GetLanguageScript(args);
                        }
                        else if (prefix == "command-script|")
                        {
                            cmd = GetDefinitionBuilder().GetScript(args);
                        }
                        else if (prefix == "command-original|")
                        {
                            cmd = GetDefinitionBuilder().GetOriginal(args);
                        }

                        if (cmd != null)
                        {
                            new CommandRunner(EventDispatcher)
                            .Run(cmd, args);
                        }
                        else
                        {
                            Logger.Write("Could not find handler for " + command);
                        }
                        onCommandCompleted();
                    }
                    else if (isEvent(command))
                    {
                        Logger.Write("Handling as event");
                        var prefix = "event|";
                        EventDispatcher()
                        .Forward(command.Substring(prefix.Length, command.Length - prefix.Length));
                    }
                    lock (_commandProcessLock) {
                        _commandsInProcessing--;
                    }
                }, null);
            }
            else if (command.StartsWith("raw|"))
            {
                var msg = command.Substring(4, command.Length - 4);
                Console.Write(msg);
            }
            else
            {
                Console.WriteLine(command);
            }
        }
Exemplo n.º 25
0
        private static bool handleOiLnk(ref string command, ref string arguments,
                                        string workingDir,
                                        Action <bool, string> onRecievedLine,
                                        KeyValuePair <string, string>[] replacements)
        {
            if (Path.GetExtension(command) != ".oilnk")
            {
                return(false);
            }
            var fileDir = Path.GetDirectoryName(command);
            var args    = new CommandStringParser(' ').Parse(arguments);
            var lnk     = OiLnkReader.Read(File.ReadAllText(command));

            if ((args.Count() == 2 && args.ElementAt(1) == "get-command-definitions") || (args.Count() == 1 && args.ElementAt(0) == "reactive-script-reacts-to"))
            {
                // Run preparer if exists
                if (lnk.Preparer != null)
                {
                    var preparerArgs = new CommandStringParser(' ').Parse(lnk.Preparer);
                    if (preparerArgs.Count() > 0)
                    {
                        var preparerFile      = Path.Combine(fileDir, Path.GetFileNameWithoutExtension(command) + "-files", preparerArgs.ElementAt(0));
                        var preparerArguments = "";
                        if (preparerArgs.Count() > 1)
                        {
                            preparerArguments = new CommandStringParser(' ').GetArgumentString(preparerArgs.Skip(1).ToArray());
                        }
                        Logger.Write("Running preparer: " + preparerFile);
                        if (File.Exists(preparerFile))
                        {
                            string[] errors;
                            var      output = new Process()
                                              .QueryAll(preparerFile, preparerArguments, false, workingDir, out errors);
                            var hasErrors = false;
                            foreach (var line in output)
                            {
                                if (line.StartsWith("error|"))
                                {
                                    onRecievedLine(true, line.Substring(6, line.Length - 6));
                                    hasErrors = true;
                                }
                            }
                            foreach (var line in errors)
                            {
                                if (line.Trim().Length > 0)
                                {
                                    onRecievedLine(true, line);
                                    hasErrors = true;
                                }
                            }
                            if (hasErrors)
                            {
                                return(true);
                            }
                        }
                    }
                }
                else
                {
                    Logger.Write("No preparer registered");
                }
            }

            foreach (var handler in lnk.Handlers)
            {
                if (handler.Matches(args.ToArray()))
                {
                    handler.WriteResponses((line) => onRecievedLine(false, line));
                    return(true);
                }
            }
            if (lnk.LinkCommand == null)
            {
                return(true);
            }

            if (fileDir != null && File.Exists(Path.Combine(fileDir, lnk.LinkCommand)))
            {
                command = Path.Combine(fileDir, lnk.LinkCommand);
            }
            else if (File.Exists(Path.Combine(workingDir, lnk.LinkCommand)))
            {
                command = Path.Combine(workingDir, lnk.LinkCommand);
            }
            else
            {
                command = lnk.LinkCommand;
            }

            // This is a terrible hack, shame on me!!!!!!!
            // If get command definitions don't mess with arguments
            if (
                (args.Count() == 2 && args.ElementAt(1) == "get-command-definitions") ||
                (args.Count() == 1 && args.ElementAt(0) == "reactive-script-reacts-to")
                )
            {
                return(false);
            }

            var originalArguments = arguments;

            foreach (var replacement in replacements)
            {
                originalArguments = originalArguments.Replace(replacement.Key, "");
            }
            arguments =
                lnk.LinkArguments
                .Replace("{args}", originalArguments).Trim();
            return(false);
        }
Exemplo n.º 26
0
        static void Main(string[] args)
        {
            // TCL API init
            //TclAPI.Initialize();
            mainInterpreter = new TclInterpreter();
            unsafe
            {
                ExecuteGOAcmd = TclProcs.ExecuteGOACommand;
                TclDLL.Helper_RegisterProc(mainInterpreter.ptr, "cs", TclProcs.Cs);
                TclDLL.Helper_RegisterProc(mainInterpreter.ptr, "cshelp", TclProcs.CsHelp);
                TclDLL.Helper_RegisterProc(mainInterpreter.ptr, "cslist", TclProcs.CsList);
                TclDLL.Helper_RegisterProc(mainInterpreter.ptr, "clear", TclProcs.Clear);
                TclDLL.Helper_RegisterProc(mainInterpreter.ptr, "clearcontext", TclProcs.ClearContext);
                //TclDLL.Helper_RegisterProc(mainInterpreter.ptr, "test", TclProcs.Test);
            }
            //int rc = mainInterpreter.EvalScript("puts [testproc Tile]");
            //Console.WriteLine("rc=" + rc + " Interp.Result = " + mainInterpreter.Result);

            // restore settings
            StoredPreferences.LoadPrefernces();

            // check vars
            StringBuilder errorList;

            if (!EnvChecker.CheckEnv(out errorList))
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(errorList.ToString());
                Console.ResetColor();
            }

            // detect commands without default constructor
            foreach (Type type in CommandStringParser.GetAllCommandTypes())
            {
                try
                {
                    Command cmd = (Command)Activator.CreateInstance(type);
                    TclDLL.Helper_RegisterProc(mainInterpreter.ptr, type.Name, ExecuteGOAcmd);
                    unsafe
                    {
                        //string[] parts = cmd.ToString().Split(' ');
                        //if (parts[0].EndsWith(";")) parts[0] = parts[0].Substring(0, parts[0].Length - 1);
                        TclDLL.Helper_RegisterProc(mainInterpreter.ptr, type.Name, ExecuteGOAcmd);
                    }
                }
                catch (Exception)
                {
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    Console.WriteLine("Warning: No default constructor found for command " + type.Name);
                    Console.ResetColor();
                }
            }



            // register console hook
            // first hook print progress to clean the % output
            CommandExecuter.Instance.AddHook(new PrintProgressToConsoleHook());
            // the profiling hook must be added before the output hook hooks as it produces output
            CommandExecuter.Instance.AddHook(new ProfilingHook());
            CommandExecuter.Instance.AddHook(new ConsoleCommandHook());
            CommandExecuter.Instance.AddHook(new PrintOutputHook());

            // check if init.goa is found in binary of the current assembly
            string dir      = AssemblyDirectory;
            string initFile = dir + Path.DirectorySeparatorChar + "init.goa";

            // if so, execute init.goa
            if (File.Exists(initFile))
            {
                RunScript runInitCmd = new RunScript();
                runInitCmd.FileName = initFile;
                CommandExecuter.Instance.Execute(runInitCmd);
                //FileInfo fi = new FileInfo(initFile);
                //CommandExecuter.Instance.Execute(fi);
            }
            else
            {
                Console.WriteLine("GoAhead did not find the init file: " + initFile);
            }

            bool   showGUIOnly = false;
            bool   execScript  = false;
            string scriptFile  = "";
            bool   shellMode   = false;
            bool   serverMode  = false;
            int    portNumber  = 0;
            bool   commandMode = false;

            if (args.Length == 0)
            {
                showGUIOnly = true;
            }
            else
            {
                int i = 0;
                while (i < args.Length)
                {
                    switch (args[i])
                    {
                    case "-gui":
                        showGUIOnly = true;
                        break;

                    case "-exec":
                        execScript = true;
                        scriptFile = GetScriptFileName(args, i + 1);
                        i++;
                        break;

                    case "-shell":
                        shellMode = true;
                        break;

                    case "-command":
                    case "-commands":
                        commandMode = true;
                        break;

                    case "-server":
                        portNumber = int.Parse(args[i + 1]);
                        i++;
                        break;

                    default:
                        if (args[i].EndsWith(".goa") && File.Exists(args[i]))
                        {
                            execScript = true;
                            scriptFile = GetScriptFileName(args, i);
                        }
                        break;
                    }
                    i++;
                }
            }
            if (showGUIOnly)
            {
                // open gui
                CommandExecuter.Instance.Execute(new Commands.GUI.ShowGUI());
            }
            else if (execScript)
            {
                if (!File.Exists(scriptFile))
                {
                    string errorMessage = "Error: File " + scriptFile + " not found";
                    // allow the test scripts to catch this string (goahead -exec script.goa | tee.goa)
                    Console.WriteLine(errorMessage);
                    throw new ArgumentException(errorMessage);
                }

                // command file mode
                FileInfo fi = new FileInfo(scriptFile);
                CommandExecuter.Instance.Execute(fi);
            }
            else if (shellMode)
            {
                Objects.CommandShell shell = new Objects.CommandShell();
                shell.Run();
            }
            else if (serverMode)
            {
                Objects.CommandServer server = new Objects.CommandServer();
                server.Run(portNumber);
            }
            else if (commandMode)
            {
                string cmdString = "";
                if (args.Length > 1)
                {
                    for (int i = 1; i < args.Length; i++)
                    {
                        cmdString += args[i] + " ";
                    }
                }
                if (string.IsNullOrEmpty(cmdString))
                {
                    Console.WriteLine("GoAhead was started with -commands, but no command was given");
                }
                Command             cmd;
                string              errorDescr;
                CommandStringParser parser = new CommandStringParser(cmdString);
                foreach (string subCommandString in parser.Parse())
                {
                    bool valid = parser.ParseCommand(subCommandString, true, out cmd, out errorDescr);
                    if (!valid)
                    {
                        Console.WriteLine(errorDescr);
                    }
                    CommandExecuter.Instance.Execute(cmd);
                }
            }
            else
            {
                Console.WriteLine("No switch found. Start GoAhead with one of the following options:");
                Console.WriteLine("GoAhead -gui             : Open GoAhead in GUI-Mode");
                Console.WriteLine("GoAhead -exec script.goa : Execute script.goa");
                Console.WriteLine("GoAhead script.goa       : Execute script.goa");
                Console.WriteLine("GoAhead -shell           : Start GoAhead shell (interactive Command mode)");
                Console.WriteLine("GoAhead -command(s)      : Execute GoAhead commands (e.g GoAhead -command \"FixS6XDLBug XDLInFile=in.xdl XDLOutFile=out.xdl;\"");
            }

            // save settings
            StoredPreferences.SavePrefernces();
        }