Example #1
0
		/// <summary>Loads all script files in this directory + sub dirs.</summary>
		/// <param name="ScriptListPath">Full pathname of the directory o search in.</param>
		public static void Initialize(string ScriptListPath) {
			ScriptList ScriptEntrys = new ScriptList();
			if (File.Exists(ScriptListPath) == false) {
				ServerConsole.ErrorLine("Can't load File from \"" + ScriptListPath + "\"!");
				return;
			}

			using (FileStream s = File.OpenRead(ScriptListPath)) {
				ScriptEntrys = mXmlSerializer.Deserialize(s) as ScriptList;
			}

			// Build absolute paths and load includes
			string basePath = Path.GetDirectoryName(ScriptListPath);
			for (int i = 0; i < ScriptEntrys.Count; i++) {
				for (int j = 0; j < ScriptEntrys[i].Entrys.Count; j++)
					// Include or path?
					if (ScriptEntrys[i].Entrys[j].Type == EScriptType.Include) {
						string includePath = Path.Combine(Path.GetDirectoryName(ScriptListPath), ScriptEntrys[i].Entrys[j].Path);
						ScriptDatabase.Initialize(includePath);
					} else {
						// Build an absolute path
						ScriptEntrys[i].Entrys[j].Path = Path.Combine(basePath, Path.GetDirectoryName(ScriptEntrys[i].Entrys[j].Path)) + @"\" + Path.GetFileName(ScriptEntrys[i].Entrys[j].Path);
					}
			}

			// Push to static list
			if (ScriptEntrys.Count > 0) {
				Scripts.AddRange(ScriptEntrys);
			}
		}
Example #2
0
        private Function defunImple(Context context, ScriptList arguments, bool addToScope)
        {
            var functionName = ArgumentType<String>(arguments[0]);

            List<ArgumentInfo> argumentInfo = null;
            try
            {
                argumentInfo = ArgumentInfo.ParseArguments(this, ArgumentType<ScriptList>(arguments[1]));
            }
            catch (ScriptError e)
            {
                context.RaiseNewError(e.Message, context.currentNode);
                return null;
            }

            var functionBody = ArgumentType<ParseNode>(arguments[2]);

            var newFunction = new Function(
                functionName,
                argumentInfo,
                "Script-defined function",
                functionBody,
                CopyScope(context.Scope));

            newFunction.shortHelp = ScriptObject.AsString(arguments[3]);

            if (addToScope) newFunction.declarationScope.PushVariable(newFunction.name, newFunction);

            return newFunction;
        }
Example #3
0
        private ScriptObject defunImple(Context context, ScriptList arguments, bool addToScope)
        {
            var functionName = ArgumentType<String>(arguments[0]);

            ScriptList argumentInfo = null;
            try
            {
                argumentInfo = ArgumentType<ScriptList>(arguments[1]);
            }
            catch (ScriptError e)
            {
                context.RaiseNewError(e.Message, context.currentNode);
                return null;
            }

            var functionBody = ArgumentType<ScriptObject>(arguments[2]);

            var newFunction = Function.MakeFunction(
                functionName,
                argumentInfo,
                "Script-defined function",
                functionBody,
                CopyScope(context.Scope));

            if (arguments[3] != null) newFunction["@help"] = ScriptObject.AsString(arguments[3]);

            if (addToScope) (newFunction["declaration-scope"] as Scope).PushVariable(functionName, newFunction);

            return newFunction;
        }
Example #4
0
 public override ScriptList ListProperties()
 {
     var r = new ScriptList();
     r.AddRange(this.GetType().GetFields().Select((info) => info.Name));
     r.AddRange(properties.Select((p) => p.Key));
     return r;
 }
Example #5
0
 static void CollectScriptTable(ScriptList scList, Dictionary <string, ScriptLang> output)
 {
     if (scList == null)
     {
         return;
     }
     //
     foreach (var kv in scList)
     {
         ScriptTable scTable = kv.Value;
         //default and others
         {
             ScriptTable.LangSysTable langSys = scTable.defaultLang;
             ScriptLang sclang = new ScriptLang(scTable.ScriptTagName, langSys.LangSysTagIdenString);
             string     key    = sclang.ToString();
             if (!output.ContainsKey(key))
             {
                 output.Add(key, sclang);
             }
         }
         //
         if (scTable.langSysTables != null && scTable.langSysTables.Length > 0)
         {
             foreach (ScriptTable.LangSysTable langSys in scTable.langSysTables)
             {
                 var    pair = new ScriptLang(scTable.ScriptTagName, langSys.LangSysTagIdenString);
                 string key  = pair.ToString();
                 if (!output.ContainsKey(key))
                 {
                     output.Add(key, pair);
                 }
             }
         }
     }
 }
    public static Script[] ScriptFromJson(string scriptName)
    {
        string     path    = "Jsons/Scripts/" + scriptName;
        ScriptList scripts = JsonUtility.FromJson <ScriptList>((Resources.Load(path, typeof(TextAsset)) as TextAsset).text);

        return(scripts.data);
    }
Example #7
0
 public void StartLuaDrawing()
 {
     if (ScriptList.Any() && GuiLibrary.SurfaceIsNull)
     {
         GuiLibrary.DrawNew("emu");
     }
 }
 private void addScriptButton_Click(object sender, EventArgs e)
 {
     ScriptList.ClearSelection();
     ScriptManager.GetScripts().AddNew();
     ScriptList.Rows[ScriptList.RowCount - 1].Selected = true;
     ScriptList_SelectionChanged(null, null); //needed for linux
 }
Example #9
0
 public void EndLuaDrawing()
 {
     if (ScriptList.Any())
     {
         GuiLibrary.DrawFinish();
     }
 }
Example #10
0
        public static void RedrawScripts()
        {
            ScriptList.SafeAction(s =>
            {
                int curIndex = 0;

                if (s.SelectedIndex > -1)
                {
                    curIndex = s.SelectedIndex;
                }

                s.BeginUpdate();
                s.Items.Clear();

                LoadScripts();

                foreach (RazorScript script in Scripts)
                {
                    if (script != null)
                    {
                        s.Items.Add(script);
                    }
                }

                if (s.Items.Count > 0 && (curIndex - 1 != -1))
                {
                    s.SelectedIndex = curIndex - 1;
                }

                s.EndUpdate();
            });
        }
Example #11
0
        private void Start(object sender, EventArgs e)
        {
            string[] args = ys.Common.GetArgs((string)Argument);

            if (args.Length < 1)
            {
                return;
            }

            // Set fullCmd list.
            for (int i = 0; i < args.Length - 1; i++)
            {
                Script script = new Script(args[i]);
                ScriptList.Add(script);
                btnRunScript.DropDownItems.Insert(
                    btnRunScript.DropDownItems.Count - 1,
                    CreatePathMenuItem(script)
                    );
            }

            if (NavigateOnStartup)
            {
                webBrowser.Navigate(args[args.Length - 1]);
                cbAddress.Text = args[args.Length - 1].Replace("?", "");
            }
        }
Example #12
0
 private void AddScripts(Entity scriptsEntity, ScriptList scriptList, SceneSettings sceneSettings)
 {
     scriptsEntity.AddComponent(new ScriptComponent
     {
         ScriptGroups = CreateMapScriptGroups(scriptList.ScriptGroups, sceneSettings),
         Scripts      = CreateMapScripts(scriptList.Scripts, sceneSettings)
     });
 }
Example #13
0
 public void Close()
 {
     RegisteredFunctions.Clear(_mainForm.Emulator);
     ScriptList.Clear();
     FormsLibrary.DestroyAll();
     _lua.Close();
     _lua = new Lua();
 }
 private void addScriptButton_Click(object sender, EventArgs e)
 {
     ScriptList.ClearSelection();
     ScriptInfo script = ScriptManager.GetScripts().AddNew();
     script.HotkeyCommandIdentifier = ScriptManager.NextHotkeyCommandIdentifier();
     ScriptList.Rows[ScriptList.RowCount - 1].Selected = true;
     ScriptList_SelectionChanged(null, null); // needed for linux
 }
Example #15
0
        public static void RegisterScripts(this PluginContainer pluginContainer, PluginScriptRegistry registry)
        {
            ScriptList scripts = new ScriptList();

            pluginContainer.ExecuteMethod("RegisterScripts", scripts);

            scripts.ForEach(s => registry.Add(pluginContainer.Tag as Plugin, s.Url, psc => s.PageCondition(new ScriptContext(psc))));
        }
Example #16
0
    /// <summary>
    /// 根据文件名制造一个文本框,并纳入字典管理
    /// </summary>
    void CreatFileText(string name)
    {
        var newObj = Instantiate(Origin, _fileListTrans);
        var script = newObj.GetComponent <LevelText>();

        script.Init(name);
        ScriptList.Add(script);
    }
Example #17
0
 public override void Close()
 {
     RegisteredFunctions.Clear(GlobalWin.Emulator);             // TODO: don't use globals
     ScriptList.Clear();
     FormsLibrary.DestroyAll();
     _lua.Close();
     _lua = new Lua();
     GuiLibrary.Dispose();
 }
Example #18
0
 public static ScriptList Args(params Object[] objs)
 {
     var r = new ScriptList();
     foreach (var obj in objs)
     {
         if (obj is ScriptObject) r.Add(obj);
         else if (obj is String) r.Add(Arg(obj.ToString()));
         else throw new InvalidProgramException();
     }
     return r;
 }
Example #19
0
        public void PlayScript(string scriptName)
        {
            Debug.Log("Playing " + scriptName);

            Func <string, Script[]> ScriptFromJson = (string script) => {
                TextAsset textAsset = null;
                DBManager.Instance.LoadScripts(script, out textAsset);
                ScriptList scripts = JsonUtility.FromJson <ScriptList>(textAsset.text);
                return(scripts.data);
            };

            PlayScript(ScriptFromJson(scriptName));
        }
Example #20
0
        public Project()
        {
            //NOP
            sources = new SourceList();

            layers = new BuildLayerList();
            targets = new BuildTargetList();
            terrains = new TerrainList();

            graphs = new FilterGraphList();
            resources = new ResourceList();
            scripts = new ScriptList();
            mogreLocations = new List<MogreLocation>();
        }
        private void moveDownButton_Click(object sender, EventArgs e)
        {
            if (ScriptList.SelectedRows.Count > 0)
            {
                ScriptInfo scriptInfo = ScriptList.SelectedRows[0].DataBoundItem as ScriptInfo;
                int        index      = ScriptManager.GetScripts().IndexOf(scriptInfo);
                ScriptManager.GetScripts().Remove(scriptInfo);
                ScriptManager.GetScripts().Insert(Math.Min(index + 1, ScriptManager.GetScripts().Count), scriptInfo);

                ScriptList.ClearSelection();
                ScriptList.Rows[Math.Max(index + 1, 0)].Selected = true;
                ScriptList.Focus();
            }
        }
Example #22
0
        public Project()
        {
            //NOP
            sources = new SourceList();

            layers   = new BuildLayerList();
            targets  = new BuildTargetList();
            terrains = new TerrainList();

            graphs         = new FilterGraphList();
            resources      = new ResourceList();
            scripts        = new ScriptList();
            mogreLocations = new List <MogreLocation>();
        }
Example #23
0
        public void Close()
        {
            foreach (var closeCallback in RegisteredFunctions
                     .Where(l => l.Event == "OnConsoleClose"))
            {
                closeCallback.Call();
            }

            RegisteredFunctions.Clear(_mainForm.Emulator);
            ScriptList.Clear();
            FormsLibrary.DestroyAll();
            _lua.Close();
            _lua = new Lua();
        }
        public static void AddQueue(ScriptList ListItems, UUID Requester, string GitOwner = "OpenCollarTeam", string GitBranch = "master")
        {
            Queue inst = Queue.Instance;
            List <Queue.QueueType> Queued = new List <Queue.QueueType>();

            foreach (KeyValuePair <string, ScriptList.ScriptListFlags> kvp in ListItems.Scripts)
            {
                Queue.QueueType QT = new Queue.QueueType();
                QT.Name     = kvp.Value.ScriptName;
                QT.GitOwner = GitOwner;

                HttpWebRequest  hwr    = null;
                HttpWebResponse hwresp = null;

                try
                {
                    hwr = (HttpWebRequest)HttpWebRequest.Create("https://raw.githubusercontent.com/" + GitOwner + "/OpenCollar/" + GitBranch + "/src/" + kvp.Value.Container + "/" + kvp.Value.ScriptName + kvp.Value.FileExt);

                    hwr.Method = "GET";
                    hwresp     = (HttpWebResponse)hwr.GetResponse();
                }
                catch (Exception e) { }

                if (hwresp.StatusCode == HttpStatusCode.NotFound)
                {
                    MH(Destinations.DEST_AGENT, Requester, "ALERT: BDF Entry: " + kvp.Value.ScriptName + kvp.Value.FileExt + "; Does not exist on the server!");
                    continue;
                }
                else if (hwresp.StatusCode == HttpStatusCode.OK)
                {
                    // Get the file text and add to queued items
                    StreamReader sr = new StreamReader(hwresp.GetResponseStream());
                    QT.Text = sr.ReadToEnd();
                    //Console.WriteLine("Generating ZHX for string with length : "+QT.Text.Length.ToString());
                    Console.WriteLine("MD5 [" + QT.Name + "] : " + Tools.MD5Hash(QT.Text));
                    QT.Hash = Tools.MD5Hash(QT.Text);
                    //Console.WriteLine("ZHX [" + QT.Name + "] : " + QT.Hash);
                    QT.GitBranch = GitBranch;
                    QT.Container = kvp.Value.Container;
                    QT.ItemType  = kvp.Value.Type;
                    QT.FileExt   = kvp.Value.FileExt;

                    Queued.Add(QT);
                }
            }

            inst.ActualQueue.Add(Requester, Queued);
        }
        /// <summary>
        /// Extracts a list of non text statements from a list of statements
        /// </summary>
        /// <param name="statements">Statement list</param>
        /// <returns>Script statement list</returns>
        private static List <ScriptStatement> ExtractStatementsFromList(ScriptList <ScriptStatement> statements)
        {
            List <ScriptStatement> scriptStatements = new List <ScriptStatement>();

            if (statements == null || !statements.Any())
            {
                return(scriptStatements);
            }

            foreach (ScriptStatement curStatement in statements)
            {
                ExtractStatement(scriptStatements, curStatement);
            }

            return(scriptStatements);
        }
Example #26
0
        private static void DrawScriptList(int index, ScriptList scriptList)
        {
            if (ImGui.TreeNodeEx($"Script List {index}", ImGuiTreeNodeFlags.DefaultOpen))
            {
                foreach (var childGroup in scriptList.ScriptGroups)
                {
                    DrawScriptGroup(childGroup);
                }

                foreach (var script in scriptList.Scripts)
                {
                    DrawScript(script);
                }

                ImGui.TreePop();
            }
        }
Example #27
0
            private static ITreeItem CreateScriptListTreeItem(int index, ScriptList scriptList)
            {
                var treeItem = new TreeItem
                {
                    Text     = $"Script List {index}",
                    Expanded = true
                };

                foreach (var childGroup in scriptList.ScriptGroups)
                {
                    treeItem.Children.Add(CreateScriptGroupTreeItem(childGroup));
                }

                foreach (var script in scriptList.Scripts)
                {
                    treeItem.Children.Add(CreateScriptTreeItem(script));
                }

                return(treeItem);
            }
Example #28
0
        /// <summary>Loads all script files in this directory + sub dirs.</summary>
        /// <param name="ScriptListPath">Full pathname of the directory o search in.</param>
        public static void Initialize(string ScriptListPath)
        {
            ScriptList ScriptEntrys = new ScriptList();

            if (File.Exists(ScriptListPath) == false)
            {
                ServerConsole.ErrorLine("Can't load File from \"" + ScriptListPath + "\"!");
                return;
            }

            using (FileStream s = File.OpenRead(ScriptListPath)) {
                ScriptEntrys = mXmlSerializer.Deserialize(s) as ScriptList;
            }

            // Build absolute paths and load includes
            string basePath = Path.GetDirectoryName(ScriptListPath);

            for (int i = 0; i < ScriptEntrys.Count; i++)
            {
                for (int j = 0; j < ScriptEntrys[i].Entrys.Count; j++)
                {
                    // Include or path?
                    if (ScriptEntrys[i].Entrys[j].Type == EScriptType.Include)
                    {
                        string includePath = Path.Combine(Path.GetDirectoryName(ScriptListPath), ScriptEntrys[i].Entrys[j].Path);
                        ScriptDatabase.Initialize(includePath);
                    }
                    else
                    {
                        // Build an absolute path
                        ScriptEntrys[i].Entrys[j].Path = Path.Combine(basePath, Path.GetDirectoryName(ScriptEntrys[i].Entrys[j].Path)) + @"\" + Path.GetFileName(ScriptEntrys[i].Entrys[j].Path);
                    }
                }
            }

            // Push to static list
            if (ScriptEntrys.Count > 0)
            {
                Scripts.AddRange(ScriptEntrys);
            }
        }
Example #29
0
        public static void Initialize(string ScriptListPath)
        {
            ScriptList ScriptEntrys = new ScriptList();

            if (File.Exists(ScriptListPath) == false)
            {
                CConsole.ErrorLine("Can't load File from \"" + ScriptListPath + "\"!");
                return;
            }

            using (FileStream s = File.OpenRead(ScriptListPath))
                ScriptEntrys = mXmlSerializer.Deserialize(s) as ScriptList;

            string basePath = Path.GetDirectoryName(ScriptListPath);

            for (int i = 0; i < ScriptEntrys.Count; i++)
            {
                for (int j = 0; j < ScriptEntrys[i].Entrys.Count; j++)
                {
                    if (ScriptEntrys[i].Entrys[j].Type == EScriptType.Include)
                    {
                        ScriptDatabase.Initialize(Path.Combine(Path.GetDirectoryName(ScriptListPath), ScriptEntrys[i].Entrys[j].Path));
                    }
                    else
                    {
                        // fixx Directory
                        ScriptEntrys[i].Entrys[j].Path = Path.Combine(basePath, Path.GetDirectoryName(ScriptEntrys[i].Entrys[j].Path)) + @"\" + Path.GetFileName(ScriptEntrys[i].Entrys[j].Path);
                    }
                }
            }

            if (ScriptEntrys.Count > 0)
            {
                Scripts.AddRange(ScriptEntrys);
            }
        }
Example #30
0
 public static ScriptObject MakeSystemFunction(
     String name, 
     ScriptList arguments,
     String help,
     Func<Context, ScriptList, Object> func)
 {
     return new GenericScriptObject(
         "@name", name,
         "@arguments", arguments,
         "@help", help,
         "@function-body", func);
 }
Example #31
0
        private void SetupLoopFunctions()
        {
            AddFunction("map", "variable_name list code : Transform one list into another",
                (context, arguments) =>
                {
                    var vName = ArgumentType<String>(arguments[0]);
                    var list = ArgumentType<System.Collections.IEnumerable>(arguments[1]);
                    var code = ArgumentType<ScriptObject>(arguments[2]);
                    var result = new ScriptList();
                    context.Scope.PushVariable(vName, null);
                    foreach (var item in list)
                    {
                        context.Scope.ChangeVariable(vName, item);
                        result.Add(Evaluate(context, code, true));
                        if (context.evaluationState == EvaluationState.UnwindingBreak)
                        {
                            context.Scope.PopVariable(vName);
                            return context.UnBreak();
                        }
                    }
                    context.Scope.PopVariable(vName);
                    return result;
                },
                Arguments.Mutator(Arguments.Lazy("variable-name"), "(@identifier value)"),
                Arguments.Arg("in"),
                Arguments.Lazy("code"));

            AddFunction("mapi", "Like map, except the variable will hold the index.",
                (context, arguments) =>
                {
                    var vName = ArgumentType<String>(arguments[0]);
                    var from = AutoBind.IntArgument(arguments[1]);
                    var to = AutoBind.IntArgument(arguments[2]);
                    var code = ArgumentType<ScriptObject>(arguments[3]);
                    var result = new ScriptList();
                    context.Scope.PushVariable(vName, null);
                    for (int i = from; i < to; ++i)
                    {
                        context.Scope.ChangeVariable(vName, i);
                        result.Add(Evaluate(context, code, true));
                        if (context.evaluationState == EvaluationState.UnwindingBreak)
                        {
                            context.Scope.PopVariable(vName);
                            return context.UnBreak();
                        }
                    }
                    context.Scope.PopVariable(vName);
                    return result;
                },
                Arguments.Mutator(Arguments.Lazy("variable-name"), "(@identifier value)"),
                Arguments.Arg("from"),
                Arguments.Arg("to"),
                Arguments.Lazy("code"));

            AddFunction("mapex",
                "variable_name start code next : Like map, but the next element is the result of 'next'. Stops when next = null.",
                (context, arguments) =>
                {
                    var vName = ArgumentType<String>(arguments[0]);
                    var code = ArgumentType<ScriptObject>(arguments[2]);
                    var next = ArgumentType<ScriptObject>(arguments[3]);
                    var result = new ScriptList();
                    var item = arguments[1];
                    context.Scope.PushVariable(vName, null);

                    while (item != null)
                    {
                        context.Scope.ChangeVariable(vName, item);
                        result.Add(Evaluate(context, code, true));
                        if (context.evaluationState == EvaluationState.UnwindingBreak)
                        {
                            context.Scope.PopVariable(vName);
                            return context.UnBreak();
                        }
                        item = Evaluate(context, next, true);
                    }

                    context.Scope.PopVariable(vName);
                    return result;
                },
                Arguments.Mutator(Arguments.Lazy("variable-name"), "(@identifier value)"),
                Arguments.Arg("start"),
                Arguments.Lazy("code"),
                Arguments.Lazy("next"));

            AddFunction("for",
                "variable_name list code : Execute code for each item in list. Returns result of last run of code.",
                (context, arguments) =>
                {
                    var vName = ArgumentType<String>(arguments[0]);
                    var list = ArgumentType<System.Collections.IEnumerable>(arguments[1]);
                    var func = ArgumentType<ScriptObject>(arguments[2]);
                    context.Scope.PushVariable(vName, null);
                    Object result = null;
                    foreach (var item in list)
                    {
                        context.Scope.ChangeVariable(vName, item);
                        result = Evaluate(context, func, true);
                        if (context.evaluationState == EvaluationState.UnwindingBreak)
                        {
                            context.Scope.PopVariable(vName);
                            return context.UnBreak();
                        }
                    }

                    context.Scope.PopVariable(vName);

                    return result;
                },
                Arguments.Mutator(Arguments.Lazy("variable-name"), "(@identifier value)"),
                Arguments.Arg("list"),
                Arguments.Lazy("code"));

            AddFunction("fori",
                "variable_name list code : Execute code for each item in list. Returns result of last run of code.",
                (context, arguments) =>
                {
                    var vName = ArgumentType<String>(arguments[0]);
                    var from = AutoBind.IntArgument(arguments[1]);
                    var to = AutoBind.IntArgument(arguments[2]);
                    var func = ArgumentType<ScriptObject>(arguments[3]);
                    context.Scope.PushVariable(vName, null);
                    Object result = null;
                    for (int i = from; i < to; ++i)
                    {
                        context.Scope.ChangeVariable(vName, i);
                        result = Evaluate(context, func, true);
                        if (context.evaluationState == EvaluationState.UnwindingBreak)
                        {
                            context.Scope.PopVariable(vName);
                            return context.UnBreak();
                        }
                    }

                    context.Scope.PopVariable(vName);

                    return result;
                },
                Arguments.Mutator(Arguments.Lazy("variable-name"), "(@identifier value)"),
                Arguments.Arg("from"),
                Arguments.Arg("to"),
                Arguments.Lazy("code"));

            AddFunction("while",
                "condition code : Repeat code while condition evaluates to true.",
                (context, arguments) =>
                {
                    var cond = ArgumentType<ScriptObject>(arguments[0]);
                    var code = ArgumentType<ScriptObject>(arguments[1]);

                    while (context.evaluationState == EvaluationState.Normal && Evaluate(context, cond, true) != null)
                        if (context.evaluationState == EvaluationState.Normal) Evaluate(context, code, true);
                    if (context.evaluationState == EvaluationState.UnwindingBreak) return context.UnBreak();
                    return null;
                },
                Arguments.Lazy("condition"),
                Arguments.Lazy("code"));
        }
 private void ScriptInfoEdit_Validating(object sender, System.ComponentModel.CancelEventArgs e)
 {
     ScriptInfoFromEdits();
     ScriptList.Refresh();
 }
 public void RegisterScripts(ScriptList scripts)
 {
     scripts.Add("base.js", "ListForAdmin");
     scripts.Add("base.js", "Item");
 }
Example #34
0
        public static Object Invoke(ScriptObject func, Engine engine, Context context, ScriptList arguments)
        {
            var name = func.gsp("@name");
            var argumentInfo = func["@arguments"] as ScriptList;

            if (context.trace != null)
            {
                context.trace(new String('.', context.traceDepth) + "Entering " + name +"\n");
                context.traceDepth += 1;
            }

            var newArguments = new ScriptList();
            //Check argument types
            if (argumentInfo.Count == 0 && arguments.Count != 0)
            {
                context.RaiseNewError("Function expects no arguments.", context.currentNode);
                return null;
            }

                int argumentIndex = 0;
                for (int i = 0; i < argumentInfo.Count; ++i)
                {
                    var info = argumentInfo[i] as ScriptObject;
                    if (info == null)
                        throw new ScriptError("Invalid argument descriptor on function object", context.currentNode);
                    if (info["@repeat"] != null)
                    {
                        var list = new ScriptList();
                        while (argumentIndex < arguments.Count) //Handy side effect: If no argument is passed for an optional repeat
                        {                                       //argument, it will get an empty list.
                            list.Add(MutateArgument(arguments[argumentIndex], info, engine, context));
                            //list.Add((info["@type"] as Type).ProcessArgument(context, arguments[argumentIndex]));
                            if (context.evaluationState != EvaluationState.Normal) return null;
                            ++argumentIndex;
                        }
                        newArguments.Add(list);
                    }
                    else
                    {
                        if (argumentIndex < arguments.Count)
                        {
                            newArguments.Add(MutateArgument(arguments[argumentIndex], info, engine, context));
                            //newArguments.Add((info["@type"] as Type).ProcessArgument(context, arguments[argumentIndex]));
                            if (context.evaluationState == EvaluationState.UnwindingError) return null;
                        }
                        else if (info["@optional"] != null)
                            newArguments.Add(MutateArgument(null, info, engine, context));
                        else
                        {
                            context.RaiseNewError("Not enough arguments to " + name, context.currentNode);
                            return null;
                        }
                        ++argumentIndex;
                    }
                }
                if (argumentIndex < arguments.Count)
                {
                    context.RaiseNewError("Too many arguments to " + name, context.currentNode);
                    return null;
                }

            Object r = null;

            if (func["@function-body"] is ScriptObject)
            {
                var declarationScope = func["@declaration-scope"];
                if (declarationScope is GenericScriptObject)
                {
                    var newScope = new Scope();
                    foreach (var valueName in (declarationScope as GenericScriptObject).properties)
                        newScope.PushVariable(valueName.Key, valueName.Value);
                    func["@declaration-scope"] = newScope;
                }

                context.PushScope(func["@declaration-scope"] as Scope);

                for (int i = 0; i < argumentInfo.Count; ++i)
                    context.Scope.PushVariable((argumentInfo[i] as ScriptObject).gsp("@name"), newArguments[i]);

                r = engine.Evaluate(context, func["@function-body"], true);

                for (int i = 0; i < argumentInfo.Count; ++i)
                    context.Scope.PopVariable((argumentInfo[i] as ScriptObject).gsp("@name"));

                context.PopScope();
            }
            else
            {
                try
                {
                    r = (func["@function-body"] as Func<Context, ScriptList, Object>)(context, newArguments);
                }
                catch (Exception e)
                {
                    context.RaiseNewError("System Exception: " + e.Message, context.currentNode);
                    return null;
                }
            }

            if (context.trace != null)
            {
                context.traceDepth -= 1;
                context.trace(new String('.', context.traceDepth) + "Leaving " + name +
                    (context.evaluationState == EvaluationState.UnwindingError ?
                    (" -Error: " + context.errorObject.GetLocalProperty("message").ToString()) :
                    "") +
                    (context.evaluationState == EvaluationState.UnwindingBreak ? " -Breaking" : "") +
                    "\n");
            }

            return r;
        }
Example #35
0
        private void evaluateNodeChild(bool callFunction, Object child, ScriptList arguments, Context context)
        {
            bool lazyArgument = false;
            var prefix = (child as ScriptObject).gsp("@prefix");

            if (callFunction && arguments.Count > 0 && (Function.IsFunction(arguments[0] as ScriptObject)))
            {
                var argumentInfo = Function.GetArgumentInfo(arguments[0] as ScriptObject, context, arguments.Count - 1);
                if (context.evaluationState != EvaluationState.Normal) return;
                lazyArgument = argumentInfo["@lazy"] != null;
            }

            if (lazyArgument && prefix != ":" && prefix != "#")
                arguments.Add(child);
            else
            {
                var argument = Evaluate(context, child);
                if (context.evaluationState != EvaluationState.Normal) return;
                if (prefix == "$" && argument is ScriptList)
                    arguments.AddRange(argument as ScriptList);
                else
                    arguments.Add(argument);
            }
        }
Example #36
0
        public Object Evaluate(
            Context context,
            Object what,
            bool ignoreStar = false,
            bool discardResults = false)
        {
            if (context.evaluationState != EvaluationState.Normal)
                throw new ScriptError("Invalid Context", null);
            if (context.callDepth >= context.maximumCallDepth)
            {
                context.RaiseNewError("Overflow.", null);
                return null;
            }

            context.callDepth += 1; //All exit points must decrement depth.

            if (what is String)
            {
                var r = EvaluateString(context, what as String, "", discardResults);
                context.callDepth -= 1;
                return r;
            }
            else if (!(what is ScriptObject))
            {
                context.callDepth -= 1;
                return what;
            }

            var node = what as ScriptObject;
            context.currentNode = node;

            if (context.limitExecutionTime && (DateTime.Now - context.executionStart > context.allowedExecutionTime))
            {
                context.RaiseNewError("Timeout.", node);
                context.callDepth -= 1;
                return null;
            }

            if (node.gsp("@prefix") == "*" && !ignoreStar) //Object is a quoted node
            {
                context.callDepth -= 1;
                return node;
            }

            var type = node.gsp("@type");
            if (String.IsNullOrEmpty(type))
            {
                context.callDepth -= 1;
                return node;
            } //Object is not evaluatable code.

            object result = null;

            if (type == "string")
            {
                result = node["@token"];
            }
            else if (type == "stringexpression")
            {
                if (discardResults) //Don't bother assembling the string expression.
                {
                    foreach (var piece in node._children)
                    {
                        if ((piece as ScriptObject).gsp("@type") == "string")
                            continue;
                        else
                        {
                            Evaluate(context, piece);
                            if (context.evaluationState != EvaluationState.Normal)
                            {
                                context.callDepth -= 1;
                                return null;
                            }
                        }
                    }
                    result = null;
                }
                else
                {
                    if (node._children.Count == 1) //If there's only a single item, the result is that item.
                    {
                        result = Evaluate(context, node._child(0));
                        if (context.evaluationState != EvaluationState.Normal)
                        {
                            context.callDepth -= 1;
                            return null;
                        }
                    }
                    else
                    {
                        var resultString = String.Empty;
                        foreach (var piece in node._children)
                        {
                            resultString += ScriptObject.AsString(Evaluate(context, piece));
                            if (context.evaluationState != EvaluationState.Normal)
                            {
                                context.callDepth -= 1;
                                return null;
                            }
                        }
                        result = resultString;
                    }
                }
            }
            else if (type == "token")
            {
                result = LookupToken(context, node.gsp("@token"));
                if (context.evaluationState != EvaluationState.Normal)
                {
                    context.callDepth -= 1;
                    return null;
                }
            }
            else if (type == "memberaccess")
            {
                var lhs = Evaluate(context, node._child(0));
                if (context.evaluationState != EvaluationState.Normal)
                { context.callDepth -= 1; return null; }
                String rhs = "";

                if ((node._child(1) as ScriptObject).gsp("@type") == "token")
                    rhs = (node._child(1) as ScriptObject).gsp("@token");
                else
                    rhs = ScriptObject.AsString(Evaluate(context, node._child(1), false));
                if (context.evaluationState != EvaluationState.Normal) { context.callDepth -= 1; return null; }

                if (lhs == null) result = null;
                else if (lhs is ScriptObject)
                {
                    result = (lhs as ScriptObject).GetProperty(ScriptObject.AsString(rhs));
                    if (node.gsp("@token") == ":")
                    {
                        context.Scope.PushVariable("this", lhs);
                        result = Evaluate(context, result, true, false);
                        context.Scope.PopVariable("this");
                        if (context.evaluationState != EvaluationState.Normal)
                        { context.callDepth -= 1; return null; }
                    }
                }
                else
                {
                    var field = lhs.GetType().GetField(ScriptObject.AsString(rhs));
                    if (field != null)
                        result = field.GetValue(lhs);
                    else
                    {
                        var prop = lhs.GetType().GetProperty(ScriptObject.AsString(rhs));
                        if (prop != null)
                            result = prop.GetValue(lhs, null);
                        else
                        {
                            var members = lhs.GetType().FindMembers(System.Reflection.MemberTypes.Method,
                                System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance,
                                new System.Reflection.MemberFilter((minfo, obj) => { return minfo.Name == obj.ToString(); }),
                                ScriptObject.AsString(rhs));
                            if (members.Length != 0)
                            {
                                result = new GenericScriptObject(
                                    "@lazy-reflection", ScriptObject.AsString(rhs),
                                    "@source-object", lhs,
                                    "@source-type", lhs.GetType());
                            }
                            else
                                result = null;
                        }
                    }
                }
            }
            else if (type == "node")
            {
                if (!ignoreStar && node.gsp("@prefix") == "*")
                {
                    result = node;
                }
                else
                {

                    bool eval = node.gsp("@prefix") != "^";

                    var arguments = new ScriptList();

                    foreach (var child in node._children)
                    {
                        evaluateNodeChild(eval, child, arguments, context);
                        if (context.evaluationState != EvaluationState.Normal)
                        {
                            context.callDepth -= 1;
                            return null;
                        }
                    }

                    if (node.gsp("@prefix") == "^") result = arguments;
                    else
                    {
                        if (arguments.Count > 0 && Function.IsFunction(arguments[0] as ScriptObject))
                        {

                            result = Function.Invoke((arguments[0] as ScriptObject), this, context,
                                new ScriptList(arguments.GetRange(1, arguments.Count - 1)));
                            if (context.evaluationState != EvaluationState.Normal)
                            {
                                if (context.evaluationState == EvaluationState.UnwindingError)
                                    context.PushStackTrace((arguments[0] as ScriptObject).gsp("@name"));
                                context.callDepth -= 1;
                                return null;
                            }

                        }
                        else if (arguments.Count > 0 &&
                            arguments[0] is ScriptObject &&
                            (arguments[0] as ScriptObject).GetProperty("@lazy-reflection") != null)
                        {
                            var sObj = arguments[0] as ScriptObject;
                            var argumentTypes = arguments.GetRange(1, arguments.Count - 1).Select(
                                (obj) => obj.GetType()).ToArray();
                            var sourceObject = sObj.GetProperty("@source-object");
                            var method = (sObj.GetProperty("@source-type") as System.Type)
                                .GetMethod(sObj.gsp("@lazy-reflection"), argumentTypes);
                            if (method == null)
                                throw new ScriptError("Could not find overload for " +
                                    sObj.gsp("@lazy-reflection") + " that takes argument types " +
                                    String.Join(", ", argumentTypes.Select((t) => t.Name)) + " on type " +
                                    sObj.GetProperty("@source-type").ToString(), what as ScriptObject);
                            result = method.Invoke(sourceObject, arguments.GetRange(1, arguments.Count - 1).ToArray());
                        }
                        else if (arguments.Count > 0)
                            result = arguments[0];
                        else
                            result = null;
                    }
                }
            }
            else if (type == "root")
            {
                var results = new ScriptList();
                foreach (var child in node._children)
                {
                    results.Add(Evaluate(context, child, false, false));
                    if (context.evaluationState != EvaluationState.Normal)
                        {
                            context.callDepth -= 1;
                            return null;
                        }
                    }
                return results;
            }
            else if (type == "number")
            {
                try
                {
                    if (node.gsp("@token").Contains('.')) result = Convert.ToSingle(node.gsp("@token"));
                    else result = Convert.ToInt32(node.gsp("@token"));
                }
                catch (Exception e)
                {
                    context.RaiseNewError("Number format error.", node);
                    { context.callDepth -= 1; return null; }
                }
            }
            else if (type == "char")
            {
                context.callDepth -= 1;
                return node.gsp("@token")[0];
            }
            else
            {
                context.RaiseNewError("Internal evaluator error.", node);
                { context.callDepth -= 1; return null; }
            }

            if (node.gsp("@prefix") == ":" && !ignoreStar)
                result = Evaluate(context, result);
            if (context.evaluationState != EvaluationState.Normal) { context.callDepth -= 1; return null; };
            if (node.gsp("@prefix") == ".") result = LookupToken(context, ScriptObject.AsString(result));
            context.callDepth -= 1;
            return result;
        }
Example #37
0
        private void SetupStringFunctions()
        {
            AddFunction("split", "Split a string into pieces", (context, arguments) =>
                {
                    var pieces = AutoBind.StringArgument(arguments[0]).Split(
                        new String[] { AutoBind.StringArgument(arguments[1]) },
                        Int32.MaxValue, StringSplitOptions.RemoveEmptyEntries);
                    var r = new ScriptList(pieces);
                    return r;
                }, Arguments.Arg("string"), Arguments.Arg("split-chars"));

            AddFunction("strlen", "string : Returns length of string.",
                (context, arguments) =>
                {
                    return ScriptObject.AsString(arguments[0]).Length;
                }, Arguments.Arg("string"));

            AddFunction("strind",
                "string n : Returns nth element in string.",
                (context, arguments) =>
                {
                    var index = arguments[1] as int?;
                    if (index == null || !index.HasValue) return null;
                    if (index.Value < 0) return null;
                    var str = ScriptObject.AsString(arguments[0]);
                        if (index.Value >= str.Length) return null;
                        return str[index.Value];
                },
                Arguments.Arg("string"),
                Arguments.Arg("n"));

            AddFunction("substr", "Returns a portion of the input string.",
                (context, arguments) =>
                {
                    var str = ScriptObject.AsString(arguments[0]);
                    var start = AutoBind.IntArgument(arguments[1]);
                    if (arguments[2] == null) return str.Substring(start);
                    else return str.Substring(start, AutoBind.IntArgument(arguments[2]));
                },
                    Arguments.Arg("string"),
                    Arguments.Arg("start"),
                    Arguments.Optional("length"));

            AddFunction("strcat", "Concatenate many strings into one.",
                (context, arguments) =>
                    {
                        var r = new StringBuilder();
                        foreach (var obj in AutoBind.ListArgument(arguments[0]))
                            r.Append(ScriptObject.AsString(obj));
                        return r.ToString();
                    },
                    Arguments.Repeat("item"));

            AddFunction("itoa", "Change a number to the string representation.",
                (context, arguments) =>
                {
                    return arguments[0].ToString();
                },
                Arguments.Arg("i"));

            AddFunction("atoi", "",
                (context, arguments) =>
                {
                    return Convert.ToInt32(arguments[0]);
                },
                Arguments.Arg("i"));

            AddFunction("unescape", "", (context, arguments) =>
            {
                return Console.UnescapeString(ScriptObject.AsString(arguments[0]));
            },
            Arguments.Arg("string"));

            AddFunction("format", "Format a string.",
                (context, arguments) =>
                {
                    return String.Format(AutoBind.StringArgument(arguments[0]),
                        AutoBind.ListArgument(arguments[1]).ToArray());
                },
                Arguments.Arg("format-string"),
                Arguments.Optional(Arguments.Repeat("value")));
        }
Example #38
0
        private void SetupStandardLibrary()
        {
            //types.Add("STRING", new TypeString());
            //types.Add("INTEGER", new TypePrimitive(typeof(int), true));
            //types.Add("LIST", new TypeList());
            //types.Add("OBJECT", new TypePrimitive(typeof(ScriptObject), false));
            //types.Add("CODE", new TypePrimitive(typeof(ScriptObject), false));
            //types.Add("IDENTIFIER", new TypeString());
            //types.Add("FUNCTION", new TypePrimitive(typeof(ScriptObject), false));
            //types.Add("ANYTHING", Type.Anything);
            //types.Add("FLOAT", new TypePrimitive(typeof(float), true));

            //foreach (var type in types)
            //    type.Value.Typename = type.Key;

            specialVariables.Add("null", (c) => { return null; });
            specialVariables.Add("functions", (c) => { return new ScriptList(functions.Select((pair) => { return pair.Value; })); });
            specialVariables.Add("true", (c) => { return true; });
            specialVariables.Add("false", (c) => { return null; });
            specialVariables.Add("@scope", (c) => { return c.Scope; });

            //AddFunction("net-module", "Loads a module from a .net assembly",
            //    (context, arguments) =>
            //    {
            //        NetModule.LoadModule(context, this, ScriptObject.AsString(arguments[0]), ScriptObject.AsString(arguments[1]));
            //        return null;
            //    }, "string assembly", "string module");

            AddFunction("@list", "If the argument is a list, great. If not, now it is.",
                (context, arguments) =>
                {
                    if (arguments[0] == null) return new ScriptList();
                    if (arguments[0] is ScriptList) return arguments[0];
                    return new ScriptList(arguments[0]);
                },
                    Arguments.Arg("value"));

            AddFunction("@lazy-list", "Mutates a lazy argument into a list. Effectively makes the ^ optional.",
                (context, arguments) =>
                {
                    var node = arguments[0] as ScriptObject;
                    if (node == null) return new ScriptList();
                    var r = new ScriptList();
                    foreach (var child in node._children)
                        r.Add(Evaluate(context, child));
                    return r;
                }, Arguments.Arg("arg"));

            AddFunction("@identifier", "Mutates a lazy argument. If it's a token, return as a string. If not, evaluate and return as a string.",
                (context, arguments) =>
                {
                    var arg = arguments[0] as ScriptObject;
                    if (arg != null && arg.gsp("@type") == "token") return arg.gsp("@token");
                    return ScriptObject.AsString(Evaluate(context, arg, true));
                }, Arguments.Arg("arg"));

            AddFunction("@identifier-if-token", "Mutates a lazy argument. If it's a token, return as a string. If not, evaluate and return.",
               (context, arguments) =>
               {
                   var arg = arguments[0] as ScriptObject;
                   if (arg != null && arg.gsp("@type") == "token") return arg.gsp("@token");
                   return Evaluate(context, arg, true);
               }, Arguments.Arg("arg"));

            AddFunction("arg", "create an argument", (context, arguments) =>
            {
                if (arguments[0] is ScriptObject)
                    return arguments[0];
                else return Arguments.Arg(ScriptObject.AsString(arguments[0]));
            }, Arguments.Mutator(Arguments.Lazy("name"), "(@identifier value)"));

            AddFunction("arg-lazy", "create a lazy argument", (context, arguments) =>
                {
                    if (arguments[0] is ScriptObject)
                    {
                        (arguments[0] as ScriptObject)["@lazy"] = true;
                        return arguments[0];
                    }
                    else return Arguments.Lazy(Arguments.Arg(ScriptObject.AsString(arguments[0])));
                }, Arguments.Mutator(Arguments.Lazy("name"), "(@identifier-if-token value)"));

            AddFunction("arg-optional", "create an optional argument", (context, arguments) =>
            {
                if (arguments[0] is ScriptObject)
                {
                    (arguments[0] as ScriptObject)["@optional"] = true;
                    return arguments[0];
                }
                else return Arguments.Optional(Arguments.Arg(ScriptObject.AsString(arguments[0])));
            }, Arguments.Mutator(Arguments.Lazy("name"), "(@identifier-if-token value)"));

            AddFunction("arg-repeat", "create a repeat argument", (context, arguments) =>
            {
                if (arguments[0] is ScriptObject)
                {
                    (arguments[0] as ScriptObject)["@repeat"] = true;
                    return arguments[0];
                }
                else return Arguments.Repeat(Arguments.Arg(ScriptObject.AsString(arguments[0])));
            }, Arguments.Mutator(Arguments.Lazy("name"), "(@identifier-if-token value)"));

            AddFunction("arg-mutator", "Add a mutator to an argument", (context, arguments) =>
                {
                    if (arguments[0] is ScriptObject)
                    {
                        (arguments[0] as ScriptObject)["@mutator"] = arguments[1];
                        return arguments[0];
                    }
                    else
                    {
                        var r = Arguments.Arg(ScriptObject.AsString(arguments[0]));
                        r["@mutator"] = arguments[1];
                        return r;
                    }
                }, Arguments.Mutator(Arguments.Lazy("name"), "(@identifier-if-token value)"), Arguments.Lazy("mutator"));

            AddFunction("eval", "Evaluates it's argument.",
                (context, arguments) =>
                {
                    return Evaluate(context, arguments[0], true);
                },
                    Arguments.Arg("arg"));

            AddFunction("lastarg", "Returns last argument",
                (context, arguments) =>
                {
                    return (arguments[0] as ScriptList).LastOrDefault();
                },
                    Arguments.Repeat("child"));

            AddFunction("nop", "Returns null.",
                (context, arguments) => { return null; },
                Arguments.Optional(Arguments.Repeat("value")));

            AddFunction("coalesce", "B if A is null, A otherwise.",
                (context, arguments) =>
                {
                    if (arguments[0] == null)
                        return Evaluate(context, arguments[1], true, false);
                    else
                        return arguments[0];
                },
                Arguments.Arg("A"), Arguments.Lazy("B"));

            AddFunction("raise-error", "Raises a new error.",
                (context, arguments) =>
                {
                    context.RaiseNewError(MISP.ScriptObject.AsString(arguments[0]), context.currentNode);
                    return null;
                },
                Arguments.Arg("message"));

            AddFunction("catch-error", "Evaluate and return A unless error generated; if error Evaluate and return B.",
                (context, arguments) =>
                {
                    var result = Evaluate(context, arguments[0], true, false);
                    if (context.evaluationState == EvaluationState.UnwindingError)
                    {
                        context.evaluationState = EvaluationState.Normal;
                        return Evaluate(context, arguments[1], true, false);
                    }
                    return result;
                },
                    Arguments.Lazy("good"),
                    Arguments.Lazy("bad"));

            AddFunction("break", "Aborts loops and supplies a return value.",
                (context, arguments) =>
                {
                    context.evaluationState = EvaluationState.UnwindingBreak;
                    context.breakObject = arguments[0];
                    return null;
                }, Arguments.Arg("value"));

            AddFunction("reflect", "Examine an object using .net reflection.",
                (context, arguments) =>
                {
                    var stream = new System.IO.StringWriter();
                    if (arguments[0] == null) stream.Write("null\n");
                    else
                    {
                        stream.Write(arguments[0].GetType().Name + "\n");
                        foreach (var field in arguments[0].GetType().GetFields())
                            stream.Write("field: " + field.Name + " " + field.FieldType.Name + "\n");
                        foreach (var method in arguments[0].GetType().GetMethods())
                            stream.Write("method: " + method.Name + " " + method.ReturnType.Name + "\n");
                    }
                    return stream.ToString();
                }, Arguments.Arg("object"));

            AddFunction("lazy-overloads", "Examine all possible overloads of a lazy binding.",
                (context, arguments) =>
                {
                    var binding = arguments[0] as ScriptObject;
                    var stream = new System.IO.StringWriter();
                    if (binding.GetProperty("@lazy-reflection") == null) stream.Write("Not a lazy binding object.");
                    else
                    {
                        var sourceType = binding.GetProperty("@source-type") as System.Type;
                        var methods = sourceType.GetMethods().Where((m) => m.Name == binding.gsp("@lazy-reflection"));
                        stream.Write("Methods found:\n");
                        foreach (var method in methods)
                        {
                            stream.Write("args: ");
                            stream.Write(String.Join(" ", method.GetParameters().Select((p) => p.ParameterType.Name)));
                            stream.Write("\n");
                        }
                    }
                    return stream.ToString();
                }, Arguments.Arg("object"));

            AddFunction("emitt", "Emit in tight-formatting style.",
                (context, arguments) =>
                {
                    return TightFormat(arguments[0]);
                }, Arguments.Arg("object", "Meant for use with objects generated via AutoBind."));

            AddFunction("emitf", "Emit a function",
                (context, arguments) =>
                {
                    var stream = new System.IO.StringWriter();
                    var obj = arguments[0] as ScriptObject;
                    stream.Write("Name: ");
                    stream.Write(obj.gsp("@name") + "\nHelp: " + obj.gsp("@help") + "\nArguments: \n");
                    foreach (var arg_ in obj["@arguments"] as ScriptList)
                    {
                        stream.Write("   ");
                        var arg = arg_ as ScriptObject;
                        //stream.Write((arg["@type"] as Type).Typename + " ");
                        if (arg["@optional"] != null) stream.Write("?");
                        if (arg["@repeat"] != null) stream.Write("+");
                        if (arg["@lazy"] != null) stream.Write("*");
                        stream.Write(arg["@name"] + "  ");
                        if (arg["@mutator"] != null) Engine.SerializeCode(stream, arg["@mutator"] as ScriptObject);
                        if (arg["@help"] != null) stream.Write(" - " + arg["@help"].ToString());
                        stream.Write("\n");
                    }
                    stream.Write("\nBody: ");
                    if (obj["@function-body"] is ScriptObject)
                        Engine.SerializeCode(stream, obj["@function-body"] as ScriptObject);
                    else
                        stream.Write("System");
                    stream.Write("\n");
                    return stream.ToString();
                },
                Arguments.Arg("func", "Must be a function."));

            AddFunction("serialize", "Serialize an object",
                (context, arguments) =>
                {
                    var stream = new System.IO.StringWriter();
                    SerializeObject(stream, arguments[0] as ScriptObject);
                    return stream.ToString();
                },
                    Arguments.Arg("object"));

            SetupVariableFunctions();
            SetupObjectFunctions();
            SetupMathFunctions();
            SetupFunctionFunctions();
            SetupBranchingFunctions();
            SetupLoopFunctions();
            SetupListFunctions();
            SetupStringFunctions();
            SetupEncryptionFunctions();
            SetupFileFunctions();
            SetupRegexFunctions();
        }
Example #39
0
        /// <summary>
        /// Position glyphs according to features defined in the font.
        /// </summary>
        /// <param name="Font">In: Font access interface</param>
        /// <param name="workspace">In: Workspace for layout engine</param>
        /// <param name="ScriptTag">In: Script tag</param>
        /// <param name="LangSysTag">In: LangSys tag</param>
        /// <param name="Metrics">In: LayoutMetrics</param>
        /// <param name="FeatureSet">In: List of features to apply</param>
        /// <param name="featureCount">In: Actual number of features in <paramref name="FeatureSet"/></param>
        /// <param name="featureSetOffset">In: offset of input characters inside FeatureSet</param>
        /// <param name="CharCount">In: Characters count (i.e. <paramref name="Charmap"/>.Length);</param>
        /// <param name="Charmap">In: Char to glyph mapping</param>
        /// <param name="Glyphs">In/out: List of GlyphInfo structs</param>
        /// <param name="Advances">In/out: Glyphs adv.widths</param>
        /// <param name="Offsets">In/out: Glyph offsets</param>
        /// <returns>Substitution result</returns>
        internal static OpenTypeLayoutResult PositionGlyphs(
            IOpenTypeFont Font,
            OpenTypeLayoutWorkspace workspace,
            uint ScriptTag,
            uint LangSysTag,
            LayoutMetrics Metrics,
            Feature[]               FeatureSet,
            int featureCount,
            int featureSetOffset,
            int CharCount,
            UshortList Charmap,
            GlyphInfoList Glyphs,
            int *Advances,
            LayoutOffset *Offsets
            )
        {
            try
            {
                FontTable GposTable = Font.GetFontTable(OpenTypeTags.GPOS);
                if (!GposTable.IsPresent)
                {
                    return(OpenTypeLayoutResult.ScriptNotFound);
                }

                GPOSHeader GposHeader = new GPOSHeader(0);
                ScriptList ScriptList = GposHeader.GetScriptList(GposTable);

                ScriptTable Script = ScriptList.FindScript(GposTable, ScriptTag);
                if (Script.IsNull)
                {
                    return(OpenTypeLayoutResult.ScriptNotFound);
                }

                LangSysTable LangSys = Script.FindLangSys(GposTable, LangSysTag);
                if (LangSys.IsNull)
                {
                    return(OpenTypeLayoutResult.LangSysNotFound);
                }

                FeatureList FeatureList = GposHeader.GetFeatureList(GposTable);
                LookupList  LookupList  = GposHeader.GetLookupList(GposTable);

                LayoutEngine.ApplyFeatures(
                    Font,
                    workspace,
                    OpenTypeTags.GPOS,
                    GposTable,
                    Metrics,
                    LangSys,
                    FeatureList,
                    LookupList,
                    FeatureSet,
                    featureCount,
                    featureSetOffset,
                    CharCount,
                    Charmap,
                    Glyphs,
                    Advances,
                    Offsets
                    );
            }
            catch (FileFormatException)
            {
                return(OpenTypeLayoutResult.BadFontTable);
            }

            return(OpenTypeLayoutResult.Success);
        }
Example #40
0
/* This is unused code, but will be used later so it is just commented out for now.
 *
 *      /// <summary>
 *      /// Enumerates scripts in a font
 *      /// </summary>
 *      internal static OpenTypeLayoutResult GetScriptList (
 *          IOpenTypeFont       Font,     // In: Font access interface
 *          out TagInfo[]       Scripts   // Out: Array of scripts supported
 *          )
 *      {
 *          ushort i;
 *          ushort GposNewTags;
 *
 *          Scripts=null; // Assignment required, because of out attribute.
 *                        // This value should be owerwritten later.
 *
 *          try
 *          {
 *              FontTable GsubTable = Font.GetFontTable(OpenTypeTags.GSUB);
 *              FontTable GposTable = Font.GetFontTable(OpenTypeTags.GPOS);
 *
 *              GSUBHeader GsubHeader = new GSUBHeader(0);
 *              GPOSHeader GposHeader = new GPOSHeader(0);
 *
 *              ScriptList GsubScriptList;
 *              ScriptList GposScriptList;
 *              ushort GsubScriptCount;
 *              ushort GposScriptCount;
 *
 *              if (GsubTable.IsNotPresent && GposTable.IsNotPresent)
 *              {
 *                  Scripts = Array.Empty<TagInfo>();
 *                  return OpenTypeLayoutResult.Success;
 *              }
 *
 *              if (GsubTable.IsPresent)
 *              {
 *                  GsubScriptList  = GsubHeader.GetScriptList(GsubTable);
 *                  GsubScriptCount = GsubScriptList.GetScriptCount(GsubTable);
 *              }
 *              else
 *              {
 *                  GsubScriptList = new ScriptList(FontTable.InvalidOffset);
 *                  GsubScriptCount = 0;
 *              }
 *
 *              if (GposTable.IsPresent)
 *              {
 *                  GposScriptList  = GposHeader.GetScriptList(GposTable);
 *                  GposScriptCount = GposScriptList.GetScriptCount(GposTable);
 *              }
 *              else
 *              {
 *                  GposScriptList = new ScriptList(FontTable.InvalidOffset);
 *                  GposScriptCount = 0;
 *              }
 *
 *              //This is true in most cases that there is no new tags in GPOS.
 *              //So, we allocate this array then check GPOS for new tags
 *              Scripts = new TagInfo[GsubScriptCount];
 *
 *              for(i=0; i<GsubScriptCount; i++)
 *              {
 *                  Scripts[i].Tag      = GsubScriptList.GetScriptTag(GsubTable,i);
 *                  Scripts[i].TagFlags = TagInfoFlags.Substitution;
 *              }
 *
 *              //Check GPOS for tags that is not in GSUB
 *              GposNewTags=0;
 *
 *              for(i=0;i<GposScriptCount;i++)
 *              {
 *                  uint GposTag = GsubScriptList.GetScriptTag(GposTable,i);
 *                  if (TagInfo.IsNewTag(Scripts,GposTag)) GposNewTags++;
 *              }
 *
 *              //append new tags to ScriptTags if any exists
 *              if (GposNewTags>0)
 *              {
 *                  int CurrentScriptIndex=GposScriptCount;
 *
 *                  //Allocate new array to fit all tags
 *                  TagInfo[] tmp = Scripts;
 *                  Scripts = new TagInfo[GsubScriptCount+GposNewTags];
 *                  Array.Copy(tmp,0,Scripts,0,tmp.Length);
 *
 *                  for(i=0;i<GposScriptCount;i++)
 *                  {
 *                      uint GposTag = GsubScriptList.GetScriptTag(GposTable,i);
 *                      if (TagInfo.IsNewTag(Scripts,GposTag))
 *                      {
 *                          Scripts[CurrentScriptIndex].Tag=GposTag;
 *                          Scripts[CurrentScriptIndex].TagFlags
 *                              = TagInfoFlags.Positioning;
 ++CurrentScriptIndex;
 *                      }
 *                      else
 *                      {
 *                          int ScriptIndex = TagInfo.GetTagIndex(Scripts,GposTag);
 *                          Scripts[ScriptIndex].TagFlags |= TagInfoFlags.Positioning;
 *                      }
 *                  }
 *
 *                  Debug.Assert(CurrentScriptIndex==Scripts.Length);
 *              }
 *          }
 *          catch (FileFormatException)
 *          {
 *              return OpenTypeLayoutResult.BadFontTable;
 *          }
 *
 *          return OpenTypeLayoutResult.Success;
 *      }
 *
 *
 *      ///<summary>
 *      /// Enumerates language systems for script
 *      /// </summary>
 *      internal static OpenTypeLayoutResult  GetLangSysList (
 *          IOpenTypeFont   Font,       // In: Font access interface
 *          uint            ScriptTag,  // In: Script tag
 *          out TagInfo[]   LangSystems // Out: Array of LangSystems for Script
 *          )
 *      {
 *          ushort i;
 *          ushort GposNewTags;
 *
 *          LangSystems=null; // Assignment required, because of out attribute.
 *                            // This value should be owerwritten later.
 *
 *          try
 *          {
 *              FontTable GsubTable = Font.GetFontTable(OpenTypeTags.GSUB);
 *              FontTable GposTable = Font.GetFontTable(OpenTypeTags.GPOS);
 *
 *              GSUBHeader GsubHeader = new GSUBHeader(0);
 *              GPOSHeader GposHeader = new GPOSHeader(0);
 *
 *              ScriptList GsubScriptList;
 *              ScriptList GposScriptList;
 *              ScriptTable GsubScript;
 *              ScriptTable GposScript;
 *              ushort GsubLangSysCount;
 *              ushort GposLangSysCount;
 *
 *              if (GsubTable.IsNotPresent && GposTable.IsNotPresent)
 *              {
 *                  return OpenTypeLayoutResult.ScriptNotFound;
 *              }
 *
 *              if (GsubTable.IsPresent)
 *              {
 *                  GsubScriptList = GsubHeader.GetScriptList(GsubTable);
 *                  GsubScript = GsubScriptList.FindScript(GsubTable,ScriptTag);
 *              }
 *              else
 *              {
 *                  GsubScript = new ScriptTable(FontTable.InvalidOffset);
 *              }
 *
 *              if (GposTable.IsPresent)
 *              {
 *                  GposScriptList  = GposHeader.GetScriptList(GposTable);
 *                  GposScript = GposScriptList.FindScript(GposTable,ScriptTag);
 *              }
 *              else
 *              {
 *                  GposScript = new ScriptTable(FontTable.InvalidOffset);
 *              }
 *
 *              if (GsubScript.IsNull && GposScript.IsNull)
 *              {
 *                  return OpenTypeLayoutResult.ScriptNotFound;
 *              }
 *
 *              if (!GsubScript.IsNull)
 *              {
 *                  GsubLangSysCount = GsubScript.GetLangSysCount(GsubTable);
 *              }
 *              else
 *              {
 *                  GsubLangSysCount = 0;
 *              }
 *
 *              if (!GposScript.IsNull)
 *              {
 *                  GposLangSysCount = GposScript.GetLangSysCount(GposTable);
 *              }
 *              else
 *              {
 *                  GposLangSysCount = 0;
 *              }
 *
 *              //This is true in most cases that there is no new tags in GPOS.
 *              //So, we allocate this array then check GPOS for new tags
 *              ushort CurrentLangSysIndex;
 *
 *              if (GsubScript.IsDefaultLangSysExists(GsubTable))
 *              {
 *                  LangSystems = new TagInfo[GsubLangSysCount+1];
 *                  LangSystems[0].Tag      = (uint)OpenTypeTags.dflt;
 *                  LangSystems[0].TagFlags = TagInfoFlags.Substitution;
 *                  CurrentLangSysIndex = 1;
 *              }
 *              else
 *              {
 *                  LangSystems = new TagInfo[GsubLangSysCount];
 *                  CurrentLangSysIndex = 0;
 *              }
 *
 *              for(i=0; i<GsubLangSysCount; i++)
 *              {
 *                  LangSystems[CurrentLangSysIndex].Tag = GsubScript.GetLangSysTag(GsubTable,i);
 *                  LangSystems[CurrentLangSysIndex].TagFlags = TagInfoFlags.Substitution;
 ++CurrentLangSysIndex;
 *              }
 *
 *              //Check GPOS for tags that is not in GSUB
 *              GposNewTags=0;
 *
 *              if (!GposScript.IsNull)
 *              {
 *                  if (GposScript.IsDefaultLangSysExists(GposTable) &&
 *                      TagInfo.IsNewTag(LangSystems,(uint)OpenTypeTags.dflt))
 *                  {
 ++GposNewTags;
 *                  }
 *
 *                  for(i=0;i<GposLangSysCount;i++)
 *                  {
 *                      uint GposTag = GsubScript.GetLangSysTag(GposTable,i);
 *                      if (TagInfo.IsNewTag(LangSystems,GposTag))
 *                      {
 ++GposNewTags;
 *                      }
 *                  }
 *              }
 *
 *              Debug.Assert(CurrentLangSysIndex==LangSystems.Length);
 *
 *              //append new tags to ScriptTags if any exists
 *              if (GposNewTags>0)
 *              {
 *                  //Allocate new array to fit all tags
 *                  TagInfo[] tmp = LangSystems;
 *                  LangSystems = new TagInfo[GsubLangSysCount+GposNewTags];
 *                  Array.Copy(tmp,0,LangSystems,0,tmp.Length);
 *
 *                  if (GposScript.IsDefaultLangSysExists(GposTable))
 *                  {
 *                      if (TagInfo.IsNewTag(LangSystems,(uint)OpenTypeTags.dflt))
 *                      {
 *                          LangSystems[CurrentLangSysIndex].Tag = (uint)OpenTypeTags.dflt;
 *                          LangSystems[CurrentLangSysIndex].TagFlags = TagInfoFlags.Positioning;
 ++CurrentLangSysIndex;
 *                      }
 *                      else
 *                      {
 *                          int LangSysIndex = TagInfo.GetTagIndex(LangSystems,(uint)OpenTypeTags.dflt);
 *                          LangSystems[LangSysIndex].TagFlags |= TagInfoFlags.Positioning;
 *                      }
 *                  }
 *
 *                  for(i=0;i<GposLangSysCount;i++)
 *                  {
 *                      uint GposTag = GposScript.GetLangSysTag(GposTable,i);
 *
 *                      if (TagInfo.IsNewTag(LangSystems,GposTag))
 *                      {
 *                          LangSystems[CurrentLangSysIndex].Tag = GposTag;
 *                          LangSystems[CurrentLangSysIndex].TagFlags = TagInfoFlags.Positioning;
 ++CurrentLangSysIndex;
 *                      }
 *                      else
 *                      {
 *                          int LangSysIndex = TagInfo.GetTagIndex(LangSystems,GposTag);
 *                          LangSystems[LangSysIndex].TagFlags |= TagInfoFlags.Positioning;
 *                      }
 *                  }
 *
 *                  Debug.Assert(CurrentLangSysIndex==LangSystems.Length);
 *              }
 *          }
 *          catch (FileFormatException)
 *          {
 *              return OpenTypeLayoutResult.BadFontTable;
 *          }
 *
 *          return OpenTypeLayoutResult.Success;
 *      }
 *
 *
 *      /// <summary>
 *      /// Enumerates features in a language system
 *      /// </summary>
 *      internal static OpenTypeLayoutResult  GetFeatureList (
 *          IOpenTypeFont   Font,           // In: Font access interface
 *          uint            ScriptTag,      // In: Script tag
 *          uint            LangSysTag,     // In: LangSys tag
 *          out TagInfo[]   Features        // Out: Array of features
 *          )
 *      {
 *          ushort i;
 *          ushort GposNewTags;
 *
 *          Features=null; // Assignment required, because of out attribute.
 *                         // This value should be owerwritten later.
 *
 *          try
 *          {
 *              FontTable GsubTable = Font.GetFontTable(OpenTypeTags.GSUB);
 *              FontTable GposTable = Font.GetFontTable(OpenTypeTags.GPOS);
 *
 *              GSUBHeader GsubHeader = new GSUBHeader(0);
 *              GPOSHeader GposHeader = new GPOSHeader(0);
 *
 *              ScriptList GsubScriptList;
 *              ScriptList GposScriptList;
 *              ScriptTable GsubScript;
 *              ScriptTable GposScript;
 *              LangSysTable GsubLangSys;
 *              LangSysTable GposLangSys;
 *              ushort GsubFeatureCount;
 *              ushort GposFeatureCount;
 *              FeatureList GsubFeatureList;
 *              FeatureList GposFeatureList;
 *
 *
 *              if (GsubTable.IsNotPresent && GposTable.IsNotPresent)
 *              {
 *                  return OpenTypeLayoutResult.ScriptNotFound;
 *              }
 *
 *              if (GsubTable.IsPresent)
 *              {
 *                  GsubScriptList  = GsubHeader.GetScriptList(GsubTable);
 *                  GsubScript      = GsubScriptList.FindScript(GsubTable,ScriptTag);
 *                  GsubLangSys     = GsubScript.FindLangSys(GsubTable,LangSysTag);
 *                  GsubFeatureList = GsubHeader.GetFeatureList(GsubTable);
 *              }
 *              else
 *              {
 *                  GsubScript = new ScriptTable(FontTable.InvalidOffset);
 *                  GsubLangSys = new LangSysTable(FontTable.InvalidOffset);
 *                  GsubFeatureList = new FeatureList(FontTable.InvalidOffset);
 *              }
 *
 *              if (GposTable.IsPresent)
 *              {
 *                  GposScriptList  = GposHeader.GetScriptList(GposTable);
 *                  GposScript      = GposScriptList.FindScript(GposTable,ScriptTag);
 *                  GposLangSys     = GposScript.FindLangSys(GposTable,LangSysTag);
 *                  GposFeatureList = GposHeader.GetFeatureList(GposTable);
 *              }
 *              else
 *              {
 *                  GposScript = new ScriptTable(FontTable.InvalidOffset);
 *                  GposLangSys = new LangSysTable(FontTable.InvalidOffset);
 *                  GposFeatureList = new FeatureList(FontTable.InvalidOffset);
 *              }
 *
 *              if (GsubScript.IsNull && GposScript.IsNull)
 *              {
 *                  return OpenTypeLayoutResult.ScriptNotFound;
 *              }
 *
 *              if (GsubLangSys.IsNull && GposLangSys.IsNull)
 *              {
 *                  return OpenTypeLayoutResult.LangSysNotFound;
 *              }
 *
 *              if (!GsubLangSys.IsNull)
 *              {
 *                  GsubFeatureCount = GsubLangSys.FeatureCount(GsubTable);
 *              }
 *              else
 *              {
 *                  GsubFeatureCount = 0;
 *              }
 *
 *              if (!GposLangSys.IsNull)
 *              {
 *                  GposFeatureCount = GposLangSys.FeatureCount(GposTable);
 *              }
 *              else
 *              {
 *                  GposFeatureCount = 0;
 *              }
 *
 *              Features = new TagInfo[GsubFeatureCount];
 *              int CurrentFeatureIndex = 0;
 *
 *              for(i=0; i<GsubFeatureCount; i++)
 *              {
 *                  ushort FeatureIndex = GsubLangSys.GetFeatureIndex(GsubTable,i);
 *                  Features[CurrentFeatureIndex].Tag = GsubFeatureList.FeatureTag(GsubTable,FeatureIndex);
 *                  Features[CurrentFeatureIndex].TagFlags = TagInfoFlags.Substitution;
 ++CurrentFeatureIndex;
 *              }
 *
 *              Debug.Assert(CurrentFeatureIndex==Features.Length);
 *
 *              //Check GPOS for tags that is not in GSUB
 *              GposNewTags=0;
 *              if (!GposLangSys.IsNull)
 *              {
 *                  for(i=0;i<GposFeatureCount;i++)
 *                  {
 *                      ushort FeatureIndex = GposLangSys.GetFeatureIndex(GposTable,i);
 *                      uint GposTag = GposFeatureList.FeatureTag(GposTable,FeatureIndex);
 *                      if (TagInfo.IsNewTag(Features,GposTag))
 *                      {
 ++GposNewTags;
 *                      }
 *                  }
 *              }
 *
 *              //append new tags to ScriptTags if any exists
 *              if (GposNewTags>0)
 *              {
 *                  //Allocate new array to fit all tags
 *                  TagInfo[] tmp = Features;
 *                  Features = new TagInfo[GsubFeatureCount+GposNewTags];
 *                  Array.Copy(tmp,0,Features,0,tmp.Length);
 *
 *                  for(i=0;i<GposFeatureCount;i++)
 *                  {
 *                      ushort FeatureIndex = GposLangSys.GetFeatureIndex(GposTable,i);
 *                      uint GposTag = GposFeatureList.FeatureTag(GposTable,FeatureIndex);
 *
 *                      if (TagInfo.IsNewTag(Features,GposTag))
 *                      {
 *                          Features[CurrentFeatureIndex].Tag = GposTag;
 *                          Features[CurrentFeatureIndex].TagFlags = TagInfoFlags.Positioning;
 ++CurrentFeatureIndex;
 *                      }
 *                      else
 *                      {
 *                          int Index = TagInfo.GetTagIndex(Features,GposTag);
 *                          Features[Index].TagFlags |= TagInfoFlags.Positioning;
 *                      }
 *                  }
 *
 *                  Debug.Assert(CurrentFeatureIndex==Features.Length);
 *              }
 *
 *
 *          }
 *          catch (FileFormatException)
 *          {
 *              return OpenTypeLayoutResult.BadFontTable;
 *          }
 *
 *          return OpenTypeLayoutResult.Success;
 *      }
 */

        /// <summary>
        /// Substitutes glyphs according to features defined in the font.
        /// </summary>
        /// <param name="Font">In: Font access interface</param>
        /// <param name="workspace">In: Workspace for layout engine</param>
        /// <param name="ScriptTag">In: Script tag</param>
        /// <param name="LangSysTag">In: LangSys tag</param>
        /// <param name="FeatureSet">In: List of features to apply</param>
        /// <param name="featureCount">In: Actual number of features in <paramref name="FeatureSet"/></param>
        /// <param name="featureSetOffset">In: offset of input characters inside FeatureSet</param>
        /// <param name="CharCount">In: Characters count (i.e. <paramref name="Charmap"/>.Length);</param>
        /// <param name="Charmap">In/out: Char to glyph mapping</param>
        /// <param name="Glyphs">In/out: List of GlyphInfo structs</param>
        /// <returns>Substitution result</returns>
        internal static OpenTypeLayoutResult SubstituteGlyphs(
            IOpenTypeFont Font,                     // In: Font access interface
            OpenTypeLayoutWorkspace workspace,      // In: Workspace for layout engine
            uint ScriptTag,                         // In: Script tag
            uint LangSysTag,                        // In: LangSys tag
            Feature[]               FeatureSet,     // In: List of features to apply
            int featureCount,                       // In: Actual number of features in FeatureSet
            int featureSetOffset,
            int CharCount,                          // In: Characters count (i.e. Charmap.Length);
            UshortList Charmap,                     // In/out: Char to glyph mapping
            GlyphInfoList Glyphs                    // In/out: List of GlyphInfo structs
            )
        {
            try
            {
                FontTable GsubTable = Font.GetFontTable(OpenTypeTags.GSUB);
                if (!GsubTable.IsPresent)
                {
                    return(OpenTypeLayoutResult.ScriptNotFound);
                }

                GSUBHeader GsubHeader = new GSUBHeader(0);
                ScriptList ScriptList = GsubHeader.GetScriptList(GsubTable);

                ScriptTable Script = ScriptList.FindScript(GsubTable, ScriptTag);
                if (Script.IsNull)
                {
                    return(OpenTypeLayoutResult.ScriptNotFound);
                }

                LangSysTable LangSys = Script.FindLangSys(GsubTable, LangSysTag);
                if (LangSys.IsNull)
                {
                    return(OpenTypeLayoutResult.LangSysNotFound);
                }

                FeatureList FeatureList = GsubHeader.GetFeatureList(GsubTable);
                LookupList  LookupList  = GsubHeader.GetLookupList(GsubTable);

                LayoutEngine.ApplyFeatures(
                    Font,
                    workspace,
                    OpenTypeTags.GSUB,
                    GsubTable,
                    new LayoutMetrics(), //it is not needed for substitution
                    LangSys,
                    FeatureList,
                    LookupList,
                    FeatureSet,
                    featureCount,
                    featureSetOffset,
                    CharCount,
                    Charmap,
                    Glyphs,
                    null,
                    null
                    );
            }
            catch (FileFormatException)
            {
                return(OpenTypeLayoutResult.BadFontTable);
            }

            return(OpenTypeLayoutResult.Success);
        }
Example #41
0
        public static ScriptObject MakeFunction(
            String name, 
            ScriptList arguments,
            String help,
            ScriptObject body,
            ScriptObject declarationScope,
            bool copyScope = false)
        {
            if (copyScope)
            {
                var newScope = new Scope();
                foreach (var prop in declarationScope.ListProperties())
                    newScope.PushVariable(prop as String, declarationScope.GetLocalProperty(prop as String));
                declarationScope = newScope;
            }

            return new GenericScriptObject(
                "@name", name,
                "@arguments", arguments,
                "@help", help,
                "@function-body", body,
                "@declaration-scope", declarationScope);
        }
Example #42
0
 public DebugListView(ScriptList <TScriptNode> collection)
 {
     this._collection = collection;
 }
Example #43
0
        internal void Update(OS2Table os2Tabble, Meta meta, GSUB gsub, GPOS gpos)
        {
            //https://docs.microsoft.com/en-us/typography/opentype/spec/os2#ur


            //This field is used to specify the Unicode blocks or ranges encompassed by the font file in 'cmap' subtables for platform 3,
            //encoding ID 1 (Microsoft platform, Unicode BMP) and platform 3,
            //encoding ID 10 (Microsoft platform, Unicode full repertoire).
            //If a bit is set (1), then the Unicode ranges assigned to that bit are considered functional.
            //If the bit is clear (0), then the range is not considered functional.

            //unicode BMP (Basic Multilingual Plane),OR plane0 (see https://unicode.org/roadmaps/bmp/)

            //Each of the bits is treated as an independent flag and the bits can be set in any combination.
            //The determination of “functional” is left up to the font designer,
            //although character set selection should attempt to be functional by ranges if at all possible.

            //--------------
            //Different versions of the OS/2 table were created when different Unicode versions were current,
            //and the initial specification for a given version defined fewer bit assignments than for later versions.
            //Some applications may not support all assignments for fonts that have earlier OS/2 versions.

            //All of the bit assignments listed above are valid for any version of the OS/2 table,
            //though OS/2 versions 1 and 2 were specified with some assignments that did not correspond to well-defined Unicode ranges and
            //that conflict with later assignments — see the details below.
            //If a font has a version 1 or version 2 OS/2 table with one of these bits set,
            //the obsolete assignment may be the intended interpretation.
            //Because these assignments do not correspond to well-defined ranges,
            //however, the implied character coverage is unclear.

            //Version 0: When version 0 was first specified, no bit assignments were defined.
            //Some applications may ignore these fields in a version 0 OS/2 table.

            //Version 1:
            //Version 1 was first specified concurrent with Unicode 1.1,
            //and bit assigments were defined for bits 0 to 69 only. With fonts that have a version 1 table,
            //some applications might recognize only bits 0 to 69.

            //Also, version 1 was specified with some bit assignments that did not correspond to a well-defined Unicode range:

            //    Bit 8: “Greek Symbols and Coptic” (bit 7 was specified as “Basic Greek”)
            //    Bit 12: “Hebrew Extended” (bit 11 was specified as “Basic Hebrew”)
            //    Bit 14: “Arabic Extended” (bit 13 was specified as “Basic Arabic”)
            //    Bit 27: “Georgian Extended” (bit 26 was specified as “Basic Georgian”)

            //These assignments were discontinued as of version 2.

            //In addition, versions 1 and 2 were defined with bit 53 specified as “CJK Miscellaneous”,
            //which also does not correspond to any well-defined Unicode range.
            //This assignment was discontinued as of version 3.

            //Version 2:
            //Version 2 was defined in OpenType 1.1, which was concurrent with Unicode 2.1.
            //At that time, bit assignments were defined for bits 0 to 69 only.
            //Bit assignments for version 2 were updated in OpenType 1.3,
            //adding assignments for bits 70 to 83 corresponding to new blocks assigned in Unicode 2.0 and Unicode 3.0.
            //With fonts that have a version 2 table,
            //some applications might recognize only those bits assigned in OpenType 1.2 or OpenType 1.3.

            //Also, the specification for version 2 continued to use a problematic assignment for bit 53 —
            //see details for version 1. This assignment was discontinued as of version 3.

            //Version 3: Version 3 was defined in OpenType 1.4 with assignments for bits 84 to 91 corresponding to additional
            //ranges in Unicode 3.2.
            //In addition, some already-assigned bits were extended to cover additional Unicode ranges for related characters; s
            //ee details in the table above.

            //Version 4: Version 4 was defined in OpenType 1.5 with assignments for bit 58 and bits 92 to 122 corresponding to additional ranges in Unicode 5.1.
            //Also, bits 8, 12, 14, 27 and 53 were re-assigned (see version 1 for previous assignments).
            //In addition, some already-assigned bits were extended to cover additional Unicode ranges for related characters;
            //see details in the table above.

            OS2Version    = os2Tabble.version;
            UnicodeRange1 = os2Tabble.ulUnicodeRange1;
            UnicodeRange2 = os2Tabble.ulUnicodeRange2;
            UnicodeRange3 = os2Tabble.ulUnicodeRange3;
            UnicodeRange4 = os2Tabble.ulUnicodeRange4;
            //ULONG     ulUnicodeRange1     Bits 0-31
            //ULONG     ulUnicodeRange2     Bits 32-63
            //ULONG     ulUnicodeRange3     Bits 64-95
            //ULONG     ulUnicodeRange4     Bits 96-127



            //-------
            //IMPORTANT:***
            //All available bits were exhausted as of Unicode 5.1.  ***
            //The bit assignments were last updated for OS/2 version 4 in OpenType 1.5.
            //There are many additional ranges supported in the current version of Unicode that are not supported by these fields in the OS/2 table.
            //
            //See the 'dlng' and 'slng' tags in the 'meta' table for an alternate mechanism to declare
            //what scripts or languages that a font can support or is designed for.
            //-------


            if (meta != null)
            {
                SupportedLangs = meta.SupportedLanguageTags;
                DesignLangs    = meta.DesignLanguageTags;
            }

            //----
            //gsub and gpos contains actual script_list that are in the typeface
            GSUBScriptList = gsub?.ScriptList;
            GPOSScriptList = gpos?.ScriptList;
        }
Example #44
0
 private MapScriptCollection CreateScripts(ScriptList scriptList)
 {
     return(new MapScriptCollection(
                CreateMapScriptGroups(scriptList.ScriptGroups),
                CreateMapScripts(scriptList.Scripts)));
 }
Example #45
0
        private static ScriptList children(ScriptObject obj)
        {
            var list = obj["@children"];
            if (list == null)
            {
                list = new ScriptList();
                obj["@children"] = list;
            }

            return list as ScriptList;
        }