Exemplo n.º 1
0
        public void EvaluateIfCommandWithFalseAsCondition()
        {
            IExpression condition   = new ConstantExpression(false);
            ICommand    thenCommand = new SetCommand("a", new ConstantExpression(1));
            ICommand    elseCommand = new SetCommand("b", new ConstantExpression(2));

            IfCommand command = new IfCommand(condition, thenCommand, elseCommand);

            BindingEnvironment environment = new BindingEnvironment();

            command.Execute(environment);

            Assert.IsNull(environment.GetValue("a"));
            Assert.AreEqual(2, environment.GetValue("b"));
        }
Exemplo n.º 2
0
        public void ExecuteSimpleForWithContinue()
        {
            ICommand ifcmd  = new IfCommand(new CompareExpression(ComparisonOperator.Equal, new NameExpression("a"), new ConstantExpression(2)), new ContinueCommand());
            ICommand setcmd = new SetCommand("b", new BinaryOperatorExpression(new NameExpression("a"), new NameExpression("b"), BinaryOperator.Add));
            ICommand body   = new CompositeCommand(new ICommand[] { ifcmd, setcmd });

            BindingEnvironment environment = new BindingEnvironment();

            environment.SetValue("b", 0);

            ForCommand command = new ForCommand("a", new ConstantExpression(new object[] { 1, 2, 3 }), body);

            command.Execute(environment);

            Assert.AreEqual(4, environment.GetValue("b"));
        }
Exemplo n.º 3
0
        public void CompileIfCommandWithCompositeThenCommand()
        {
            Parser parser = new Parser("if a:\r\n  print a\r\n  print b");

            ICommand cmd = parser.CompileCommand();

            Assert.IsNotNull(cmd);
            Assert.IsInstanceOfType(cmd, typeof(IfCommand));

            IfCommand ifcmd = (IfCommand)cmd;

            Assert.IsNotNull(ifcmd.Condition);
            Assert.IsInstanceOfType(ifcmd.Condition, typeof(NameExpression));
            Assert.IsNotNull(ifcmd.ThenCommand);
            Assert.IsInstanceOfType(ifcmd.ThenCommand, typeof(CompositeCommand));

            Assert.IsNull(parser.CompileCommand());
        }
Exemplo n.º 4
0
        public void CompileIfCommandWithSingleThenCommandSameLine()
        {
            Parser parser = new Parser("if a: print a");

            ICommand cmd = parser.CompileCommand();

            Assert.IsNotNull(cmd);
            Assert.IsInstanceOfType(cmd, typeof(IfCommand));

            IfCommand ifcmd = (IfCommand)cmd;

            Assert.IsNotNull(ifcmd.Condition);
            Assert.IsInstanceOfType(ifcmd.Condition, typeof(NameExpression));
            Assert.IsNotNull(ifcmd.ThenCommand);
            Assert.IsInstanceOfType(ifcmd.ThenCommand, typeof(PrintCommand));

            Assert.IsNull(parser.CompileCommand());
        }
Exemplo n.º 5
0
        public void ParseIfCommandWithMultipleLineAndElse()
        {
            Parser   parser  = new Parser("if a \r\n b = a\r\n else \r\n b = 1\r\n end");
            ICommand command = parser.ParseCommand();

            Assert.IsNotNull(command);
            Assert.IsInstanceOfType(command, typeof(IfCommand));

            IfCommand ifcommand = (IfCommand)command;

            Assert.IsNotNull(ifcommand.Condition);
            Assert.IsNotNull(ifcommand.ThenCommand);
            Assert.IsNotNull(ifcommand.ElseCommand);

            Assert.IsInstanceOfType(ifcommand.Condition, typeof(VariableExpression));

            Assert.IsNull(parser.ParseCommand());
        }
Exemplo n.º 6
0
        public void ParseIfCommandWithOneLineThen()
        {
            Parser   parser  = new Parser("if a then b = a end");
            ICommand command = parser.ParseCommand();

            Assert.IsNotNull(command);
            Assert.IsInstanceOfType(command, typeof(IfCommand));

            IfCommand ifcommand = (IfCommand)command;

            Assert.IsNotNull(ifcommand.Condition);
            Assert.IsNotNull(ifcommand.ThenCommand);
            Assert.IsNull(ifcommand.ElseCommand);

            Assert.IsInstanceOfType(ifcommand.Condition, typeof(VariableExpression));

            Assert.IsNull(parser.ParseCommand());
        }
Exemplo n.º 7
0
        public void CreateAndEvaluateSimpleWhileCommandWithContinue()
        {
            BindingEnvironment environment = new BindingEnvironment();

            environment.SetValue("a", 1);
            IExpression condition = new CompareExpression(ComparisonOperator.Less, new NameExpression("a"), new ConstantExpression(10));
            ICommand    ifcmd     = new IfCommand(new CompareExpression(ComparisonOperator.Equal, new NameExpression("a"), new ConstantExpression(2)), new ContinueCommand());
            ICommand    setcmd    = new SetCommand("a", new BinaryOperatorExpression(new NameExpression("a"), new ConstantExpression(1), BinaryOperator.Add));
            ICommand    body      = new CompositeCommand(new ICommand[] { setcmd, ifcmd, setcmd });

            WhileCommand command = new WhileCommand(condition, body);

            command.Execute(environment);

            Assert.AreEqual(condition, command.Condition);
            Assert.AreEqual(body, command.Command);
            Assert.AreEqual(10, environment.GetValue("a"));
        }
Exemplo n.º 8
0
        Command parseCommand()
        {
            Command C = null;
            if (CurrentToken == null)
                return null;

            switch (CurrentToken.getType())
            {
                case If:
                    accept(If);
                    Expression E = parseExpression();
                    accept(Then);
                    Command C1 = parseCommand();
                    accept(Else);
                    Command C2 = parseCommand();
                    C = new IfCommand(E, C1, C2);
                    break;

                case Identifier:
                    Identifier I = parseIdentifier();
                    accept(Becomes);
                    Expression E1 = parseExpression();
                    C = new AssignCommand(I, E1);
                    break;

                case Let:
                    accept(Let);
                    Declaration D = parseDeclaration();
                    accept(In);
                    Command C3 = parseCommand();
                    C = new letCommand(D, C3);
                    break;

                default:
                    Console.WriteLine("Syntax Error in Command at token: " + CurrentToken.getSpelling());
                    C = null;
                    break;

            }

            return C;
        }
Exemplo n.º 9
0
        public void IfFalseThen()
        {
            var condition   = new CompareExpression(ComparisonOperator.Less, new VariableExpression("a"), new ConstantExpression(10));
            var thencommand = new SetVariableCommand("k", new ConstantExpression(1));

            var ifcommand = new IfCommand(condition, thencommand);

            Context context = new Context();

            context.SetValue("a", 10);
            context.SetValue("k", 0);

            var result = ifcommand.Execute(context);

            Assert.IsNull(result);
            Assert.IsNotNull(ifcommand.Condition);
            Assert.IsNotNull(ifcommand.ThenCommand);
            Assert.IsNull(ifcommand.ElseCommand);

            Assert.AreEqual(0, context.GetValue("k"));
        }
Exemplo n.º 10
0
        public void ParseAndEvaluateSimpleIfWithCompositeCommand()
        {
            Parser parser = new Parser("if (1) { a = a+1; a = a+2; }");

            ICommand command = parser.ParseCommand();

            Assert.IsNotNull(command);
            Assert.IsInstanceOfType(command, typeof(IfCommand));

            IfCommand ifcmd = (IfCommand)command;

            Assert.IsInstanceOfType(ifcmd.ThenCommand, typeof(CompositeCommand));

            BindingEnvironment environment = new BindingEnvironment();

            environment.SetValue("a", 2);

            command.Execute(environment);

            Assert.AreEqual(5, environment.GetValue("a"));
        }
Exemplo n.º 11
0
        private IfCommand parseIf()
        {
            accept(_if);
            ConditionExpression expression = parseConditionExpression();

            IfCommand ifCommand = new IfCommand(CurrentToken.Line, expression);

            if (accept(_then))
            {
                Command thenCommand = parseCommand();

                ifCommand.ThenCommand = thenCommand;

                if (accept(_else))
                {
                    Command elseCommand = parseCommand();
                    ifCommand.ElseCommand = elseCommand;
                    return(ifCommand);
                }
            }
            return(null);
        }
Exemplo n.º 12
0
        public void ReturnTrueForCanExecuteSinceExecutionWillBeDecidedFromTheCondition()
        {
            var ifCommand = new IfCommand(o => true, null);

            Assert.IsTrue(ifCommand.CanExecute(null));
        }
Exemplo n.º 13
0
        public void NotCauseNullReferenceExceptionIfIfBranchIsNull()
        {
            var ifCommand = new IfCommand(o => true, null);

            Assert.DoesNotThrow(() => ifCommand.Execute(null));
        }
Exemplo n.º 14
0
        public void NotThrowExceptionIfElseCommandIsNull()
        {
            var ifCommand = new IfCommand(o => false, null);

            Assert.DoesNotThrow(() => ifCommand.Execute(null));
        }
Exemplo n.º 15
0
    private void parseBlock(ScriptBlock block)
    {
        StackPosition last             = getTop();
        string        expectedPreSpace = last == null ? null : last.whitespace;
        StackPosition current          = new StackPosition(null, block);

        stackPositions.Push(current);

        int i = 0;

        while (this.hasNext() && i < 10)
        {
            var next = peekNextLine();

            // ignore full whitespace lines
            if (next.hasContent())
            {
                var leadingSpace = next.getLeadingSpace();

                if (current.whitespace == null)
                {
                    if (expectedPreSpace == null ||
                        expectedPreSpace.Length < leadingSpace.Length && leadingSpace.Substring(0, expectedPreSpace.Length) == expectedPreSpace
                        )
                    {
                        current.whitespace = leadingSpace;
                    }
                    else
                    {
                        throw new GameScriptParseError("Expected indentation but none found", currentLine);
                    }
                }

                if (leadingSpace != current.whitespace)
                {
                    if (leadingSpace.Length < current.whitespace.Length && current.whitespace.Substring(0, leadingSpace.Length) == leadingSpace)
                    {
                        break;
                    }
                    else
                    {
                        throw new GameScriptParseError("Bad whitespace", currentLine);
                    }
                }
                else
                {
                    var command = next.getCommand();
                    moveNext();

                    if (command != null)
                    {
                        if (command == "if")
                        {
                            var ifBlock = new ScriptBlock();
                            parseBlock(ifBlock);
                            IfCommand result = new IfCommand(ConditionParser.parseCondition(next.getCommandParameters()), ifBlock);
                            block.addCommand(result);

                            var nextLine = peekNextLine();

                            while (leadingSpace == nextLine.getLeadingSpace() &&
                                   nextLine.getCommand() == "elseif")
                            {
                                moveNext();
                                var nextBlock = new ScriptBlock();
                                parseBlock(nextBlock);
                                var nextIf = new IfCommand(ConditionParser.parseCondition(nextLine.getCommandParameters()), nextBlock);
                                result.setElseBlock(ScriptBlock.singleCommand(nextIf));
                                result   = nextIf;
                                nextLine = peekNextLine();
                            }

                            if (leadingSpace == nextLine.getLeadingSpace() &&
                                nextLine.getCommand() == "else")
                            {
                                moveNext();
                                var elseBlock = new ScriptBlock();
                                parseBlock(elseBlock);
                                result.setElseBlock(elseBlock);
                            }
                        }
                        else if (command == "set")
                        {
                            var parts = next.getCommandParameters().Split(null, 3);

                            if (parts.Length != 3)
                            {
                                throw new GameScriptParseError("set expects 3 parameters", currentLine);
                            }
                            else
                            {
                                var type  = parts[0];
                                var name  = parts[1];
                                var value = parts[2];
                                if (type == "bool")
                                {
                                    block.addCommand(new SetBooleanCommand(name, ConditionParser.parseCondition(value)));
                                }
                                else if (type == "number")
                                {
                                    block.addCommand(new SetNumberCommand(name, ConditionParser.parseNumerValue(value)));
                                }
                                else if (type == "string")
                                {
                                    block.addCommand(new SetStringCommand(name, value));
                                }
                                else
                                {
                                    throw new GameScriptParseError("set expects first parameter to be bool, number, or string", currentLine);
                                }
                            }
                        }
                    }
                    else
                    {
                        block.addCommand(new TextCommand(next.getContent()));
                    }
                }
            }
            else
            {
                moveNext();
            }

            ++i;
        }

        stackPositions.Pop();
    }
Exemplo n.º 16
0
        public void GenerateCodeForInstruction(CodeLine line)
        {
            if (InstructionHelper.IsMoveInstruction(line.instruction))
            {
                var command = new MoveCommand(InstructionHelper.GetInstructionDirection(line.instruction), currentCodeLineNumber + 1);
                commandToCodeLineMapping.Add(command, line);
                allCommands.Add(command);
            }
            if (InstructionHelper.IsPutInstruction(line.instruction))
            {
                var command = new PutCommand(currentCodeLineNumber + 1);
                commandToCodeLineMapping.Add(command, line);
                allCommands.Add(command);
            }
            if (InstructionHelper.IsPickInstruction(line.instruction))
            {
                var command = new PickCommand(currentCodeLineNumber + 1);
                commandToCodeLineMapping.Add(command, line);
                allCommands.Add(command);
            }
            if (InstructionHelper.IsJumpInstruction(line.instruction))
            {
                ICommand command;

                if (InstructionHelper.IsJumpInstructionLabel(line.instruction))
                {
                    command = new JumpCommand(currentCodeLineNumber + 1);
                    allCommands.Add(command);
                }
                else
                {
                    //this is being set in code later - otherwise forward jumps will not work - see RepairJumps for reference.
                    command = new JumpCommand(currentCodeLineNumber + 1);
                    allCommands.Add(command);
                }
                commandToCodeLineMapping.Add(command, line);
            }

            if (InstructionHelper.IsIfInstruction(line.instruction))
            {
                int trueLineNumber = currentCodeLineNumber + 1;
                int elseLineNumber = currentCodeLineNumber + line.TotalChildrenCount + 1;
                var command        = new IfCommand(trueLineNumber, elseLineNumber, GetConditions(line), GetLogicalOperators(line));
                allCommands.Add(command);
                commandToCodeLineMapping.Add(command, line);
                currentCodeLineNumber++;
                foreach (var child in line.children)
                {
                    GenerateCodeForInstruction(child);
                }
                command.NextCommandId = currentCodeLineNumber;
                currentCodeLineNumber--; //this may seem wrong but actually it is not
            }

            if (InstructionHelper.IsWhileInstruction(line.instruction))
            {
                int trueLineNumber  = currentCodeLineNumber + 1;
                int falseLineNumber = currentCodeLineNumber + line.TotalChildrenCount + 1;
                var command         = new WhileCommand(trueLineNumber, falseLineNumber, GetConditions(line), GetLogicalOperators(line));
                allCommands.Add(command);
                commandToCodeLineMapping.Add(command, line);
                currentCodeLineNumber++;
                foreach (var child in line.children)
                {
                    GenerateCodeForInstruction(child);
                }
                var loopJumpCommand = new JumpCommand(trueLineNumber - 1);
                commandToCodeLineMapping.Add(loopJumpCommand, null);
                command.NextCommandId = currentCodeLineNumber + 1;
                allCommands.Add(loopJumpCommand);
            }

            if (InstructionHelper.IsRepeatInstruction(line.instruction))
            {
                int trueLineNumber  = currentCodeLineNumber + 1;
                int falseLineNumber = currentCodeLineNumber + line.TotalChildrenCount + 1;
                var command         = new RepeatCommand(trueLineNumber, falseLineNumber, InstructionHelper.GetRepeatTimes(line.instruction));
                allCommands.Add(command);
                commandToCodeLineMapping.Add(command, line);
                currentCodeLineNumber++;
                foreach (var child in line.children)
                {
                    GenerateCodeForInstruction(child);
                }
                var loopJumpCommand = new JumpCommand(trueLineNumber - 1);
                commandToCodeLineMapping.Add(loopJumpCommand, null);
                command.NextCommandId = currentCodeLineNumber;
                allCommands.Add(loopJumpCommand);
            }

            currentCodeLineNumber++;
        }
Exemplo n.º 17
0
 protected internal override void VisitIfCommand(IfCommand ifCommand)
 {
     this.WriteIndent();
     this.writer.WriteLine("if {0} {1} {2}", ifCommand.Left, this.ToString(ifCommand.Operation), ifCommand.Right);
     this.IncreaseIndent();
 }
Exemplo n.º 18
0
        private static void ProcessCommands(Command[] commands, ref int currentCommandIndex, int depth)
        {
            if (depth > Constants.MaxProcessingStack)
            {
                throw new Exception(Resources.ProcessingStackOverflow);
            }

            if (depth < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(depth));
            }

            while (currentCommandIndex < commands.Length)
            {
                Command currentCommand = commands[currentCommandIndex];

                //Console.WriteLine(currentCommand.Name);

                if (currentCommand.Name.Equals(Constants.StartDefinition))
                {
                    currentCommandIndex++;
                    ParseDefinition(commands, ref currentCommandIndex, false);
                }
                else if (currentCommand.Name.Equals(Constants.RedefineDefinition))
                {
                    currentCommandIndex++;
                    ParseDefinition(commands, ref currentCommandIndex, true);
                }
                else if (currentCommand is IfCommand)
                {
                    IfCommand ifCommand = currentCommand as IfCommand;
                    FInteger  intValue  = new FInteger(BitConverter.ToInt32(Stack.Pop().Bytes, 0));
                    if (intValue.Value == Constants.True)
                    {
                        int ifCommandIndex = 0;
                        ProcessCommands(ifCommand.IfCommands.ToArray(), ref ifCommandIndex, depth + 1);
                    }
                    else
                    {
                        int elseCommandIndex = 0;
                        ProcessCommands(ifCommand.ElseCommands.ToArray(), ref elseCommandIndex, depth + 1);
                    }
                }
                else if (currentCommand.Name.Equals(Constants.Else))
                {
                }
                else if (currentCommand.Name.Equals(Constants.EndIf))
                {
                }
                else if (currentCommand is RepeatCommand)
                {
                    RepeatCommand repeatCommand = currentCommand as RepeatCommand;
                    FInteger      fInteger;
                    do
                    {
                        int repeatCommandIndex = 0;
                        ProcessCommands(repeatCommand.RepeatCommands.ToArray(), ref repeatCommandIndex, depth + 1);
                        fInteger = new FInteger(BitConverter.ToInt32(Stack.Pop().Bytes, 0));
                    } while (fInteger.Value == Constants.False);
                }
                else if (currentCommand.Name.Equals(Constants.Until))
                {
                }
                else if (currentCommand is LoopCommand)
                {
                    LoopCommand loopCommand = currentCommand as LoopCommand;

                    FInteger incrementor  = new FInteger(BitConverter.ToInt32(Stack.Pop().Bytes, 0));
                    FInteger currentValue = new FInteger(BitConverter.ToInt32(Stack.Pop().Bytes, 0));
                    FInteger targetValue  = new FInteger(BitConverter.ToInt32(Stack.Pop().Bytes, 0));

                    while (currentValue.Value != targetValue.Value)
                    {
                        Stack.Push(new Cell(targetValue.GetBytes()));
                        Stack.Push(new Cell(currentValue.GetBytes()));
                        Stack.Push(new Cell(incrementor.GetBytes()));
                        int loopCommandIndex = 0;
                        ProcessCommands(loopCommand.LoopCommands.ToArray(), ref loopCommandIndex, depth + 1);

                        incrementor         = new FInteger(BitConverter.ToInt32(Stack.Pop().Bytes, 0));
                        currentValue        = new FInteger(BitConverter.ToInt32(Stack.Pop().Bytes, 0));
                        targetValue         = new FInteger(BitConverter.ToInt32(Stack.Pop().Bytes, 0));
                        currentValue.Value += incrementor.Value;
                    }
                }
                else if (currentCommand.Name.Equals(Constants.EndLoop))
                {
                }
                else
                {
                    if ((_ioMode == IoModeEnum.Hex) && (IsHexInteger(currentCommand.Name)))
                    {
                        int intValue;

                        if (!int.TryParse(currentCommand.Name, System.Globalization.NumberStyles.HexNumber, null,
                                          out intValue))
                        {
                            throw new Exception(string.Format(Resources.InvalidHexInteger, currentCommand));
                        }

                        FInteger intConstant = new FInteger(intValue);
                        Stack.Push(new Cell(intConstant.GetBytes()));
                    }
                    else if ((_ioMode == IoModeEnum.Decimal) && (IsInteger(currentCommand.Name)))
                    {
                        int intValue;
                        if (!int.TryParse(currentCommand.Name, out intValue))
                        {
                            throw new Exception(string.Format(Resources.InvalidInteger, currentCommand));
                        }

                        FInteger intConstant = new FInteger(intValue);
                        Stack.Push(new Cell(intConstant.GetBytes()));
                    }
                    else
                    {
                        float floatValue;
                        if ((_ioMode == IoModeEnum.Fraction) && (IsFloat(currentCommand.Name)))
                        {
                            if (!float.TryParse(currentCommand.Name, out floatValue))
                            {
                                throw new Exception(string.Format(Resources.InvalidFloat, currentCommand));
                            }

                            FFloat intConstant = new FFloat(floatValue);
                            Stack.Push(new Cell(intConstant.GetBytes()));
                        }
                        else if ((_ioMode == IoModeEnum.Char) && (IsChar(currentCommand.Name)))
                        {
                            string subString = currentCommand.Name.Substring(Constants.StartChar.Length,
                                                                             currentCommand.Name.Length - Constants.EndChar.Length - 1);
                            char ch;
                            if (!char.TryParse(subString, out ch))
                            {
                                throw new Exception(string.Format(Resources.InvalidCharacter, subString));
                            }

                            FInteger intConstant = new FInteger(ch);
                            Stack.Push(new Cell(intConstant.GetBytes()));
                        }
                        else if (IsString(currentCommand.Name))
                        {
                            string subString = currentCommand.Name.Substring(Constants.StartString.Length,
                                                                             currentCommand.Name.Length - Constants.EndString.Length - 2);
                            Console.Write(subString);
                        }
                        else if (IsVariable(currentCommand.Name))
                        {
                            Stack.Push(new Cell(new FInteger(Objects[currentCommand.Name].Item2).GetBytes()));
                        }
                        else if (IsValue(currentCommand.Name))
                        {
                            byte[] bytes = new byte[Constants.CellSize];
                            Array.Copy(Memory, Objects[currentCommand.Name].Item2, bytes, 0, Constants.CellSize);
                            Stack.Push(new Cell(bytes));
                        }
                        else if (IsConstant(currentCommand.Name))
                        {
                            byte[] bytes = new byte[Constants.CellSize];
                            Array.Copy(Memory, Objects[currentCommand.Name].Item2, bytes, 0, Constants.CellSize);
                            Stack.Push(new Cell(bytes));
                        }
                        else if (IsDefinition(currentCommand.Name))
                        {
                            int definitionTokenIndex = 0;
                            ProcessCommands(Definitions[currentCommand.Name].ToArray(), ref definitionTokenIndex, depth + 1);
                        }
                        else if (currentCommand.Name.Equals(Constants.ViewDefinitions))
                        {
                            Console.WriteLine();
                            foreach (string key in Definitions.Keys)
                            {
                                Console.Write(Resources.Executor_ProcessCommands__StartDefinition, Constants.StartDefinition);
                                Console.Write(string.Format(Resources.Executor_ProcessCommands__Key, key).PadRight(18, ' '));
                                foreach (Command command in Definitions[key])
                                {
                                    Console.Write(string.Format("{0} ", command.Name));
                                }

                                Console.WriteLine(string.Format("{0}", Constants.EndDefinition));
                            }
                        }
                        else if (currentCommand.Name.Equals(Constants.ViewObjects))
                        {
                            Console.WriteLine();
                            foreach (string key in Objects.Keys)
                            {
                                Console.Write(string.Format("{0}", key).PadRight(20, ' '));
                                Console.Write(string.Format("{0}\t", Objects[key].Item1));
                                Console.Write(string.Format("{0}\t", Objects[key].Item2));

                                byte[] bytes = FetchFromMemory(new FInteger(Objects[key].Item2));
                                Console.WriteLine(string.Format("{0}", GetOutputValue(bytes)));
                            }
                        }
                        else if (currentCommand.Name.Equals(Constants.Help))
                        {
                            Console.WriteLine();
                            foreach (string command in Constants.ValidCommands)
                            {
                                Console.WriteLine(command);
                            }
                        }
                        else if (currentCommand.Name.Equals(Constants.Variable))
                        {
                            if (currentCommandIndex >= commands.Length - 1)
                            {
                                throw new Exception(Resources.ExpectedAName);
                            }

                            currentCommandIndex++;
                            string variableName = commands[currentCommandIndex].Name;
                            if (IsAlreadyDefined(variableName))
                            {
                                throw new Exception(string.Format(Resources.AlreadyDefined, variableName));
                            }

                            AddObject(variableName, MemoryEntryEnum.Variable);
                        }
                        else if (currentCommand.Name.Equals(Constants.Value))
                        {
                            if (currentCommandIndex >= commands.Length - 1)
                            {
                                throw new Exception(Resources.ExpectedAName);
                            }

                            currentCommandIndex++;
                            string variableName = commands[currentCommandIndex].Name;
                            if (IsAlreadyDefined(variableName))
                            {
                                throw new Exception(string.Format(Resources.AlreadyDefined, variableName));
                            }

                            AddObject(variableName, MemoryEntryEnum.Value, Stack.Pop().Bytes);
                        }
                        else if (currentCommand.Name.Equals(Constants.Constant))
                        {
                            if (currentCommandIndex >= commands.Length - 1)
                            {
                                throw new Exception(Resources.ExpectedAName);
                            }

                            currentCommandIndex++;
                            string variableName = commands[currentCommandIndex].Name;
                            if (IsAlreadyDefined(variableName))
                            {
                                throw new Exception(string.Format(Resources.AlreadyDefined, variableName));
                            }

                            AddObject(variableName, MemoryEntryEnum.Constant, Stack.Pop().Bytes);
                        }
                        else if (currentCommand.Name.Equals(Constants.Store))
                        {
                            FInteger memoryLocation = new FInteger(BitConverter.ToInt32(Stack.Pop().Bytes, 0));
                            FInteger intValue       = new FInteger(BitConverter.ToInt32(Stack.Pop().Bytes, 0));

                            StoreToMemory(intValue, memoryLocation);
                        }
                        else if (currentCommand.Name.Equals(Constants.Fetch))
                        {
                            FInteger memoryLocation = new FInteger(BitConverter.ToInt32(Stack.Pop().Bytes, 0));

                            byte[] bytes = FetchFromMemory(memoryLocation);

                            FInteger intValue = new FInteger(BitConverter.ToInt32(bytes, 0));
                            Stack.Push(new Cell(intValue.GetBytes()));
                        }
                        else if (currentCommand.Name.Equals(Constants.To))
                        {
                            if (currentCommandIndex >= commands.Length - 1)
                            {
                                throw new Exception(Resources.ExpectedAName);
                            }

                            currentCommandIndex++;
                            string valueName = commands[currentCommandIndex].Name;
                            if (!IsValue(valueName))
                            {
                                throw new Exception(string.Format(Resources.NameIsNotAValue, valueName));
                            }

                            SetObject(Objects[valueName].Item2, Stack.Pop().Bytes);
                        }
                        else if (currentCommand.Name.Equals(Constants.Cell))
                        {
                            Stack.Push(new Cell(new FInteger(Constants.CellSize).GetBytes()));
                        }
                        else if (currentCommand.Name.Equals(Constants.Here))
                        {
                            Stack.Push(new Cell(new FInteger(_memoryPointer).GetBytes()));
                        }
                        else if (currentCommand.Name.Equals(Constants.Allot))
                        {
                            FInteger memoryAllocBytes = new FInteger(BitConverter.ToInt32(Stack.Pop().Bytes, 0));
                            if (_memoryPointer + memoryAllocBytes.Value < 0)
                            {
                                throw new Exception(Resources.MemoryUnderflow);
                            }
                            else if (_memoryPointer + memoryAllocBytes.Value > Constants.MemorySize)
                            {
                                throw new Exception(Resources.MemoryOverflow);
                            }

                            _memoryPointer += memoryAllocBytes.Value;
                        }
                        else if (currentCommand.Name.Equals(Constants.Decimal))
                        {
                            _ioMode = IoModeEnum.Decimal;
                        }
                        else if (currentCommand.Name.Equals(Constants.Hex))
                        {
                            _ioMode = IoModeEnum.Hex;
                        }
                        else if (currentCommand.Name.Equals(Constants.Fractional))
                        {
                            _ioMode = IoModeEnum.Fraction;
                        }
                        else if (currentCommand.Name.Equals(Constants.Char))
                        {
                            _ioMode = IoModeEnum.Char;
                        }
                        else if (currentCommand.Name.Equals(Constants.Period))
                        {
                            OutputValue(Stack.Pop().Bytes);
                        }
                        else if (currentCommand.Name.Equals(Constants.Dup))
                        {
                            Stack.Dup();
                        }
                        else if (currentCommand.Name.Equals(Constants.Swap))
                        {
                            Stack.Swap();
                        }
                        else if (currentCommand.Name.Equals(Constants.Drop))
                        {
                            Stack.Drop();
                        }
                        else if (currentCommand.Name.Equals(Constants.Rot))
                        {
                            Stack.Rot();
                        }
                        else if (currentCommand.Name.Equals(Constants.Over))
                        {
                            Stack.Over();
                        }
                        else if (currentCommand.Name.Equals(Constants.Tuck))
                        {
                            Stack.Tuck();
                        }
                        else if (currentCommand.Name.Equals(Constants.Roll))
                        {
                            Stack.Roll();
                        }
                        else if (currentCommand.Name.Equals(Constants.Pick))
                        {
                            Stack.Pick();
                        }
                        else if (currentCommand.Name.Equals(Constants.Cr))
                        {
                            Console.WriteLine();
                        }
                        else if (
                            currentCommand.Name.Equals(Constants.Add) ||
                            currentCommand.Name.Equals(Constants.Subtract) ||
                            currentCommand.Name.Equals(Constants.Multiply) ||
                            currentCommand.Name.Equals(Constants.Modulus) ||
                            currentCommand.Name.Equals(Constants.Divide) ||
                            currentCommand.Name.Equals(Constants.GreaterThan) ||
                            currentCommand.Name.Equals(Constants.LessThan) ||
                            currentCommand.Name.Equals(Constants.GreaterThanOrEqual) ||
                            currentCommand.Name.Equals(Constants.LessThanOrEqual) ||
                            currentCommand.Name.Equals(Constants.Equal) ||
                            currentCommand.Name.Equals(Constants.NotEqual) ||
                            currentCommand.Name.Equals(Constants.And) ||
                            currentCommand.Name.Equals(Constants.Or) ||
                            currentCommand.Name.Equals(Constants.Not)
                            )
                        {
                            if (_ioMode == IoModeEnum.Fraction)
                            {
                                Stack.FloatMaths(currentCommand.Name);
                            }
                            else
                            {
                                Stack.IntMaths(currentCommand.Name);
                            }
                        }
                        else
                        {
                            throw new Exception(string.Format(Resources.UnknownItem, currentCommand.Name));
                        }
                    }
                }

                // Increment to next token
                currentCommandIndex++;
            }
        }
Exemplo n.º 19
0
        /// <summary>
        /// Read .tgpa files outside TGPA Game class
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        public static Map BuildMapFromTGPAFile(String file, Vector2 screenResolution)
        {
            Map map = new Map();

            StreamReader reader = new StreamReader(TitleContainer.OpenStream(file));

            String line = reader.ReadLine();

            while (line.Equals("") || line.StartsWith("//"))
            {
                line = reader.ReadLine();
            }

            //Check version
            //try
            //{
            //    if (Convert.ToDouble((line.Split(' '))[1]) > Convert.ToDouble(TheGreatPaperGame.version))
            //    {
            //        reader.Close();
            //        throw new Exception("Insupported game version.");
            //    }
            //}
            //catch (FormatException) { throw new Exception("Invalid game version : " + line); } //Bullshit

            map.GameVersion = TheGreatPaperGame.Version;

            line = reader.ReadLine();
            while (line.Equals("") || line.StartsWith("//"))
            {
                line = reader.ReadLine();
            }

            //Map informations
            #region Map Infos

            try
            {
                map.Level = Convert.ToInt32((line.Split(' '))[1]);
            }
            catch (FormatException) { reader.Close(); throw new Exception("Invalid map level number : " + line); }

            line = reader.ReadLine();
            while (line.Equals("") || line.StartsWith("//"))
            {
                line = reader.ReadLine();
            }

            try
            {
                map.lastPart = Convert.ToBoolean(line.Replace("lastpart ", ""));
            }
            catch (FormatException) { reader.Close(); throw new Exception("Invalid map level lastpart : " + line); }

            line = reader.ReadLine();
            while (line.Equals("") || line.StartsWith("//"))
            {
                line = reader.ReadLine();
            }

            map.Name = LocalizedStrings.GetString(line.Replace("name ", ""));

            line = reader.ReadLine();
            while (line.Equals("") || line.StartsWith("//"))
            {
                line = reader.ReadLine();
            }

            String filedesc = line.Replace("desc ", "");
            map.Description = LocalizedStrings.GetString(filedesc);

            #endregion

            line = reader.ReadLine();
            while (line.Equals("") || line.StartsWith("//"))
            {
                line = reader.ReadLine();
            }

            //Backgrounds
            #region Backgrounds

            for (int i = 1; i < 4; i++)
            {
                ScrollingBackground bg = null;

                if (i == 1)
                {
                    bg = map.Background1;
                }
                else if (i == 2)
                {
                    bg = map.Background2;
                }
                else if (i == 3)
                {
                    bg = map.Background3;
                }


                string[] tokens = line.Split(' ');

                ScrollDirection direction = ScrollDirection.Left;

                try
                {
                    direction = ScrollingBackground.String2ScrollDirection(tokens[1]);
                }
                catch (Exception e)
                {
                    Logger.Log(LogLevel.Error, "TGPA Exception : " + e.Message);
                }

                bool inf = false;
                try
                {
                    inf = Convert.ToBoolean(tokens[4]);
                }
                catch (FormatException) { reader.Close(); throw new Exception("Invalid boolean for Infinite scroll : " + line); }

                Vector2 speed = Vector2.Zero;
                try
                {
                    speed = new Vector2(Convert.ToInt32(tokens[2]), Convert.ToInt32(tokens[3]));
                }
                catch (FormatException) { reader.Close(); throw new Exception("Invalid Vector for scroll speed : " + line); }

                bg = new ScrollingBackground(direction, speed, inf);

                //Parts
                while ((line = reader.ReadLine()).Split(' ')[0].Equals("bgpart"))
                {
                    Logger.Log(LogLevel.Info, "BG Found  " + line.Split(' ')[1]);

                    bg.AddBackground(line.Split(' ')[1]);
                }

                if (bg.BackgroundSprites.Count == 0)
                {
                    reader.Close(); throw new Exception("No BGPart found for Background " + i);
                }

                if (i == 1)
                {
                    map.Background1 = bg;
                }
                else if (i == 2)
                {
                    map.Background2 = bg;
                }
                else if (i == 3)
                {
                    map.Background3 = bg;
                }

                line = reader.ReadLine();
                while (line.Equals("") || line.StartsWith("//"))
                {
                    line = reader.ReadLine();
                }
            }

            #endregion

            //Initialization
            #region Init

            if (!line.Split(' ')[0].Equals("init"))
            {
                reader.Close();
                throw new Exception("Invalid TGPA map : init section not found");
            }

            line = reader.ReadLine();
            while (line.Equals("") || line.StartsWith("//"))
            {
                line = reader.ReadLine();
            }

            //level music
            string[] tokens2 = line.Split('\"');
            if (tokens2.Length < 4)
            {
                Console.WriteLine("No music loaded");
            }
            else
            {
                map.Music = new MySong(tokens2[0].Split(' ')[1], tokens2[1], tokens2[3]);
            }
            line = reader.ReadLine();
            while (line.Equals("") || line.StartsWith("//"))
            {
                line = reader.ReadLine();
            }

            //Initial datas
            try
            {
                map.InitialScore = Convert.ToInt32(line.Split(' ')[1]);
            }
            catch (FormatException) { reader.Close(); throw new Exception("Invalid integer for score : " + line); }

            line = reader.ReadLine();
            while (line.Equals("") || line.StartsWith("//"))
            {
                line = reader.ReadLine();
            }

            try
            {
                map.InitialLivesCount = Convert.ToInt32(line.Split(' ')[1]);
            }
            catch (FormatException) { reader.Close(); throw new Exception("Invalid integer for lives : " + line); }

            line = reader.ReadLine();
            while (line.Equals("") || line.StartsWith("//"))
            {
                line = reader.ReadLine();
            }

            string weaponName = line.Split(' ')[1];
            map.InitialWeapon = Weapon.TypeToWeapon(weaponName);

            line = reader.ReadLine();
            while (line.Equals("") || line.StartsWith("//"))
            {
                line = reader.ReadLine();
            }

            //Initial loc
            Vector2 initialPlayerLoc = new Vector2(Convert.ToInt32(line.Split(' ')[1]), Convert.ToInt32(line.Split(' ')[2]));
            map.InitialPlayerLocation = initialPlayerLoc;

            line = reader.ReadLine();
            while (line.Equals("") || line.StartsWith("//"))
            {
                line = reader.ReadLine();
            }

            //Initial flip
            string        sFlip = line.Split(' ')[1];
            SpriteEffects flip  = SpriteEffects.None;

            if (sFlip.Equals(SpriteEffects.FlipHorizontally.ToString()))
            {
                flip = SpriteEffects.FlipHorizontally;
            }
            else if (sFlip.Equals(SpriteEffects.FlipVertically.ToString()))
            {
                flip = SpriteEffects.FlipVertically;
            }

            map.InitialFlip = flip;

            line = reader.ReadLine();
            while (line.Equals("") || line.StartsWith("//"))
            {
                line = reader.ReadLine();
            }

            //End conditions
            Event  endmap  = new Event(Vector2.Zero, null);
            String winflag = line.Split(' ')[1];
            line = reader.ReadLine();
            String loseflag = line.Split(' ')[1];
            endmap.AddCommand(new EndLevelCommand(winflag, loseflag));

            map.Events.Add(endmap);

            line = reader.ReadLine();
            while (line.Equals("") || line.StartsWith("//"))
            {
                line = reader.ReadLine();
            }

            ScrollDirection outDirection = ScrollingBackground.String2ScrollDirection(line.Split(' ')[1]);
            map.OutDirection = outDirection;

            #endregion

            //Script
            #region Script event

            line = reader.ReadLine();
            while (line.Equals("") || line.StartsWith("//"))
            {
                line = reader.ReadLine();
            }

            if (!line.Split(' ')[0].Equals("begin"))
            {
                reader.Close();
                throw new Exception("Invalid TGPA map : begin keyword not found");
            }

            line = reader.ReadLine();
            while (line.Equals("") || line.StartsWith("//"))
            {
                line = reader.ReadLine();
            }

            //Read all events
            while (!line.Split(' ')[0].Equals("end"))
            {
                tokens2 = line.Split(' ');

                if (!tokens2[0].Equals("event"))
                {
                    reader.Close();
                    throw new Exception("Invalid TGPA map : event section missing (line : " + line + ")");
                }

                Vector2 vector = Vector2.Zero;
                try
                {
                    vector = new Vector2((float)Convert.ToDouble(tokens2[2]), (float)Convert.ToDouble(tokens2[3]));
                }
                catch (FormatException) { reader.Close(); throw new Exception("Invalid Vector for event scroll value : " + line); }

                line    = reader.ReadLine();
                tokens2 = line.Split(' ');
                if (!tokens2[0].Equals("start"))
                {
                    reader.Close();
                    throw new Exception("Invalid TGPA map : start keyword missing");
                }

                String    startFlag = null;
                IfCommand ifc       = null;

                try
                {
                    startFlag = line.Split(' ')[1];
                    if (!startFlag.Equals(""))
                    {
                        ifc = new IfCommand(startFlag);
                    }
                }
                catch (IndexOutOfRangeException) { }

                Event e = new Event(vector, ifc);

                line = reader.ReadLine();
                while (line.Equals("") || line.StartsWith("//"))
                {
                    line = reader.ReadLine();
                }

                List <Command> commands = new List <Command>();

                //Add actions
                while (!line.Split(' ')[0].Equals("endevent"))
                {
                    Command c = null;

                    switch (line.Split(' ')[0])
                    {
                    case "addenemy":
                        c = new AddEnemyCommand(line, screenResolution);

                        AddEnemyRessourcesToLoadIfNecessary(map, (AddEnemyCommand)c);

                        break;

                    case "addbge":
                        c = new AddBackgroundElementCommand(line, screenResolution);
                        AddBGERessourcesToLoadIfNecessary(map, (AddBackgroundElementCommand)c);
                        break;

                    case "if":
                        c = new IfCommand(line);
                        break;

                    case "set":
                        c = new SetFlagCommand(line, true);
                        break;

                    case "unset":
                        c = new UnsetFlagCommand(line, true);
                        break;

                    case "whilenot":
                        c = new WhileNotCommand(line);

                        line = reader.ReadLine();
                        while (line.Equals("") || line.StartsWith("//"))
                        {
                            line = reader.ReadLine();
                        }

                        List <String> lines = new List <String>();
                        while (!line.Split(' ')[0].Equals("done"))
                        {
                            if (line.Split(' ')[0].Equals("addenemy"))
                            {
                                AddEnemyRessourcesToLoadIfNecessary(map, new AddEnemyCommand(line, screenResolution));
                            }
                            lines.Add(line);

                            line = reader.ReadLine();
                            while (line.Equals("") || line.StartsWith("//"))
                            {
                                line = reader.ReadLine();
                            }
                        }

                        ((WhileNotCommand)c).AddCommands(lines);

                        break;

                    case "scrollspeedreset":
                        c = new ResetScrollingSpeedCommand(line);
                        break;

                    case "scrollspeed":
                        c = new NewScrollingSpeedCommand(line);
                        break;

                    case "changemusic":
                        c = new ChangeMusicCommand(line);

                        map.MusicRessourcesToLoad.Add(((ChangeMusicCommand)c).Song);

                        break;

                    case "autogen":
                        c = new EnemyAutoGenerationCommand(line);
                        break;

                    case "addrandombonus":
                        c = new AddRandomBonusCommand(line);
                        break;

                    case "changemusicstate":
                        c = new ChangeMusicStateCommand(line);
                        break;

                    case "wait":
                        c = new WaitCommand(line);
                        break;

                    case "addbomb":
                        c = new AddBombToPlayerCommand(line);
                        break;

                    default:
                        throw new Exception("Unknown TGPA script command " + line);
                    }

                    commands.Add(c);

                    line = reader.ReadLine();
                    while (line.Equals("") || line.StartsWith("//"))
                    {
                        line = reader.ReadLine();
                    }
                } //commands

                e.AddCommands(commands);

                map.Events.Add(e);

                line = reader.ReadLine();
                while (line.Equals("") || line.StartsWith("//"))
                {
                    line = reader.ReadLine();
                }
            } //events

            #endregion

            reader.Close();

            return(map);
        }
Exemplo n.º 20
0
        private void listBoxCommandSequence_DoubleClick(object sender, EventArgs e)
        {
            if (listBoxMacro.SelectedIndex == -1)
            {
                return;
            }

            try
            {
                string selected   = listBoxMacro.SelectedItem as string;
                string newCommand = null;


                if (selected.StartsWith(Common.CmdPrefixIf, StringComparison.OrdinalIgnoreCase))
                {
                    string[] commands = Common.SplitIfCommand(selected.Substring(Common.CmdPrefixIf.Length));

                    IfCommand ifCommand = new IfCommand(commands);
                    if (ifCommand.ShowDialog(this) == DialogResult.OK)
                    {
                        newCommand = Common.CmdPrefixIf + ifCommand.CommandString;
                    }
                }
                else if (selected.StartsWith(Common.CmdPrefixLabel, StringComparison.OrdinalIgnoreCase))
                {
                    LabelNameDialog labelDialog = new LabelNameDialog(selected.Substring(Common.CmdPrefixLabel.Length));
                    if (labelDialog.ShowDialog(this) == DialogResult.OK)
                    {
                        newCommand = Common.CmdPrefixLabel + labelDialog.LabelName;
                    }
                }
                else if (selected.StartsWith(Common.CmdPrefixGotoLabel, StringComparison.OrdinalIgnoreCase))
                {
                    LabelNameDialog labelDialog = new LabelNameDialog(selected.Substring(Common.CmdPrefixGotoLabel.Length));
                    if (labelDialog.ShowDialog(this) == DialogResult.OK)
                    {
                        newCommand = Common.CmdPrefixGotoLabel + labelDialog.LabelName;
                    }
                }
                else if (selected.StartsWith(Common.CmdPrefixSetVar, StringComparison.OrdinalIgnoreCase))
                {
                    string[] commands = Common.SplitSetVarCommand(selected.Substring(Common.CmdPrefixSetVar.Length));

                    SetVariableCommand setVariableCommand = new SetVariableCommand(commands);
                    if (setVariableCommand.ShowDialog(this) == DialogResult.OK)
                    {
                        newCommand = Common.CmdPrefixSetVar + setVariableCommand.CommandString;
                    }
                }
                else if (selected.StartsWith(Common.CmdPrefixLoadVars, StringComparison.OrdinalIgnoreCase))
                {
                    VariablesFileDialog varsFileDialog =
                        new VariablesFileDialog(selected.Substring(Common.CmdPrefixLoadVars.Length));
                    if (varsFileDialog.ShowDialog(this) == DialogResult.OK)
                    {
                        newCommand = Common.CmdPrefixLoadVars + varsFileDialog.FileName;
                    }
                }
                else if (selected.StartsWith(Common.CmdPrefixSaveVars, StringComparison.OrdinalIgnoreCase))
                {
                    VariablesFileDialog varsFileDialog =
                        new VariablesFileDialog(selected.Substring(Common.CmdPrefixSaveVars.Length));
                    if (varsFileDialog.ShowDialog(this) == DialogResult.OK)
                    {
                        newCommand = Common.CmdPrefixSaveVars + varsFileDialog.FileName;
                    }
                }
                else if (selected.StartsWith(Common.CmdPrefixRun, StringComparison.OrdinalIgnoreCase))
                {
                    string[] commands = Common.SplitRunCommand(selected.Substring(Common.CmdPrefixRun.Length));

                    ExternalProgram executeProgram = new ExternalProgram(commands);
                    if (executeProgram.ShowDialog(this) == DialogResult.OK)
                    {
                        newCommand = Common.CmdPrefixRun + executeProgram.CommandString;
                    }
                }
                else if (selected.StartsWith(Common.CmdPrefixPause, StringComparison.OrdinalIgnoreCase))
                {
                    PauseTime pauseTime = new PauseTime(int.Parse(selected.Substring(Common.CmdPrefixPause.Length)));
                    if (pauseTime.ShowDialog(this) == DialogResult.OK)
                    {
                        newCommand = Common.CmdPrefixPause + pauseTime.Time;
                    }
                }
                else if (selected.StartsWith(Common.CmdPrefixSerial, StringComparison.OrdinalIgnoreCase))
                {
                    string[] commands = Common.SplitSerialCommand(selected.Substring(Common.CmdPrefixSerial.Length));

                    SerialCommand serialCommand = new SerialCommand(commands);
                    if (serialCommand.ShowDialog(this) == DialogResult.OK)
                    {
                        newCommand = Common.CmdPrefixSerial + serialCommand.CommandString;
                    }
                }
                else if (selected.StartsWith(Common.CmdPrefixWindowMsg, StringComparison.OrdinalIgnoreCase))
                {
                    string[] commands = Common.SplitWindowMessageCommand(selected.Substring(Common.CmdPrefixWindowMsg.Length));

                    MessageCommand messageCommand = new MessageCommand(commands);
                    if (messageCommand.ShowDialog(this) == DialogResult.OK)
                    {
                        newCommand = Common.CmdPrefixWindowMsg + messageCommand.CommandString;
                    }
                }
                else if (selected.StartsWith(Common.CmdPrefixTcpMsg, StringComparison.OrdinalIgnoreCase))
                {
                    string[] commands = Common.SplitTcpMessageCommand(selected.Substring(Common.CmdPrefixTcpMsg.Length));

                    TcpMessageCommand tcpMessageCommand = new TcpMessageCommand(commands);
                    if (tcpMessageCommand.ShowDialog(this) == DialogResult.OK)
                    {
                        newCommand = Common.CmdPrefixTcpMsg + tcpMessageCommand.CommandString;
                    }
                }
                else if (selected.StartsWith(Common.CmdPrefixHttpMsg, StringComparison.OrdinalIgnoreCase))
                {
                    string[] commands = Common.SplitHttpMessageCommand(selected.Substring(Common.CmdPrefixHttpMsg.Length));

                    HttpMessageCommand httpMessageCommand = new HttpMessageCommand(commands);
                    if (httpMessageCommand.ShowDialog(this) == DialogResult.OK)
                    {
                        newCommand = Common.CmdPrefixHttpMsg + httpMessageCommand.CommandString;
                    }
                }
                else if (selected.StartsWith(Common.CmdPrefixKeys, StringComparison.OrdinalIgnoreCase))
                {
                    KeysCommand keysCommand = new KeysCommand(selected.Substring(Common.CmdPrefixKeys.Length));
                    if (keysCommand.ShowDialog(this) == DialogResult.OK)
                    {
                        newCommand = Common.CmdPrefixKeys + keysCommand.CommandString;
                    }
                }
                else if (selected.StartsWith(Common.CmdPrefixMouse, StringComparison.OrdinalIgnoreCase))
                {
                    MouseCommand mouseCommand = new MouseCommand(selected.Substring(Common.CmdPrefixMouse.Length));
                    if (mouseCommand.ShowDialog(this) == DialogResult.OK)
                    {
                        newCommand = Common.CmdPrefixMouse + mouseCommand.CommandString;
                    }
                }
                else if (selected.StartsWith(Common.CmdPrefixEject, StringComparison.OrdinalIgnoreCase))
                {
                    EjectCommand ejectCommand = new EjectCommand(selected.Substring(Common.CmdPrefixEject.Length));
                    if (ejectCommand.ShowDialog(this) == DialogResult.OK)
                    {
                        newCommand = Common.CmdPrefixEject + ejectCommand.CommandString;
                    }
                }
                else if (selected.StartsWith(Common.CmdPrefixPopup, StringComparison.OrdinalIgnoreCase))
                {
                    string[] commands = Common.SplitPopupCommand(selected.Substring(Common.CmdPrefixPopup.Length));

                    PopupMessage popupMessage = new PopupMessage(commands);
                    if (popupMessage.ShowDialog(this) == DialogResult.OK)
                    {
                        newCommand = Common.CmdPrefixPopup + popupMessage.CommandString;
                    }
                }
                else if (selected.StartsWith(Common.CmdPrefixBeep, StringComparison.OrdinalIgnoreCase))
                {
                    string[] commands = Common.SplitBeepCommand(selected.Substring(Common.CmdPrefixBeep.Length));

                    BeepCommand beepCommand = new BeepCommand(commands);
                    if (beepCommand.ShowDialog(this) == DialogResult.OK)
                    {
                        newCommand = Common.CmdPrefixBeep + beepCommand.CommandString;
                    }
                }
                else if (selected.StartsWith(Common.CmdPrefixSound, StringComparison.OrdinalIgnoreCase))
                {
                    OpenFileDialog openFileDialog = new OpenFileDialog();
                    openFileDialog.Filter      = "Wave Files|*.wav";
                    openFileDialog.Multiselect = false;
                    openFileDialog.FileName    = selected.Substring(Common.CmdPrefixSound.Length);

                    if (openFileDialog.ShowDialog(this) == DialogResult.OK)
                    {
                        newCommand = Common.CmdPrefixSound + openFileDialog.FileName;
                    }
                }
                else if (selected.StartsWith(Common.CmdPrefixDisplayMode, StringComparison.OrdinalIgnoreCase))
                {
                    string[] commands = Common.SplitDisplayModeCommand(selected.Substring(Common.CmdPrefixDisplayMode.Length));

                    DisplayModeCommand displayModeCommand = new DisplayModeCommand(commands);
                    if (displayModeCommand.ShowDialog(this) == DialogResult.OK)
                    {
                        newCommand = Common.CmdPrefixDisplayMode + displayModeCommand.CommandString;
                    }
                }
                else if (selected.StartsWith(Common.CmdPrefixBlast, StringComparison.OrdinalIgnoreCase))
                {
                    string[] commands = Common.SplitBlastCommand(selected.Substring(Common.CmdPrefixBlast.Length));

                    BlastCommand blastCommand = new BlastCommand(
                        Program.BlastIR,
                        Common.FolderIRCommands,
                        Program.TransceiverInformation.Ports,
                        commands);

                    if (blastCommand.ShowDialog(this) == DialogResult.OK)
                    {
                        newCommand = Common.CmdPrefixBlast + blastCommand.CommandString;
                    }
                }

                if (!String.IsNullOrEmpty(newCommand))
                {
                    int index = listBoxMacro.SelectedIndex;
                    listBoxMacro.Items.RemoveAt(index);
                    listBoxMacro.Items.Insert(index, newCommand);
                    listBoxMacro.SelectedIndex = index;
                }
            }
            catch (Exception ex)
            {
                IrssLog.Error(ex);
                MessageBox.Show(this, ex.Message, "Failed to edit macro item", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Exemplo n.º 21
0
        private void buttonAddCommand_Click(object sender, EventArgs e)
        {
            if (comboBoxCommands.SelectedIndex == -1)
            {
                return;
            }

            try
            {
                string selected   = comboBoxCommands.SelectedItem as string;
                string newCommand = null;

                if (selected.Equals(Common.UITextIf, StringComparison.OrdinalIgnoreCase))
                {
                    IfCommand ifCommand = new IfCommand();
                    if (ifCommand.ShowDialog(this) == DialogResult.OK)
                    {
                        newCommand = Common.CmdPrefixIf + ifCommand.CommandString;
                    }
                }
                else if (selected.Equals(Common.UITextLabel, StringComparison.OrdinalIgnoreCase))
                {
                    LabelNameDialog labelDialog = new LabelNameDialog();
                    if (labelDialog.ShowDialog(this) == DialogResult.OK)
                    {
                        newCommand = Common.CmdPrefixLabel + labelDialog.LabelName;
                    }
                }
                else if (selected.Equals(Common.UITextGotoLabel, StringComparison.OrdinalIgnoreCase))
                {
                    LabelNameDialog labelDialog = new LabelNameDialog();
                    if (labelDialog.ShowDialog(this) == DialogResult.OK)
                    {
                        newCommand = Common.CmdPrefixGotoLabel + labelDialog.LabelName;
                    }
                }
                else if (selected.Equals(Common.UITextSetVar, StringComparison.OrdinalIgnoreCase))
                {
                    SetVariableCommand setVariableCommand = new SetVariableCommand();
                    if (setVariableCommand.ShowDialog(this) == DialogResult.OK)
                    {
                        newCommand = Common.CmdPrefixSetVar + setVariableCommand.CommandString;
                    }
                }
                else if (selected.Equals(Common.UITextClearVars, StringComparison.OrdinalIgnoreCase))
                {
                    newCommand = Common.CmdPrefixClearVars;
                }
                else if (selected.Equals(Common.UITextLoadVars, StringComparison.OrdinalIgnoreCase))
                {
                    VariablesFileDialog varsFileDialog = new VariablesFileDialog();
                    if (varsFileDialog.ShowDialog(this) == DialogResult.OK)
                    {
                        newCommand = Common.CmdPrefixLoadVars + varsFileDialog.FileName;
                    }
                }
                else if (selected.Equals(Common.UITextSaveVars, StringComparison.OrdinalIgnoreCase))
                {
                    VariablesFileDialog varsFileDialog = new VariablesFileDialog();
                    if (varsFileDialog.ShowDialog(this) == DialogResult.OK)
                    {
                        newCommand = Common.CmdPrefixSaveVars + varsFileDialog.FileName;
                    }
                }
                else if (selected.Equals(Common.UITextRun, StringComparison.OrdinalIgnoreCase))
                {
                    ExternalProgram externalProgram = new ExternalProgram();
                    if (externalProgram.ShowDialog(this) == DialogResult.OK)
                    {
                        newCommand = Common.CmdPrefixRun + externalProgram.CommandString;
                    }
                }
                else if (selected.Equals(Common.UITextPause, StringComparison.OrdinalIgnoreCase))
                {
                    PauseTime pauseTime = new PauseTime();
                    if (pauseTime.ShowDialog(this) == DialogResult.OK)
                    {
                        newCommand = Common.CmdPrefixPause + pauseTime.Time;
                    }
                }
                else if (selected.Equals(Common.UITextSerial, StringComparison.OrdinalIgnoreCase))
                {
                    SerialCommand serialCommand = new SerialCommand();
                    if (serialCommand.ShowDialog(this) == DialogResult.OK)
                    {
                        newCommand = Common.CmdPrefixSerial + serialCommand.CommandString;
                    }
                }
                else if (selected.Equals(Common.UITextWindowMsg, StringComparison.OrdinalIgnoreCase))
                {
                    MessageCommand messageCommand = new MessageCommand();
                    if (messageCommand.ShowDialog(this) == DialogResult.OK)
                    {
                        newCommand = Common.CmdPrefixWindowMsg + messageCommand.CommandString;
                    }
                }
                else if (selected.Equals(Common.UITextTcpMsg, StringComparison.OrdinalIgnoreCase))
                {
                    TcpMessageCommand tcpMessageCommand = new TcpMessageCommand();
                    if (tcpMessageCommand.ShowDialog(this) == DialogResult.OK)
                    {
                        newCommand = Common.CmdPrefixTcpMsg + tcpMessageCommand.CommandString;
                    }
                }
                else if (selected.Equals(Common.UITextHttpMsg, StringComparison.OrdinalIgnoreCase))
                {
                    HttpMessageCommand httpMessageCommand = new HttpMessageCommand();
                    if (httpMessageCommand.ShowDialog(this) == DialogResult.OK)
                    {
                        newCommand = Common.CmdPrefixHttpMsg + httpMessageCommand.CommandString;
                    }
                }
                else if (selected.Equals(Common.UITextKeys, StringComparison.OrdinalIgnoreCase))
                {
                    KeysCommand keysCommand = new KeysCommand();
                    if (keysCommand.ShowDialog(this) == DialogResult.OK)
                    {
                        newCommand = Common.CmdPrefixKeys + keysCommand.CommandString;
                    }
                }
                else if (selected.Equals(Common.UITextMouse, StringComparison.OrdinalIgnoreCase))
                {
                    MouseCommand mouseCommand = new MouseCommand();
                    if (mouseCommand.ShowDialog(this) == DialogResult.OK)
                    {
                        newCommand = Common.CmdPrefixMouse + mouseCommand.CommandString;
                    }
                }
                else if (selected.Equals(Common.UITextEject, StringComparison.OrdinalIgnoreCase))
                {
                    EjectCommand ejectCommand = new EjectCommand();
                    if (ejectCommand.ShowDialog(this) == DialogResult.OK)
                    {
                        newCommand = Common.CmdPrefixEject + ejectCommand.CommandString;
                    }
                }
                else if (selected.Equals(Common.UITextPopup, StringComparison.OrdinalIgnoreCase))
                {
                    PopupMessage popupMessage = new PopupMessage();
                    if (popupMessage.ShowDialog(this) == DialogResult.OK)
                    {
                        newCommand = Common.CmdPrefixPopup + popupMessage.CommandString;
                    }
                }
                else if (selected.Equals(Common.UITextVirtualKB, StringComparison.OrdinalIgnoreCase))
                {
                    newCommand = Common.CmdPrefixVirtualKB;
                }
                else if (selected.Equals(Common.UITextSmsKB, StringComparison.OrdinalIgnoreCase))
                {
                    newCommand = Common.CmdPrefixSmsKB;
                }
                else if (selected.Equals(Common.UITextBeep, StringComparison.OrdinalIgnoreCase))
                {
                    BeepCommand beepCommand = new BeepCommand();
                    if (beepCommand.ShowDialog(this) == DialogResult.OK)
                    {
                        newCommand = Common.CmdPrefixBeep + beepCommand.CommandString;
                    }
                }
                else if (selected.Equals(Common.UITextSound, StringComparison.OrdinalIgnoreCase))
                {
                    OpenFileDialog openFileDialog = new OpenFileDialog();
                    openFileDialog.Filter      = "Wave Files|*.wav";
                    openFileDialog.Multiselect = false;

                    if (openFileDialog.ShowDialog(this) == DialogResult.OK)
                    {
                        newCommand = Common.CmdPrefixSound + openFileDialog.FileName;
                    }
                }
                else if (selected.Equals(Common.UITextDisplayMode, StringComparison.OrdinalIgnoreCase))
                {
                    DisplayModeCommand displayModeCommand = new DisplayModeCommand();
                    if (displayModeCommand.ShowDialog(this) == DialogResult.OK)
                    {
                        newCommand = Common.CmdPrefixDisplayMode + displayModeCommand.CommandString;
                    }
                }
                else if (selected.Equals(Common.UITextStandby, StringComparison.OrdinalIgnoreCase))
                {
                    newCommand = Common.CmdPrefixStandby;
                }
                else if (selected.Equals(Common.UITextHibernate, StringComparison.OrdinalIgnoreCase))
                {
                    newCommand = Common.CmdPrefixHibernate;
                }
                else if (selected.Equals(Common.UITextReboot, StringComparison.OrdinalIgnoreCase))
                {
                    newCommand = Common.CmdPrefixReboot;
                }
                else if (selected.Equals(Common.UITextShutdown, StringComparison.OrdinalIgnoreCase))
                {
                    newCommand = Common.CmdPrefixShutdown;
                }
                else if (selected.StartsWith(Common.CmdPrefixBlast, StringComparison.OrdinalIgnoreCase))
                {
                    BlastCommand blastCommand = new BlastCommand(
                        Program.BlastIR,
                        Common.FolderIRCommands,
                        Program.TransceiverInformation.Ports,
                        selected.Substring(Common.CmdPrefixBlast.Length));

                    if (blastCommand.ShowDialog(this) == DialogResult.OK)
                    {
                        newCommand = Common.CmdPrefixBlast + blastCommand.CommandString;
                    }
                }
                else if (selected.StartsWith(Common.CmdPrefixMacro, StringComparison.OrdinalIgnoreCase))
                {
                    newCommand = selected;
                }
                else
                {
                    throw new CommandStructureException(String.Format("Unknown macro command ({0})", selected));
                }

                if (!String.IsNullOrEmpty(newCommand))
                {
                    listBoxMacro.Items.Add(newCommand);
                }
            }
            catch (Exception ex)
            {
                IrssLog.Error(ex);
                MessageBox.Show(this, ex.Message, "Failed to add macro command", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Exemplo n.º 22
0
        public void DashIf(bool containElse, string expr, string op1, string opr, string op2)
        {
            IHalationCommand cmd = new IfCommand(Halation.CurrentSelectedLine, this.GetIndent(Halation.CurrentSelectedLine), Halation.currentCodePackage, containElse, expr, op1, opr, op2);

            HalationInvoker.Dash(Halation.currentScriptName, cmd);
        }
Exemplo n.º 23
0
        /// <summary>
        /// Main Parser function. Takes string of tokens and parses into Command elements.
        /// Most Commands will just be plain strings, but some ('if', 'loop' etc. will be
        /// dedicated commands with properties specifying the sub-commands to be executed)
        /// </summary>
        /// <param name="tokens">Array of tokens to parse</param>
        /// <param name="tokenIndex">Initial token index</param>
        /// <param name="stopTokens">Array of stop-tokens. E.g. 'If' parsing should stop on 'else' or 'endif'</param>
        /// <returns>Array of Command objects</returns>
        public static Command[] Parse(string[] tokens, ref int tokenIndex, string[] stopTokens)
        {
            List <Command> parsedTokens = new List <Command>();

            while (tokenIndex < tokens.Length)
            {
                string token = tokens[tokenIndex];
                if (token.Equals(Constants.If))
                {
                    IfCommand ifCommand = new IfCommand();

                    tokenIndex++;
                    ifCommand.IfCommands.AddRange(Parse(tokens, ref tokenIndex,
                                                        new[] { Constants.Else, Constants.EndIf }));
                    // Only parse the following tokens in our 'if' statement if the next token after the 'then' phase is *not*
                    // 'endif'. This is to handle 'else-less' 'if's where we are only programmed to handle what happens when
                    // the 'if' evaluation is true, and to do nothing when the 'if' evaluation is false.
                    if (tokenIndex >= 1 && !tokens[tokenIndex - 1].Equals(Constants.EndIf))
                    {
                        ifCommand.ElseCommands.AddRange(Parse(tokens, ref tokenIndex, new[] { Constants.EndIf }));
                    }

                    parsedTokens.Add(ifCommand);
                }
                else if (token.Equals(Constants.Loop))
                {
                    LoopCommand loopCommand = new LoopCommand();

                    tokenIndex++;
                    loopCommand.LoopCommands.AddRange(Parse(tokens, ref tokenIndex, new[] { Constants.EndLoop }));

                    parsedTokens.Add(loopCommand);
                }
                else if (token.Equals(Constants.Repeat))
                {
                    RepeatCommand repeatCommand = new RepeatCommand();

                    tokenIndex++;
                    repeatCommand.RepeatCommands.AddRange(Parse(tokens, ref tokenIndex,
                                                                new[] { Constants.Until }));

                    parsedTokens.Add(repeatCommand);
                }
                else
                {
                    // For anything that's not an 'if', or loop, just add the string as a command.
                    // The executor can handle if it's not an actual command
                    parsedTokens.Add(new Command(token));

                    if ((stopTokens != null) && (stopTokens.Contains(token)))
                    {
                        tokenIndex++;
                        return(parsedTokens.ToArray());
                    }

                    tokenIndex++;
                }
            }

            if (stopTokens != null)
            {
                // If we get here then 'stopTokens' was set to something that should terminate a sequence of commands,
                // but wasn't found. E.G. An 'if' without an 'endif'.
                throw new Exception(string.Format(Resources.Expected_, string.Join("/", stopTokens)));
            }

            return(parsedTokens.ToArray());
        }