Beispiel #1
0
        public void Start()
        {
            // remove old sprites
            battleground.Sprites.Clear();

            // clear script context, all of global variables will be removed
            srm.Reset();

            // create an extended function to create .NET color object
            srm["rgb"] = new NativeFunctionObject("rgb", (ctx, owner, args) =>
            {
                int r = ScriptRunningMachine.GetIntParam(args, 0, 0);
                int g = ScriptRunningMachine.GetIntParam(args, 1, 0);
                int b = ScriptRunningMachine.GetIntParam(args, 2, 0);

                // this object will be returned into the world of script
                return(Color.FromArgb(r, g, b));
            });

            // add battleground object
            srm["battleground"] = battleground;

            // run script
            srm.Run(editor.Text);
        }
Beispiel #2
0
        static void Main()
        {
            var srm = new ScriptRunningMachine();

            srm.AllowDirectAccess = true;

            // proxy mode
            srm.ImportType(typeof(CarProxy), "Car1");

            // attribute mode
            srm.ImportType(typeof(Car2), "Car2");

            // DirectAccess mode
            srm.ImportType(typeof(Car), "Car3");

            srm.Run(@"

var car1 = new Car1();
car1.forward();

var car2 = new Car2();
car2.forward();

var car3 = new Car3();
car3.forward();

");
        }
Beispiel #3
0
        /// <summary>
        /// Get range information from script value
        /// </summary>
        /// <param name="sheet">worksheet instance</param>
        /// <param name="args">script value to be converted</param>
        /// <returns></returns>
        public static RangePosition GetRangeFromArgs(Worksheet sheet, object[] args)
        {
            if (args.Length == 0)
            {
                return(RangePosition.Empty);
            }

            if (args.Length == 1)
            {
                return(GetRangeFromValue(sheet, args[0]));
            }
            else
            {
                RangePosition range = RangePosition.Empty;

                range.Row = Convert.ToInt32(args[0]);
                if (args.Length > 1)
                {
                    range.Col = ScriptRunningMachine.GetIntValue(args[1]);
                }
                if (args.Length > 2)
                {
                    range.Rows = ScriptRunningMachine.GetIntValue(args[2]);
                }
                if (args.Length > 3)
                {
                    range.Cols = ScriptRunningMachine.GetIntValue(args[3]);
                }

                return(range);
            }
        }
Beispiel #4
0
        internal static WorksheetRangeStyle GetRangeStyleObject(object p)
        {
            if (p is WorksheetRangeStyle)
            {
                return((WorksheetRangeStyle)p);
            }
            else if (p is ObjectValue)
            {
                var obj = (ObjectValue)p;

                WorksheetRangeStyle style = new WorksheetRangeStyle();

                SolidColor color;

                object backColor = obj["backgroundColor"];
                if (TextFormatHelper.DecodeColor(ScriptRunningMachine.ConvertToString(backColor), out color))
                {
                    style.Flag     |= PlainStyleFlag.BackColor;
                    style.BackColor = color;
                }

                return(style);
            }
            else
            {
                return(null);
            }
        }
Beispiel #5
0
        /// <summary>
        /// Move forward selection
        /// </summary>
        public void MoveSelectionForward()
        {
            if (SelectionMovedForward != null)
            {
                var arg = new SelectionMovedForwardEventArgs();
                SelectionMovedForward(this, arg);
                if (arg.IsCancelled)
                {
                    return;
                }
            }

#if EX_SCRIPT
            var scriptReturn = RaiseScriptEvent("onnextfocus");
            if (scriptReturn != null && !ScriptRunningMachine.GetBoolValue(scriptReturn))
            {
                return;
            }
#endif

            switch (selectionForwardDirection)
            {
            case SelectionForwardDirection.Right:
            {
                if (this.selEnd.Col < this.cols.Count - 1)
                {
                    MoveSelectionRight();
                }
                else
                {
                    if (this.selEnd.Row < this.rows.Count - 1)
                    {
                        this.selEnd.Col = 0;
                        MoveSelectionDown();
                    }
                }
            }
            break;

            case SelectionForwardDirection.Down:
            {
                if (this.selEnd.Row < this.rows.Count - 1)
                {
                    this.selEnd.Col = this.focusReturnColumn;

                    MoveSelectionDown();
                }
                else
                {
                    if (this.selEnd.Col < this.cols.Count - 1)
                    {
                        this.selEnd.Row = 0;
                        MoveSelectionRight();
                    }
                }
            }
            break;
            }
        }
Beispiel #6
0
 private static void SetVarible(ScriptRunningMachine srm, string identifier, string str)
 {
     double variable = 0;
     if (double.TryParse(str, out variable))
         srm.SetGlobalVariable(identifier, variable);
     else
         srm.SetGlobalVariable(identifier, str);
 }
Beispiel #7
0
 public int this[string key]
 {
     get { return(arr[ScriptRunningMachine.GetIntValue(key.Substring(4))]); }
     set
     {
         int idx = ScriptRunningMachine.GetIntValue(key.Substring(4));
         arr[idx] = value;
     }
 }
Beispiel #8
0
        void ExternalVariableTest()
        {
            var srm = new ScriptRunningMachine();

            srm["a"] = 10;
            srm.Run("var b = a + 20; ");

            TestCaseAssertion.AssertEquals(srm["b"], 30d);
        }
Beispiel #9
0
        public RSCellObject(Worksheet sheet, CellPosition pos, Cell cell)
        {
            this.sheet = sheet;
            this.Pos   = pos;
            this.Cell  = cell;

            this["style"] = new ExternalProperty(() =>
            {
                if (cell == null)
                {
                    cell = sheet.CreateAndGetCell(pos);
                }
                if (this.Style == null)
                {
                    this.Style = new RSCellStyleObject(sheet, cell);
                }
                return(this.Style);
            }, null);

            this["data"] = new ExternalProperty(
                () => cell == null ? null : cell.InnerData,
                (v) =>
            {
                if (cell == null)
                {
                    sheet[pos] = v;
                }
                else if (!cell.IsReadOnly)
                {
                    sheet[cell] = v;
                }
            });

#if FORMULA
            this["formula"] = new ExternalProperty(
                () => cell == null ? string.Empty : cell.InnerFormula,
                (v) =>
            {
                if (cell == null)
                {
                    sheet.SetCellFormula(pos, ScriptRunningMachine.ConvertToString(v));
                }
                else if (!cell.IsReadOnly)
                {
                    cell.Formula = ScriptRunningMachine.ConvertToString(v);
                }
            });
#endif // FORMULA

            this["text"] = new ExternalProperty(() => cell == null ? string.Empty : cell.DisplayText);

            this["pos"] = new ExternalProperty(() => cell == null ? Pos : cell.InternalPos);
            this["row"] = new ExternalProperty(() => cell == null ? Pos.Row : cell.InternalRow);
            this["col"] = new ExternalProperty(() => cell == null ? Pos.Col : cell.InternalCol);

            this["address"] = new ExternalProperty(() => cell.Position.ToAddress());
        }
Beispiel #10
0
        /// <summary>
        /// This example shows how to get the information about functions and variables that
        /// is written in script from .NET program.
        ///
        /// ReoScript provides the ability to get functions and variables information after
        /// script is compiling.
        ///
        /// To use this feature you have to use the following namespaces:
        ///
        /// - Unvell.ReoScript
        /// - Unvell.ReoScript.Reflection
        ///
        /// The script's instruction information returned in a tree-style:
        ///
        ///     CompiledScript
        ///         +- Functions
        ///             +- Functions
        ///                 +- Functions
        ///                 +- Variables
        ///             +- Variables
        ///         +- Variables
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            string script = @"

				function normal() {
					return 'normal function';
				}

				function outer(p1, p2, p3, p4) {
					
					function inner(key, value) { 
            var local = 10;

						function inner2(param) {
            }
					}

					return function(a, b) { return a + b; } ();
				}

				var af = function(x, y) { return x * y; };

				var result = af(2, 5);
		        
			"            ;

            ScriptRunningMachine srm = new ScriptRunningMachine();
            CompiledScript       cs  = srm.Compile(script, true);

            Console.WriteLine("Functions: ");
            Console.WriteLine();

            foreach (FunctionInfo fi in cs.DeclaredFunctions)
            {
                IterateFunction(fi, 0);
            }

            Console.WriteLine("Global Variables: ");
            Console.WriteLine();

            foreach (VariableInfo vi in cs.DeclaredVariables)
            {
                PrintOutLine("Variable Name", vi.Name, 0);
                PrintOutLine("  Has Initial Value", vi.HasInitialValue.ToString(), 0);
                PrintOutLine("  Position", vi.Line + ":" + vi.CharIndex, 0);
                Console.WriteLine();
            }


#if DEBUG
            Console.WriteLine("Press any key to continue...");
            Console.ReadKey();
#endif
        }
Beispiel #11
0
        /// <summary>
        /// Get range information from script value
        /// </summary>
        /// <param name="sheet">worksheet instance</param>
        /// <param name="arg">script object to be converted</param>
        /// <returns></returns>
        public static RangePosition GetRangeFromValue(Worksheet sheet, object arg)
        {
            if (arg is RangePosition)
            {
                return((RangePosition)arg);
            }
            else if (arg is string)
            {
                var        addr = (string)arg;
                NamedRange namedRange;
                if (RangePosition.IsValidAddress(addr))
                {
                    return(new RangePosition(addr));
                }
                else if (NamedRange.IsValidName(addr) &&
                         sheet.TryGetNamedRange(addr, out namedRange))
                {
                    return((RangePosition)namedRange);
                }
                else
                {
                    throw new InvalidAddressException(addr);
                }
            }
            else if (arg is ReferenceRange)
            {
                return(((ReferenceRange)arg).Position);
            }
            else if (arg is RSSelectionObject)
            {
                return(sheet.SelectionRange);
            }
            else if (arg is RSRangeObject)
            {
                return(((RSRangeObject)arg).Range);
            }

            ObjectValue obj = arg as ObjectValue;

            if (obj == null)
            {
                return(RangePosition.Empty);
            }

            RangePosition range = RangePosition.Empty;

            range.Row  = ScriptRunningMachine.GetIntValue(obj["row"]);
            range.Col  = ScriptRunningMachine.GetIntValue(obj["col"]);
            range.Rows = ScriptRunningMachine.GetIntValue(obj["rows"]);
            range.Cols = ScriptRunningMachine.GetIntValue(obj["cols"]);

            return(range);
        }
Beispiel #12
0
        /// <summary>
        /// This example shows how to get the information about functions and variables that 
        /// is written in script from .NET program.
        /// 
        /// ReoScript provides the ability to get functions and variables information after 
        /// script is compiling. 
        /// 
        /// To use this feature you have to use the following namespaces:
        /// 
        /// - Unvell.ReoScript
        /// - Unvell.ReoScript.Reflection
        /// 
        /// The script's instruction information returned in a tree-style:
        /// 
        ///     CompiledScript
        ///         +- Functions
        ///             +- Functions
        ///                 +- Functions
        ///                 +- Variables
        ///             +- Variables
        ///         +- Variables
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            string script = @"

                function normal() {
                    return 'normal function';
                }

                function outer(p1, p2, p3, p4) {

                    function inner(key, value) {
            var local = 10;

                        function inner2(param) {
            }
                    }

                    return function(a, b) { return a + b; } ();
                }

                var af = function(x, y) { return x * y; };

                var result = af(2, 5);

            ";

            ScriptRunningMachine srm = new ScriptRunningMachine();
            CompiledScript cs = srm.Compile(script, true);

            Console.WriteLine("Functions: ");
            Console.WriteLine();

            foreach (FunctionInfo fi in cs.DeclaredFunctions)
            {
                IterateFunction(fi, 0);
            }

            Console.WriteLine("Global Variables: ");
            Console.WriteLine();

            foreach (VariableInfo vi in cs.DeclaredVariables)
            {
                PrintOutLine("Variable Name", vi.Name, 0);
                PrintOutLine("  Has Initial Value", vi.HasInitialValue.ToString(), 0);
                PrintOutLine("  Position", vi.Line + ":" + vi.CharIndex, 0);
                Console.WriteLine();
            }

            #if DEBUG
            Console.WriteLine("Press any key to continue...");
            Console.ReadKey();
            #endif
        }
Beispiel #13
0
        private static void SetVarible(ScriptRunningMachine srm, string identifier, string str)
        {
            double variable = 0;

            if (double.TryParse(str, out variable))
            {
                srm.SetGlobalVariable(identifier, variable);
            }
            else
            {
                srm.SetGlobalVariable(identifier, str);
            }
        }
Beispiel #14
0
        public RSColumnObject(Worksheet sheet, ColumnHeader colHeader)
        {
            this.sheet     = sheet;
            this.colHeader = colHeader;

            this["width"] = new ExternalProperty(
                () => colHeader.Width,
                (v) => colHeader.Width = (ushort)ScriptRunningMachine.GetIntValue(v));

            this["visible"] = new ExternalProperty(
                () => colHeader.IsVisible,
                (v) => colHeader.IsVisible = ScriptRunningMachine.GetBoolValue(v));
        }
Beispiel #15
0
        public RSRowObject(Worksheet sheet, RowHeader rowHeader)
        {
            this.sheet     = sheet;
            this.rowHeader = rowHeader;

            this["height"] = new ExternalProperty(
                () => rowHeader.Height,
                (v) => rowHeader.Height = (ushort)ScriptRunningMachine.GetIntValue(v));

            this["visible"] = new ExternalProperty(
                () => rowHeader.IsVisible,
                (v) => rowHeader.IsVisible = ScriptRunningMachine.GetBoolValue(v));
        }
Beispiel #16
0
        /// <summary>
        /// Copy any remove anything from selected range into Clipboard.
        /// </summary>
        public bool Cut()
        {
            if (IsEditing)
            {
                this.controlAdapter.EditControlCut();
            }
            else
            {
                if (!Copy())
                {
                    return(false);
                }

                if (BeforeCut != null)
                {
                    var evtArg = new BeforeRangeOperationEventArgs(this.selectionRange);

                    BeforeCut(this, evtArg);

                    if (evtArg.IsCancelled)
                    {
                        return(false);
                    }
                }

#if EX_SCRIPT
                object scriptReturn = RaiseScriptEvent("oncut");
                if (scriptReturn != null && !ScriptRunningMachine.GetBoolValue(scriptReturn))
                {
                    return(false);
                }
#endif

                if (!HasSettings(WorksheetSettings.Edit_Readonly))
                {
                    if (controlAdapter.ControlInstance is IActionControl actionSupportedControl)
                    {
                        actionSupportedControl.DoAction(this, new RemoveRangeDataAction(currentCopingRange));
                    }
                }

                if (AfterCut != null)
                {
                    AfterCut(this, new RangeEventArgs(this.selectionRange));
                }
            }

            return(true);
        }
Beispiel #17
0
        /// <summary>
        /// Copy any remove anything from selected range into Clipboard.
        /// </summary>
        public bool Cut()
        {
            if (IsEditing)
            {
                this.controlAdapter.EditControlCut();
            }
            else
            {
                if (!Copy())
                {
                    return(false);
                }

                if (BeforeCut != null)
                {
                    var evtArg = new BeforeRangeOperationEventArgs(this.selectionRange);

                    BeforeCut(this, evtArg);

                    if (evtArg.IsCancelled)
                    {
                        return(false);
                    }
                }

#if EX_SCRIPT
                object scriptReturn = RaiseScriptEvent("oncut");
                if (scriptReturn != null && !ScriptRunningMachine.GetBoolValue(scriptReturn))
                {
                    return(false);
                }
#endif

                if (!HasSettings(WorksheetSettings.Edit_Readonly))
                {
                    this.DeleteRangeData(currentCopingRange);
                    this.RemoveRangeStyles(currentCopingRange, PlainStyleFlag.All);
                    this.RemoveRangeBorders(currentCopingRange, BorderPositions.All);
                }

                if (AfterCut != null)
                {
                    AfterCut(this, new RangeEventArgs(this.selectionRange));
                }
            }

            return(true);
        }
Beispiel #18
0
        /// <summary>
        /// Initial or reset Script Running Machine
        /// </summary>
        internal void InitSRM()
        {
#if DEBUG
            Stopwatch sw = Stopwatch.StartNew();
#endif

            if (srm == null)
            {
                // create ReoScript instance
                srm = new ScriptRunningMachine();

                // reinit instance when SRM is reset
                srm.Resetted += (s, e) => InitSRM();
            }

            // set control instance into script's context
            if (workbookObj == null)
            {
                workbookObj = new RSWorkbook(this);
            }

            srm["workbook"] = workbookObj;

#if V088_RESERVED
            // setup built-in functions
            RSFunctions.SetupBuiltinFunctions(this);
#endif // V088_RESERVED

            // load core library
            using (MemoryStream ms = new MemoryStream(Resources.base_lib))
            {
                srm.Load(ms);
            }

            if (this.SRMInitialized != null)
            {
                this.SRMInitialized(this, null);
            }

#if DEBUG
            sw.Stop();
            long ems = sw.ElapsedMilliseconds;
            if (ems > 10)
            {
                Debug.WriteLine("init srm takes " + ems + " ms.");
            }
#endif
        }
Beispiel #19
0
 public static SizeF GetSizeObject(ScriptContext ctx, object arg, SizeF def)
 {
     if (arg is SizeF)
     {
         return((SizeF)arg);
     }
     else if (arg is ObjectValue)
     {
         return(new SizeF(ScriptRunningMachine.GetFloatValue(((ObjectValue)arg)["width"], def.Width),
                          ScriptRunningMachine.GetFloatValue(((ObjectValue)arg)["height"], def.Height)));
     }
     else
     {
         return(def);
     }
 }
Beispiel #20
0
 public static PointF GetPointObject(ScriptContext ctx, object arg, PointF def)
 {
     if (arg is PointF)
     {
         return((PointF)arg);
     }
     else if (arg is ObjectValue)
     {
         return(new PointF(ScriptRunningMachine.GetFloatValue(((ObjectValue)arg)["x"], def.X),
                           ScriptRunningMachine.GetFloatValue(((ObjectValue)arg)["y"], def.Y)));
     }
     else
     {
         return(def);
     }
 }
Beispiel #21
0
        public void ReoScriptFunction()
        {
            // custom function in script
            Grid.RunScript("script.myfun = data => '[' + data + ']'; ");
            worksheet[10, 0] = "=myfun(\"abc\")";
            AssertEquals(worksheet.GetCellText(10, 0), "[abc]");

            // custom function in .NET
            Grid.Srm["add"] = new NativeFunctionObject("add", (ctx, owner, args) =>
            {
                int v1 = ScriptRunningMachine.GetIntParam(args, 0);
                int v2 = ScriptRunningMachine.GetIntParam(args, 1);
                return(v1 + v2);
            });

            worksheet[0, 10] = "=add(2,3)";
            AssertEquals(worksheet.GetCellText(0, 10), "5");
        }
Beispiel #22
0
        public static bool TryGetPosFromValue(Worksheet sheet, object arg, out CellPosition pos)
        {
            if (arg is object[])
            {
                object[] args = (object[])arg;

                return(TryGetPosFromArgs(sheet, args, out pos));
            }
            else if (arg is ObjectValue)
            {
                var obj = (ObjectValue)arg;

                pos = new CellPosition(ScriptRunningMachine.GetIntValue(obj["row"]),
                                       ScriptRunningMachine.GetIntValue(obj["col"]));
                return(true);
            }

            pos = CellPosition.Empty;
            return(false);
        }
Beispiel #23
0
        /// <summary>
        /// Move backward selection
        /// </summary>
        public void MoveSelectionBackward()
        {
            if (SelectionMovedBackward != null)
            {
                var arg = new SelectionMovedBackwardEventArgs();
                SelectionMovedBackward(this, arg);
                if (arg.IsCancelled)
                {
                    return;
                }
            }

#if EX_SCRIPT
            var scriptReturn = RaiseScriptEvent("onpreviousfocus");
            if (scriptReturn != null && !ScriptRunningMachine.GetBoolValue(scriptReturn))
            {
                return;
            }
#endif

            switch (selectionForwardDirection)
            {
            case SelectionForwardDirection.Right:
            {
                if (selEnd.Col > 0)
                {
                    MoveSelectionLeft();
                }
            }
            break;

            case SelectionForwardDirection.Down:
            {
                if (selEnd.Row > 0)
                {
                    MoveSelectionUp();
                }
            }
            break;
            }
        }
Beispiel #24
0
        private bool RaiseBeforePasteEvent(RangePosition range)
        {
            if (BeforePaste != null)
            {
                var evtArg = new BeforeRangeOperationEventArgs(range);
                BeforePaste(this, evtArg);
                if (evtArg.IsCancelled)
                {
                    return(false);
                }
            }

#if EX_SCRIPT
            object scriptReturn = RaiseScriptEvent("onpaste", new RSRangeObject(this, range));
            if (scriptReturn != null && !ScriptRunningMachine.GetBoolValue(scriptReturn))
            {
                return(false);
            }
#endif // EX_SCRIPT

            return(true);
        }
Beispiel #25
0
        public void ExtendedVariableAccessor()
        {
            var srm = new ScriptRunningMachine();

            var ctx = srm.CreateContext();

            ctx.ExternalVariableGetter = (id) =>
            {
                if (id.StartsWith("$"))
                {
                    return(id.Substring(1));
                }
                else
                {
                    return(null);
                }
            };

            string result = Convert.ToString(srm.CalcExpression("$A1", ctx));

            TestCaseAssertion.AssertEquals(result, "A1");
        }
Beispiel #26
0
        static void Main(string[] args)
        {
            dynamic myobj = new ExpandoObject();

            myobj.name   = "hello";
            myobj.remark = "world";
            myobj.add    = (Func <int, int, int>)((a, b) =>
            {
                return(a + b);
            });

            var srm = new ScriptRunningMachine();

            srm["myobj"] = myobj;

            srm.Run(@"

var str1 = myobj.name + ' ' + myobj.remark;
var str2 = myobj.add(1, 2);
alert(str1 + ' ' + str2);

");
        }
Beispiel #27
0
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            // Attach a property to global object using 'ExternalProperty'.
            //
            // ExternalProperty class provides a chance to do something, The delegate method
            // defined in ExternalProperty will be fired when the property be getted or setted
            // in script running.
            //
            srm.SetGlobalVariable("percent", new ExternalProperty(

                                      // property getter
                                      //
                                      // this will be called when property value is required in script.
                                      () => { return(trackValue.Value); },

                                      // property setter
                                      //
                                      // this will be called when a property value will be setted in script.
                                      (v) => { trackValue.Value = ScriptRunningMachine.GetIntValue(v); }

                                      ));
        }
Beispiel #28
0
        public ReoScriptEditor()
        {
            InitializeComponent();

            newToolStripButton.Click += (s, e) => NewFile();
            newToolStripMenuItem.Click += (s, e) => NewFile();

            openToolStripButton.Click += (s, e) => LoadFile();
            openToolStripMenuItem.Click += (s, e) => LoadFile();

            saveToolStripButton.Click += (s, e) => SaveFile(false);
            saveToolStripMenuItem.Click += (s, e) => SaveFile(false);
            saveAsToolStripMenuItem.Click += (s, e) => SaveFile(true);

            runToolStripButton.Click += (s, e) => RunScript();
            runToolStripMenuItem.Click += (s, e) => RunScript();

            cutToolStripButton.Click += (s, e) => editor.Fctb.Cut();
            cutToolStripMenuItem.Click += (s, e) => editor.Fctb.Cut();

            copyToolStripButton.Click += (s, e) => editor.Fctb.Copy();
            copyToolStripMenuItem.Click += (s, e) => editor.Fctb.Copy();

            pasteToolStripMenuItem.Click += (s, e) => editor.Fctb.Paste();
            pasteToolStripDropDownButton.Click += (s, e) => editor.Fctb.Paste();

            undoToolStripButton.Click += (s, e) => editor.Fctb.Undo();
            undoToolStripMenuItem.Click += (s, e) => editor.Fctb.Undo();

            redoToolStripButton.Click += (s, e) => editor.Fctb.Redo();
            redoToolStripMenuItem.Click += (s, e) => editor.Fctb.Redo();

            using (StreamReader sr = new StreamReader(new MemoryStream(Resources.default_rs)))
            {
                editor.Text = sr.ReadToEnd();
            }

            console.LineReceived += (s, e) =>
            {
                Log("\n");

                if (!string.IsNullOrEmpty(e.Text))
                {
                    try
                    {
                        //string line = e.Text;
                        //if (!line.EndsWith(";")) line += ";";

                        object val = srm.CalcExpression(e.Text);
                        LogValue(val);
                    }
                    catch (Exception ex)
                    {
                        Log("error: " + ex.Message);
                    }
                }
            };

            timer.Tick += (s, e) =>
            {
                bool running = srm == null ? false : srm.IsRunning;

                runToolStripButton.Enabled =
                    runToolStripMenuItem.Enabled =
                    !running;

                stopToolStripButton.Enabled =
                    stopToolStripMenuItem.Enabled =
                    running;

                if (!running)
                {
                    timer.Enabled = false;
                }
            };

            stopToolStripButton.Click += (s, e) => ForceStop();
            stopToolStripMenuItem.Click += (s, e) => ForceStop();

            checkSyntaxStripButton.Click += (s, e) =>
            {
                srm.Compile(editor.Text, r => Log(r.Message));

                if (ScriptCompiled != null)
                {
                    ScriptCompiled(this, null);
                }
            };

            editor.TextChanged += (s, e) =>
            {
                if (ScriptChanged != null)
                {
                    ScriptChanged(this, e);
                }
            };

            Srm = new ScriptRunningMachine();
        }
Beispiel #29
0
        /// <summary>
        /// Copy data and put into Clipboard.
        /// </summary>
        public bool Copy()
        {
            if (IsEditing)
            {
                this.controlAdapter.EditControlCopy();
            }
            else
            {
                this.controlAdapter.ChangeCursor(CursorStyle.Busy);

                try
                {
                    if (BeforeCopy != null)
                    {
                        var evtArg = new BeforeRangeOperationEventArgs(selectionRange);
                        BeforeCopy(this, evtArg);
                        if (evtArg.IsCancelled)
                        {
                            return(false);
                        }
                    }

#if EX_SCRIPT
                    var scriptReturn = RaiseScriptEvent("oncopy");
                    if (scriptReturn != null && !ScriptRunningMachine.GetBoolValue(scriptReturn))
                    {
                        return(false);
                    }
#endif // EX_SCRIPT

                    // highlight current copy range
                    currentCopingRange = selectionRange;

#if WINFORM || WPF
                    DataObject data = new DataObject();
                    data.SetData(ClipBoardDataFormatIdentify,
                                 GetPartialGrid(currentCopingRange, PartialGridCopyFlag.All, ExPartialGridCopyFlag.None, true));

                    string text = StringifyRange(currentCopingRange);
                    if (!string.IsNullOrEmpty(text))
                    {
                        data.SetText(text);
                    }

                    // set object data into clipboard
                    Clipboard.SetDataObject(data);
#endif // WINFORM || WPF

                    if (AfterCopy != null)
                    {
                        AfterCopy(this, new RangeEventArgs(this.selectionRange));
                    }
                }
                catch (Exception ex)
                {
                    this.NotifyExceptionHappen(ex);
                    return(false);
                }
                finally
                {
                    this.controlAdapter.ChangeCursor(CursorStyle.PlatformDefault);
                }
            }

            return(true);
        }
Beispiel #30
0
        /// <summary>
        /// Initial or reset Script Running Machine
        /// </summary>
        private void InitSRM()
        {
            #if DEBUG
            Stopwatch sw = Stopwatch.StartNew();
            #endif

            if (srm == null)
            {
                // create ReoScript instance
                srm = new ScriptRunningMachine();

                // reinit instance when SRM is reset
                srm.Resetted += (s, e) => InitSRM();
            }

            // set control instance into script's context
            if (gridObj == null)
            {
                gridObj = new RSGridObject(this);
            }

            srm["grid"] = gridObj;

            if (formulaCells == null)
            {
                formulaCells = new Dictionary<ReoGridCell, List<ReoGridCell>>();
            }
            else
            {
                formulaCells.Clear();
            }

            if (formulaRanges == null)
            {
                formulaRanges = new Dictionary<ReoGridCell, List<ReferenceRange>>();
            }
            else
            {
                formulaRanges.Clear();
            }

            if (cellIdRegex == null) cellIdRegex = new Regex(@"([A-Z]+)([0-9]+)");

            // setup built-in functions
            RSFunctions.SetupBuiltinFunctions(this, srm);

            // load core library
            using (MemoryStream ms = new MemoryStream(Resources.base_lib))
            {
                srm.Load(ms);
            }

            #if DEBUG
            sw.Stop();
            Debug.WriteLine("init srm takes " + sw.ElapsedMilliseconds + " ms.");
            #endif
        }
Beispiel #31
0
 public void UnloadModule(ScriptRunningMachine srm)
 {
 }
Beispiel #32
0
 public void LoadModule(ScriptRunningMachine srm)
 {
     srm.ImportType(typeof(FileConstructorFunction), "File");
     srm.ImportType(typeof(DirectoryConstructorFunction), "Directory");
 }
Beispiel #33
0
        public bool RunCLRTests()
        {
            Console.WriteLine("Run CLR tests...\n");

            ScriptRunningMachine srm = new ScriptRunningMachine();

            srm.WorkMode |= MachineWorkMode.AllowDirectAccess;

            ScriptDebugger debugMonitor = new ScriptDebugger(srm);

            int testCases = 0, success = 0, failed = 0;
            int createdObjs = 0;

            Stopwatch sw = Stopwatch.StartNew();

            bool hasErrors = false;

            foreach (Type type in this.GetType().Assembly.GetTypes())
            {
                TestSuiteAttribute[] attrs = type.GetCustomAttributes(typeof(TestSuiteAttribute), true) as
                                             TestSuiteAttribute[];

                if (attrs.Length > 0)
                {
                    var testName = attrs[0].Name;
                    if (string.IsNullOrEmpty(testName))
                    {
                        testName = type.Name;
                    }

                    object testSuite = System.Activator.CreateInstance(type);

                    foreach (MethodInfo method in type.GetMethods())
                    {
                        TestCaseAttribute[] caseAttrs = method.GetCustomAttributes(typeof(TestCaseAttribute), false)
                                                        as TestCaseAttribute[];

                        if (caseAttrs.Length > 0 && !caseAttrs[0].Disabled)
                        {
                            testCases++;

                            var caseName = caseAttrs[0].Desc;
                            if (string.IsNullOrEmpty(caseName))
                            {
                                caseName = method.Name;
                            }

                            Console.Write("[{0,-18}] {1,-30} : ", testName, caseName);

                            if (testSuite is ReoScriptTestSuite)
                            {
                                srm.WorkMode = caseAttrs[0].WorkMode;
                                srm.Reset();
                                ((ReoScriptTestSuite)testSuite).SRM = srm;
                            }

                            try
                            {
                                sw.Reset();
                                sw.Start();

                                method.Invoke(testSuite, null);

                                sw.Stop();
                                success++;

                                Console.WriteLine("{0,5} ms. {1,4} objs.", sw.ElapsedMilliseconds,
                                                  debugMonitor.TotalObjectCreated - createdObjs);

                                createdObjs = debugMonitor.TotalObjectCreated;
                            }
                            catch (Exception ex)
                            {
                                failed++;
                                Console.WriteLine(string.IsNullOrEmpty(ex.InnerException.Message) ? "failed" : ex.InnerException.Message);

                                hasErrors = true;
                            }
                            finally
                            {
                                sw.Stop();
                            }
                        }
                    }
                }
            }

            Console.WriteLine("\n    {0,3} test cases, {1,3} successed, {2,3} failed, {3,3} skipped",
                              testCases, success, failed, (testCases - success - failed));
            Console.WriteLine("  {0,5} objects created.\n", debugMonitor.TotalObjectCreated);

            TotalCases         += testCases;
            TotalFailures      += failed;
            TotalSuccesses     += success;
            TotalObjectCreates += debugMonitor.TotalObjectCreated;

            return(hasErrors);
        }
Beispiel #34
0
        public bool RunLanguageTests(List <string> ids, List <string> enabledTags)
        {
            Console.WriteLine("Run Core tests...\n");

            bool hasErrors = false;

            ScriptRunningMachine srm          = new ScriptRunningMachine();
            ScriptDebugger       debugMonitor = new ScriptDebugger(srm);

            int testCases = 0, success = 0, failed = 0;
            int createdObjs = 0;

            foreach (string filename in Directory.GetFiles("tests"))
            {
                XmlTestSuite suite = xmlSuiteSerializer.Deserialize(File.OpenRead(filename)) as XmlTestSuite;

                if (suite != null)
                {
                    testCases += suite.TestCases.Count;
                }

                if (!string.IsNullOrEmpty(suite.Tag))
                {
                    string[] tags = suite.Tag.ToLower().Split(' ');

                    if (!enabledTags.Any(t => tags.Contains(t)))
                    {
                        continue;
                    }
                }

                Stopwatch sw = Stopwatch.StartNew();

                suite.TestCases.ForEach(t =>
                {
                    string caseId = string.Format("{0,3}-{1,3}", suite.Id, t.Id);

                    if (t.Disabled || string.IsNullOrEmpty(t.Script) ||
                        (ids.Count > 0 && !ids.Any(id => caseId.Contains(id))))
                    {
                        return;
                    }

                    srm.Reset();

                    Console.Write("[{0,6} {1,-10}] {2,-30} : ", caseId, suite.Name, t.Name);

                    try
                    {
                        sw.Reset();
                        sw.Start();

                        srm.Run(t.Script);

                        sw.Stop();

                        success++;

                        Console.WriteLine("{0,5} ms. {1,4} objs.", sw.ElapsedMilliseconds,
                                          debugMonitor.TotalObjectCreated - createdObjs);

                        createdObjs = debugMonitor.TotalObjectCreated;
                    }
                    catch (Exception ex)
                    {
                        failed++;
                        Console.WriteLine(string.IsNullOrEmpty(ex.Message) ? "failed"
                                                        : ex.Message);

                        hasErrors = true;
                    }
                    finally
                    {
                        sw.Stop();
                    }
                });

                //Console.WriteLine();
            }

            Console.WriteLine("\n    {0,3} test cases, {1,3} successed, {2,3} failed, {3,3} skipped",
                              testCases, success, failed, (testCases - success - failed));
            Console.WriteLine("  {0,5} objects created.\n", debugMonitor.TotalObjectCreated);

            TotalCases         += testCases;
            TotalFailures      += failed;
            TotalSuccesses     += success;
            TotalObjectCreates += debugMonitor.TotalObjectCreated;

            return(hasErrors);
        }
Beispiel #35
0
        public bool RunCLRTests()
        {
            Console.WriteLine("Run CLR tests...\n");

            ScriptRunningMachine srm = new ScriptRunningMachine();
            srm.WorkMode |= MachineWorkMode.AllowDirectAccess;

            ScriptDebugger debugMonitor = new ScriptDebugger(srm);

            int testCases = 0, success = 0, failed = 0;
            int createdObjs = 0;

            Stopwatch sw = Stopwatch.StartNew();

            bool hasErrors = false;

            foreach (Type type in this.GetType().Assembly.GetTypes())
            {
                TestSuiteAttribute[] attrs = type.GetCustomAttributes(typeof(TestSuiteAttribute), true) as
                    TestSuiteAttribute[];

                if (attrs.Length > 0)
                {
                    var testName = attrs[0].Name;
                    if (string.IsNullOrEmpty(testName)) testName = type.Name;

                    object testSuite = System.Activator.CreateInstance(type);

                    foreach (MethodInfo method in type.GetMethods())
                    {
                        TestCaseAttribute[] caseAttrs = method.GetCustomAttributes(typeof(TestCaseAttribute), false)
                            as TestCaseAttribute[];

                        if (caseAttrs.Length > 0 && !caseAttrs[0].Disabled)
                        {
                            testCases++;

                            var caseName = caseAttrs[0].Desc;
                            if (string.IsNullOrEmpty(caseName)) caseName = method.Name;

                            Console.Write("[{0,-18}] {1,-30} : ", testName, caseName);

                            if (testSuite is ReoScriptTestSuite)
                            {
                                srm.WorkMode = caseAttrs[0].WorkMode;
                                srm.Reset();
                                ((ReoScriptTestSuite)testSuite).SRM = srm;
                            }

                            try
                            {
                                sw.Reset();
                                sw.Start();

                                method.Invoke(testSuite, null);

                                sw.Stop();
                                success++;

                                Console.WriteLine("{0,5} ms. {1,4} objs.", sw.ElapsedMilliseconds,
                                    debugMonitor.TotalObjectCreated - createdObjs);

                                createdObjs = debugMonitor.TotalObjectCreated;
                            }
                            catch (Exception ex)
                            {
                                failed++;
                                Console.WriteLine(string.IsNullOrEmpty(ex.InnerException.Message) ? "failed" : ex.InnerException.Message);

                                hasErrors = true;
                            }
                            finally
                            {
                                sw.Stop();
                            }
                        }
                    }
                }
            }

            Console.WriteLine("\n    {0,3} test cases, {1,3} successed, {2,3} failed, {3,3} skipped",
                testCases, success, failed, (testCases - success - failed));
            Console.WriteLine("  {0,5} objects created.\n", debugMonitor.TotalObjectCreated);

            TotalCases += testCases;
            TotalFailures += failed;
            TotalSuccesses += success;
            TotalObjectCreates += debugMonitor.TotalObjectCreated;

            return hasErrors;
        }
Beispiel #36
0
        public bool RunLanguageTests(List<string> ids, List<string> enabledTags)
        {
            Console.WriteLine("Run Core tests...\n");

            bool hasErrors = false;

            ScriptRunningMachine srm = new ScriptRunningMachine();
            ScriptDebugger debugMonitor = new ScriptDebugger(srm);

            int testCases = 0, success = 0, failed = 0;
            int createdObjs = 0;

            foreach (string filename in Directory.GetFiles("tests"))
            {
                XmlTestSuite suite = xmlSuiteSerializer.Deserialize(File.OpenRead(filename)) as XmlTestSuite;

                if (suite != null)
                {
                    testCases += suite.TestCases.Count;
                }

                if (!string.IsNullOrEmpty(suite.Tag))
                {
                    string[] tags = suite.Tag.ToLower().Split(' ');

                    if (!enabledTags.Any(t => tags.Contains(t)))
                        continue;
                }

                Stopwatch sw = Stopwatch.StartNew();

                suite.TestCases.ForEach(t =>
                {
                    string caseId = string.Format("{0,3}-{1,3}", suite.Id, t.Id);

                    if (t.Disabled || string.IsNullOrEmpty(t.Script)
                        || (ids.Count > 0 && !ids.Any(id => caseId.Contains(id))))
                        return;

                    srm.Reset();

                    Console.Write("[{0,6} {1,-10}] {2,-30} : ", caseId, suite.Name, t.Name);

                    try
                    {
                        sw.Reset();
                        sw.Start();

                        srm.Run(t.Script);

                        sw.Stop();

                        success++;

                        Console.WriteLine("{0,5} ms. {1,4} objs.", sw.ElapsedMilliseconds,
                            debugMonitor.TotalObjectCreated - createdObjs);

                        createdObjs = debugMonitor.TotalObjectCreated;
                    }
                    catch (Exception ex)
                    {
                        failed++;
                        Console.WriteLine(string.IsNullOrEmpty(ex.Message) ? "failed"
                            : ex.Message);

                        hasErrors = true;
                    }
                    finally
                    {
                        sw.Stop();
                    }
                });

                //Console.WriteLine();
            }

            Console.WriteLine("\n    {0,3} test cases, {1,3} successed, {2,3} failed, {3,3} skipped",
                testCases, success, failed, (testCases - success - failed));
            Console.WriteLine("  {0,5} objects created.\n", debugMonitor.TotalObjectCreated);

            TotalCases += testCases;
            TotalFailures += failed;
            TotalSuccesses += success;
            TotalObjectCreates += debugMonitor.TotalObjectCreated;

            return hasErrors;
        }
Beispiel #37
0
 internal static void SetupBuiltinFunctions(ReoGridControl grid, ScriptRunningMachine srm)
 {
     srm["sum"] = new NativeFunctionObject("sum", (ctx, owner, args) => Sum(grid, RSUtility.GetRangeFromArgs(grid, args)));
     srm["SUM"] = new NativeFunctionObject("SUM", (ctx, owner, args) => Sum(grid, RSUtility.GetRangeFromArgs(grid, args)));
     srm["avg"] = new NativeFunctionObject("avg", (ctx, owner, args) => Avg(grid, RSUtility.GetRangeFromArgs(grid, args)));
     srm["AVG"] = new NativeFunctionObject("AVG", (ctx, owner, args) => Avg(grid, RSUtility.GetRangeFromArgs(grid, args)));
     srm["count"] = new NativeFunctionObject("count", (ctx, owner, args) => Count(grid, RSUtility.GetRangeFromArgs(grid, args)));
     srm["COUNT"] = new NativeFunctionObject("COUNT", (ctx, owner, args) => Count(grid, RSUtility.GetRangeFromArgs(grid, args)));
 }
Beispiel #38
0
        static void Main(string[] args)
        {
            if (args.Length == 0)
            {
                Console.WriteLine(
            @"ReoScript(TM) Running Machine
            Copyright(c) 2012-2013 unvell, All Rights Reserved.

            Usage: ReoScript.exe [filename|-workpath|-debug|-exec|-console]");
                return;
            }

            List<string> files = new List<string>();
            string workPath = null;
            bool debug = false;
            string initScript = null;

            bool consoleMode = false;
            bool compileMode = false;

            try
            {
                for (int i = 0; i < args.Length; i++)
                {
                    string arg = args[i];

                    if (arg.StartsWith("-"))
                    {
                        string param = arg.Substring(1);

                        switch (param)
                        {
                            case "workpath":
                                workPath = GetParameter(args, i);
                                i++;
                                break;

                            case "debug":
                                debug = true;
                                break;

                            case "exec":
                                initScript = GetParameter(args, i);
                                i++;
                                break;

                            case "com":
                                compileMode = true;
                                break;

                            case "console":
                                consoleMode = true;
                                break;
                        }
                    }
                    else
                    {
                        files.Add(arg);
                    }
                }
            }
            catch (Exception ex)
            {
                OutLn(ex.Message);
                return;
            }

            List<FileInfo> sourceFiles = new List<FileInfo>();

            foreach (string file in files)
            {
                FileInfo fi = new FileInfo(string.IsNullOrEmpty(workPath)
                    ? file : Path.Combine(workPath, file));

                if (!fi.Exists)
                {
                    Console.WriteLine("Resource not found: " + fi.FullName);
                }
                else
                {
                    sourceFiles.Add(fi);

                    if (string.IsNullOrEmpty(workPath))
                    {
                        workPath = fi.DirectoryName;
                    }
                }
            }

            if (string.IsNullOrEmpty(workPath))
            {
                workPath = Environment.CurrentDirectory;
            }

            // for test!
            if (compileMode)
            {
              using (StreamReader sr = new StreamReader(new FileStream(args[0], FileMode.Open, FileAccess.Read, FileShare.Read)))
              {
                Console.WriteLine(Unvell.ReoScript.Compiler.ReoScriptCompiler.Run(sr.ReadToEnd()));
              }
              return;
            }

            // create SRM
            ScriptRunningMachine srm = new ScriptRunningMachine(CoreFeatures.FullFeatures);
            if (debug)
            {
                new ScriptDebugger(srm);
            }

            // set to full work mode
            srm.WorkMode |= MachineWorkMode.AllowImportTypeInScript
                | MachineWorkMode.AllowCLREventBind
                | MachineWorkMode.AllowDirectAccess;

            // change work path
            srm.WorkPath = workPath;

            // add built-in output listener
            srm.AddStdOutputListener(new BuiltinConsoleOutputListener());

            // not finished yet!
            //srm.SetGlobalVariable("File", new FileConstructorFunction());

            try
            {
                foreach (FileInfo file in sourceFiles)
                {
                    // load script file
                    srm.Run(file);
                }

                if (!string.IsNullOrEmpty(initScript))
                {
                    srm.Run(initScript);
                }
            }
            catch (ReoScriptException ex)
            {
                string str = string.Empty;

                if (ex.ErrorObject == null)
                {
                    str = ex.ToString();
                }
                else if (ex.ErrorObject is ErrorObject)
                {
                    ErrorObject e = (ErrorObject)ex.ErrorObject;

                    str += "Error: " + e.GetFullErrorInfo();
                }
                else
                {
                    str += Convert.ToString(ex.ErrorObject);
                }

                Console.WriteLine(str);
            }

            if (consoleMode)
            {
                OutLn("\nReady.\n");

                bool isQuitRequired = false;

                while (!isQuitRequired)
                {
                    Prompt();

                    string line = In().Trim();
                    if (line == null)
                    {
                        isQuitRequired = true;
                        break;
                    }
                    else if (line.StartsWith("."))
                    {
                        srm.Load(line.Substring(1, line.Length - 1));
                    }
                    else if (line.StartsWith("/"))
                    {
                        string consoleCmd = line.Substring(1);

                        switch (consoleCmd)
                        {
                            case "q":
                            case "quit":
                            case "exit":
                                isQuitRequired = true;
                                break;
                            case "h":
                            case "help":
                                Help();
                                break;
                            default:
                                break;
                        }
                    }
                    else if (line.Equals("?"))
                    {
                        ObjectValue obj = srm.DefaultContext.ThisObject as ObjectValue;
                        if (obj != null) OutLn(obj.DumpObject());
                    }
                    else if (line.StartsWith("?"))
                    {
                        string expression = line.Substring(1);
                        try
                        {
                            object value = srm.CalcExpression(expression);
                            if (value is ObjectValue)
                            {
                                OutLn(((ObjectValue)value).DumpObject());
                            }
                            else
                            {
                                OutLn(ScriptRunningMachine.ConvertToString(value));
                            }
                        }
                        catch (Exception ex)
                        {
                            OutLn("error: " + ex.Message);
                        }
                    }
                    else if (line.Length == 0)
                    {
                        continue;
                    }
                    else
                    {
                        try
                        {
                            srm.Run(line);
                        }
                        catch (ReoScriptException ex)
                        {
                            Console.WriteLine("error: " + ex.Message + "\n");
                        }
                    }
                }

                OutLn("Bye.");
            }
        }