From: <che...@us...> - 2008-04-21 23:01:35
|
Revision: 1690 http://mp-plugins.svn.sourceforge.net/mp-plugins/?rev=1690&view=rev Author: chef_koch Date: 2008-04-21 16:01:33 -0700 (Mon, 21 Apr 2008) Log Message: ----------- added GUIScript from mp svn Added Paths: ----------- trunk/plugins/GUIScript/ trunk/plugins/GUIScript/!!! DO NOT CHANGE ANY FILES HERE - PLEASE UPDATE THE FILES IN MP-PLUGINS SVN !!! trunk/plugins/GUIScript/ExpressionEval.cs trunk/plugins/GUIScript/FunctionEval.cs trunk/plugins/GUIScript/GUIScript.cs trunk/plugins/GUIScript/MPScript.cs trunk/plugins/GUIScript/RegexObjects.cs trunk/plugins/GUIScript/ScriptHandler.cs trunk/plugins/GUIScript/SetupForm.cs trunk/plugins/GUIScript/SetupForm.resx trunk/plugins/GUIScript/script plugin.txt Added: trunk/plugins/GUIScript/!!! DO NOT CHANGE ANY FILES HERE - PLEASE UPDATE THE FILES IN MP-PLUGINS SVN !!! =================================================================== Added: trunk/plugins/GUIScript/ExpressionEval.cs =================================================================== --- trunk/plugins/GUIScript/ExpressionEval.cs (rev 0) +++ trunk/plugins/GUIScript/ExpressionEval.cs 2008-04-21 23:01:33 UTC (rev 1690) @@ -0,0 +1,439 @@ +#region Copyright (C) 2005-2008 Team MediaPortal + +/* + * Copyright (C) 2005-2008 Team MediaPortal + * http://www.team-mediaportal.com + * + * This Program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2, or (at your option) + * any later version. + * + * This Program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with GNU Make; see the file COPYING. If not, write to + * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. + * http://www.gnu.org/copyleft/gpl.html + * + */ + +#endregion + +// Code based on source from "The Code Project" +// by railerb + +using System; +using System.Collections; +using System.Text; +using System.Text.RegularExpressions; + +namespace MediaPortal.GUI.GUIScript +{ + public class ExpressionEval + { + + internal class BinaryOp + { + private string _strOp; + private int _nPrecedence; + + public string Op { get { return _strOp; } } + public int Precedence { get { return _nPrecedence; } } + + public BinaryOp(string strOp) + { _strOp = strOp; _nPrecedence = ExpressionEval.OperatorPrecedence(strOp); } + + public override string ToString() + { return Op; } + } + + internal class BinaryOpQueue + { + private ArrayList _oplist = new ArrayList(); + + public BinaryOpQueue(ArrayList expressionlist) + { + foreach (object item in expressionlist) + if (item is BinaryOp) + Enqueue((BinaryOp)item); + } + + public void Enqueue(BinaryOp op) + { + bool bQueued = false; + for (int x = 0; x < _oplist.Count && !bQueued; x++) + { + if (((BinaryOp)_oplist[x]).Precedence > op.Precedence) + { + _oplist.Insert(x, op); + bQueued = true; + } + } + if (!bQueued) + _oplist.Add(op); + } + + public BinaryOp Dequeue() + { + if (_oplist.Count == 0) + return null; + BinaryOp ret = (BinaryOp)_oplist[0]; + _oplist.RemoveAt(0); + return ret; + } + } + + internal class UnaryOp + { + private string _strOp; + + public string Op { get { return _strOp; } } + + public UnaryOp(string strOp) + { _strOp = strOp; } + + public override string ToString() + { return Op; } + + } + + ArrayList _expressionlist = new ArrayList(); + string _strExpression = ""; + bool _bParsed = false; + + public ExpressionEval() {} + + /// <summary> + /// Constructor with string + /// </summary> + public ExpressionEval(string strExpression) + { Expression = strExpression; } + + /// <summary> + /// Gets or sets the expression to be evaluated. + /// </summary> + public string Expression + { + get { return _strExpression; } + set + { + _strExpression = value.Trim(); + _bParsed = false; + _expressionlist.Clear(); + } + } + + /// <summary> + /// Evaluates the expression + /// </summary> + public object Evaluate() + { + if (Expression == null || Expression == "") + return 0; + + return ExecuteEvaluation(); + } + + public bool EvaluateBool() + { return Convert.ToBoolean(Evaluate()); } + + public int EvaluateInt() + { return Convert.ToInt32(Evaluate()); } + + public double EvaluateDouble() + { return Convert.ToDouble(Evaluate()); } + + public long EvaluateLong() + { return Convert.ToInt64(Evaluate()); } + + public static object Evaluate(string strExpression) + { + ExpressionEval expr = new ExpressionEval(strExpression); + return expr.Evaluate(); + } + + public static object Evaluate(string strExpression, FunctionHandler handler) + { + ExpressionEval expr = new ExpressionEval(strExpression); + expr.FunctionHandler += handler; + return expr.Evaluate(); + } + + private object ExecuteEvaluation() + { + //Break Expression Apart into List + if (!_bParsed) + for (int x = 0; x < Expression.Length; x = NextToken(x)); + _bParsed = true; + + //Perform Operations + return EvaluateList(); + } + + private int NextToken(int nIdx) + { + Match mRet = null; + int nRet = nIdx + 1; + object val = null; + Match m = DefinedRegex.Parenthesis.Match(Expression, nIdx); + if (m.Success) + { mRet = m; } + + m = DefinedRegex.Function.Match(Expression, nIdx); + if (m.Success && (mRet == null || m.Index < mRet.Index)) + { mRet = m; } + + m = DefinedRegex.UnaryOp.Match(Expression, nIdx); + if (m.Success && (mRet == null || m.Index < mRet.Index)) + { mRet = m; val = new UnaryOp(m.Value); } + + m = DefinedRegex.Hexadecimal.Match(Expression, nIdx); + if (m.Success && (mRet == null || m.Index < mRet.Index)) + { mRet = m; val = Convert.ToInt32(m.Value, 16); } + + m = DefinedRegex.Boolean.Match(Expression, nIdx); + if (m.Success && (mRet == null || m.Index < mRet.Index)) + { mRet = m; val = bool.Parse(m.Value); } + + m = DefinedRegex.Numeric.Match(Expression, nIdx); + if (m.Success && (mRet == null || m.Index < mRet.Index)) + { + while (m.Success && m.Value == "") + m = m.NextMatch(); + if (m.Success) + { + mRet = m; + val = double.Parse(m.Value); + } + } + + m = DefinedRegex.String.Match(Expression, nIdx); + if (m.Success && (mRet == null || m.Index < mRet.Index)) + { mRet = m; val = m.Groups["String"].Value.Replace("\\\"", "\""); } + + m = DefinedRegex.BinaryOp.Match(Expression, nIdx); + if (m.Success && (mRet == null || m.Index < mRet.Index)) + { mRet = m; val = new BinaryOp(m.Value); } + + if (mRet.Value == "(" || mRet.Value.StartsWith("$")) + { + nRet = (mRet.Value == "(") ? nRet+1 : mRet.Index + mRet.Length; + int nDepth = 1; + bool bInQuotes = false; + while (nDepth > 0) + { + if (nRet >= Expression.Length) + throw new Exception("Missing " + (bInQuotes ? "\"" : ")") + " in Expression"); + if (!bInQuotes && Expression[nRet] == ')') + nDepth--; + if (!bInQuotes && Expression[nRet] == '(') + nDepth++; + + if (Expression[nRet] == '"' && (nRet == 0 || Expression[nRet - 1] != '\\')) + bInQuotes = !bInQuotes; + + nRet++; + } + if (mRet.Value == "(") + { + ExpressionEval expr = new ExpressionEval( + Expression.Substring(mRet.Index + 1, nRet - mRet.Index - 2) + ); + if (this.FunctionHandler != null) + expr.FunctionHandler += this.FunctionHandler; + _expressionlist.Add(expr); + } + else + { + FunctionEval func = new FunctionEval( + Expression.Substring(mRet.Index, (nRet) - mRet.Index) + ); + if (this.FunctionHandler != null) + func.FunctionHandler += this.FunctionHandler; + _expressionlist.Add(func); + } + } + else + { + nRet = mRet.Index + mRet.Length; + _expressionlist.Add(val); + } + + return nRet; + } + + private object EvaluateList() + { + ArrayList list = (ArrayList)_expressionlist.Clone(); + + //Do the unary operators first + for (int x = 0; x < list.Count; x++) + { + if (list[x] is UnaryOp) + { + list[x] = PerformUnaryOp( + (UnaryOp)list[x], + list[x + 1] + ); + list.RemoveAt(x + 1); + } + } + + //Do the queued binary operations + BinaryOpQueue opqueue = new BinaryOpQueue(list); + BinaryOp op = opqueue.Dequeue(); + while (op != null) + { + int nIdx = list.IndexOf(op); + list[nIdx - 1] = PerformBinaryOp( + (BinaryOp)list[nIdx], + list[nIdx - 1], + list[nIdx + 1] + ); + list.RemoveAt(nIdx); + list.RemoveAt(nIdx); + op = opqueue.Dequeue(); + } + + object ret = null; + if (list[0] is ExpressionEval) + ret = ((ExpressionEval)list[0]).Evaluate(); + else if (list[0] is FunctionEval) + ret = ((FunctionEval)list[0]).Evaluate(); + else + ret = list[0]; + + return ret; + } + + private static int OperatorPrecedence(string strOp) + { + switch (strOp) + { + case "*": + case "/": + case "%": return 0; + case "+": + case "-": return 1; + case "<": + case "<=": + case ">": + case ">=": return 2; + case "==": + case "!=": return 3; + case "&": return 4; + case "^": return 5; + case "|": return 6; + case "&&": return 7; + case "||": return 8; + } + throw new Exception("Operator " + strOp + "not defined."); + } + + private static object PerformBinaryOp(BinaryOp op, object v1, object v2) + { + if (v1 is ExpressionEval) + v1 = ((ExpressionEval)v1).Evaluate(); + else if (v1 is FunctionEval) + v1 = ((FunctionEval)v1).Evaluate(); + if (v2 is ExpressionEval) + v2 = ((ExpressionEval)v2).Evaluate(); + else if (v2 is FunctionEval) + v2 = ((FunctionEval)v2).Evaluate(); + + switch (op.Op) + { + case "*": return (Convert.ToDouble(v1) * Convert.ToDouble(v2)); + case "/": return (Convert.ToDouble(v1) / Convert.ToDouble(v2)); + case "%": return (Convert.ToInt64(v1) % Convert.ToInt64(v2)); + case "+": + case "-": + case "<": + case "<=": + case ">": + case ">=": + case "==": + case "!=": return DoSpecialOperator(op, v1, v2); + case "&": return (Convert.ToUInt64(v1) & Convert.ToUInt64(v2)); + case "^": return (Convert.ToUInt64(v1) ^ Convert.ToUInt64(v2)); + case "|": return (Convert.ToUInt64(v1) | Convert.ToUInt64(v2)); + case "&&": return (Convert.ToBoolean(v1) && Convert.ToBoolean(v2)); + case "||": return (Convert.ToBoolean(v1) || Convert.ToBoolean(v2)); + } + throw new Exception("Binary Operator " + op.Op + "not defined."); + } + + private static object DoSpecialOperator(BinaryOp op, object v1, object v2) + { + if (v1 is string || v2 is string) + { + string str1 = "" + v1, + str2 = "" + v2; + + switch (op.Op) + { + case "+": return str1 + str2; + case "-": throw new Exception("operator '-' invalid for strings"); + case "<": return str1.CompareTo(str2) < 0; + case "<=": return str1.CompareTo(str2) < 0 || str1 == str2; + case ">": return str1.CompareTo(str2) > 0; + case ">=": return str1.CompareTo(str2) > 0 || str1 == str2;; + case "==": return str1 == str2; + case "!=": return str1 != str2; + } + } + if (v1 is DateTime || v2 is DateTime) + { + DateTime d1 = (DateTime)v1, d2 = Convert.ToDateTime(v2); + switch (op.Op) + { + case "+": throw new Exception("operator '+' invalid for dates"); + case "-": return d1 - d2; + case "<": return d1 < d2; + case "<=": return d1 <= d2; + case ">": return d1 > d2; + case ">=": return d1 >= d2; + case "==": return d1 == d2; + case "!=": return d1 != d2; + } + } + + double f1 = Convert.ToDouble(v1), f2 = Convert.ToDouble(v2); + switch (op.Op) + { + case "+": return f1 + f2; + case "-": return f1 - f2; + case "<": return f1 < f2; + case "<=": return f1 <= f2; + case ">": return f1 > f2; + case ">=": return f1 >= f2; + case "==": return f1 == f2; + case "!=": return f1 != f2; + } + + throw new Exception("operator '" + op.Op + "' not specified"); + } + + private static object PerformUnaryOp(UnaryOp op, object v) + { + if (v is ExpressionEval) + v = ((ExpressionEval)v).Evaluate(); + else if (v is FunctionEval) + v = ((FunctionEval)v).Evaluate(); + + switch (op.Op) + { + case "+": return (Convert.ToDouble(v)); + case "-": return (-Convert.ToDouble(v)); + } + throw new Exception("Unary Operator " + op.Op + "not defined."); + } + + public event FunctionHandler FunctionHandler; + + } +} Added: trunk/plugins/GUIScript/FunctionEval.cs =================================================================== --- trunk/plugins/GUIScript/FunctionEval.cs (rev 0) +++ trunk/plugins/GUIScript/FunctionEval.cs 2008-04-21 23:01:33 UTC (rev 1690) @@ -0,0 +1,261 @@ +#region Copyright (C) 2005-2008 Team MediaPortal + +/* + * Copyright (C) 2005-2008 Team MediaPortal + * http://www.team-mediaportal.com + * + * This Program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2, or (at your option) + * any later version. + * + * This Program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with GNU Make; see the file COPYING. If not, write to + * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. + * http://www.gnu.org/copyleft/gpl.html + * + */ + +#endregion + +// Code based on source from "The Code Project" +// by railerb + +using System; +using System.Collections; +using System.Text; +using System.Text.RegularExpressions; + +namespace MediaPortal.GUI.GUIScript +{ + + public delegate object FunctionHandler(string strName, object[] a_params); + public class FunctionEval + { + private string _strExpression = ""; + private string _strFunc = ""; + private bool _bParsed = false; + private object [] _params = null; + + public string Expression + { + get { return _strExpression; } + set + { + _strExpression = value.Trim(); + _strFunc = ""; + _bParsed = false; + _params = null; + } + } + + public FunctionEval() {} + + public FunctionEval(string strExpression) + { Expression = strExpression; } + + public object Evaluate() + { + object ret = null; + if (!_bParsed) + { + StringBuilder strbRet = new StringBuilder(Expression); + string strNext = strbRet.ToString(); + Match m = DefinedRegex.Function.Match(strNext); + + if (m.Success) + { + _params = GetParameters(m); + _strFunc = m.Groups["Function"].Value; + } + _bParsed = true; + } + ret = ExecuteFunction(_strFunc, _params); + return ret; + } + + /// <summary> + /// Evaluates a string expression of a function + /// </summary> + public static object Evaluate(string strExpression) + { + FunctionEval expr = new FunctionEval(strExpression); + return expr.Evaluate(); + } + + + public static string Replace(string strInput, FunctionHandler handler) + { + FunctionEval expr = new FunctionEval(strInput); + if (handler != null) + expr.FunctionHandler += handler; + return expr.Replace(); + } + + public static object Evaluate(string strExpression, FunctionHandler handler) + { + FunctionEval expr = new FunctionEval(strExpression); + if (handler != null) + expr.FunctionHandler += handler; + return expr.Evaluate(); + } + + public static string Replace(string strInput) + { + FunctionEval expr = new FunctionEval(strInput); + return expr.Replace(); + } + + public string Replace() + { + StringBuilder strbRet = new StringBuilder(Expression); + Match m = DefinedRegex.Function.Match(Expression); + + while (m.Success) + { + int nDepth = 1; + int nIdx = m.Index + m.Length; + //Get the parameter string + while (nDepth > 0) + { + if (nIdx >= strbRet.Length) + throw new Exception("Missing ')' in Expression"); + if (strbRet[nIdx] == ')') + nDepth--; + if (strbRet[nIdx] == '(') + nDepth++; + nIdx++; + } + string strExpression = strbRet.ToString(m.Index, nIdx - m.Index); + strbRet.Replace(strExpression, "" + Evaluate(strExpression, FunctionHandler)); + m = DefinedRegex.Function.Match(strbRet.ToString()); + } + return strbRet.ToString(); + } + + private object [] GetParameters(Match m) + { + string strParams = ""; + int nIdx = m.Index + m.Length; + int nDepth = 1; + int nLast = 0; + bool bInQuotes = false; + ArrayList ret = new ArrayList(); + + //Get the parameter string + while (nDepth > 0) + { + if (nIdx >= Expression.Length) + throw new Exception("Missing ')' in Expression"); + + if (!bInQuotes && Expression[nIdx] == ')') + nDepth--; + if (!bInQuotes && Expression[nIdx] == '(') + nDepth++; + + if (Expression[nIdx] == '"' && (nIdx == 0 || Expression[nIdx-1] != '\\')) + bInQuotes = !bInQuotes; + + if (nDepth > 0) + nIdx++; + } + strParams = Expression.Substring(m.Index + m.Length, nIdx - (m.Index + m.Length)); + + if (strParams == "") + return null; + + bInQuotes = false; + for (nIdx = 0; nIdx < strParams.Length; nIdx++) + { + if (!bInQuotes && strParams[nIdx] == ')') + nDepth--; + if (!bInQuotes && strParams[nIdx] == '(') + nDepth++; + + if (strParams[nIdx] == '"' && (nIdx == 0 || strParams[nIdx - 1] != '\\')) + bInQuotes = !bInQuotes; + + if (!bInQuotes && nDepth == 0 && strParams[nIdx] == ',') + { + ret.Add(strParams.Substring(nLast, nIdx - nLast)); + nIdx++; + nLast = nIdx; + } + } + ret.Add(strParams.Substring(nLast, nIdx - nLast)); + + for (nIdx = 0; nIdx < ret.Count; nIdx++) + try { ret[nIdx] = new ExpressionEval(ret[nIdx].ToString()); } + catch { ret[nIdx] = ((string)ret[nIdx]).Trim(); } + + return ret.ToArray(); + } + + /// <summary> + /// executes functions + /// </summary> + private object ExecuteFunction(string strName, object[] p) + { + object[] a_params = null; + if (p != null) + { + a_params = (object[])p.Clone(); + for (int x = 0; x < a_params.Length; x++) + if (a_params[x] is ExpressionEval) + a_params[x] = ((ExpressionEval)a_params[x]).Evaluate(); + } + switch (strName.ToLower()) + { + // Math functions + case "sin": return Math.Sin(Convert.ToDouble(a_params[0])); + case "cos": return Math.Cos(Convert.ToDouble(a_params[0])); + case "tan": return Math.Tan(Convert.ToDouble(a_params[0])); + case "asin": return Math.Asin(Convert.ToDouble(a_params[0])); + case "acos": return Math.Acos(Convert.ToDouble(a_params[0])); + case "atan": return Math.Atan(Convert.ToDouble(a_params[0])); + case "sinh": return Math.Sinh(Convert.ToDouble(a_params[0])); + case "cosh": return Math.Cosh(Convert.ToDouble(a_params[0])); + case "tanh": return Math.Tanh(Convert.ToDouble(a_params[0])); + case "abs": return Math.Abs(Convert.ToDouble(a_params[0])); + case "sqrt": return Math.Sqrt(Convert.ToDouble(a_params[0])); + case "log": return (a_params.Length > 1) ? + Math.Log(Convert.ToDouble(a_params[0]), Convert.ToDouble(a_params[1])) : + Math.Log(Convert.ToDouble(a_params[0])); + case "log10": return Math.Log10(Convert.ToDouble(a_params[0])); + case "ciel": return Math.Ceiling(Convert.ToDouble(a_params[0])); + case "floor": return Math.Floor(Convert.ToDouble(a_params[0])); + case "exp": return Math.Exp(Convert.ToDouble(a_params[0])); + case "max": return Math.Max(Convert.ToDouble(a_params[0]), Convert.ToDouble(a_params[1])); + case "min": return Math.Min(Convert.ToDouble(a_params[0]), Convert.ToDouble(a_params[1])); + case "pow": return Math.Pow(Convert.ToDouble(a_params[0]), Convert.ToDouble(a_params[1])); + case "round": return (a_params.Length > 1) ? + Math.Round(Convert.ToDouble(a_params[0]), Convert.ToInt32(a_params[1])) : + Math.Round(Convert.ToDouble(a_params[0])); + case "rnd": Random r = new Random(); + return r.Next(); + case "random": r = new Random(); + return r.Next(Convert.ToInt32(a_params[0]), Convert.ToInt32(a_params[1])); + case "now": return DateTime.Now; + case "today": return DateTime.Today; + case "e": return Math.E; + case "pi": return Math.PI; + case "calc": return ExpressionEval.Evaluate("" + a_params[0]); + default: return FunctionHelper(strName, a_params); + } + } + + protected object FunctionHelper(string strName, object[] a_params) + { + if (FunctionHandler != null) + return FunctionHandler(strName, a_params); + return null; + } + + public event FunctionHandler FunctionHandler; + } +} Added: trunk/plugins/GUIScript/GUIScript.cs =================================================================== --- trunk/plugins/GUIScript/GUIScript.cs (rev 0) +++ trunk/plugins/GUIScript/GUIScript.cs 2008-04-21 23:01:33 UTC (rev 1690) @@ -0,0 +1,103 @@ +#region Copyright (C) 2005-2008 Team MediaPortal + +/* + * Copyright (C) 2005-2008 Team MediaPortal + * http://www.team-mediaportal.com + * + * This Program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2, or (at your option) + * any later version. + * + * This Program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with GNU Make; see the file COPYING. If not, write to + * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. + * http://www.gnu.org/copyleft/gpl.html + * + */ + +#endregion + +#region usings +using System; +using System.IO; +using System.Collections; +using System.Management; +using MediaPortal.Util; +using MediaPortal.GUI.Library; +using MediaPortal.Dialogs; +#endregion + +namespace MediaPortal.GUI.GUIScript +{ + /// <summary> + /// Summary description for GUIExplorer + /// </summary> + public class GUIScript : GUIWindow + { + public static int WINDOW_STATUS = 740; + + #region Constructor + public GUIScript() + { + // + // TODO: Add constructor logic here + // + } + #endregion + + #region Overrides + public override int GetID + { + get { return WINDOW_STATUS; } + set { base.GetID = value; } + } + + public override bool Init() + { + //return Load (GUIGraphicsContext.Skin+@"\myexplorer.xml"); + return true; + } + + public override void OnAction(Action action) + { + if (action.wID == Action.ActionType.ACTION_PREVIOUS_MENU) + { + GUIWindowManager.ShowPreviousWindow(); + return; + } + base.OnAction(action); + } + + public override bool OnMessage(GUIMessage message) + { + switch ( message.Message ) + { + case GUIMessage.MessageType.GUI_MSG_WINDOW_INIT: // MyScript starts + base.OnMessage(message); + LoadSettings(); // loads all settings from XML + return true; + } + return base.OnMessage (message); + } + + #endregion + + #region Private Methods + + /// <summary> + /// Loads all Settings from MediaPortal.xml + /// </summary> + private void LoadSettings() + { + + } + + #endregion + } +} Added: trunk/plugins/GUIScript/MPScript.cs =================================================================== --- trunk/plugins/GUIScript/MPScript.cs (rev 0) +++ trunk/plugins/GUIScript/MPScript.cs 2008-04-21 23:01:33 UTC (rev 1690) @@ -0,0 +1,1004 @@ +#region Copyright (C) 2005-2008 Team MediaPortal + +/* + * Copyright (C) 2005-2008 Team MediaPortal + * http://www.team-mediaportal.com + * + * This Program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2, or (at your option) + * any later version. + * + * This Program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with GNU Make; see the file COPYING. If not, write to + * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. + * http://www.gnu.org/copyleft/gpl.html + * + */ + +#endregion + +#region Usings +using System; +using System.IO; +using System.Collections; +using System.Management; +using MediaPortal.GUI.Library; +using MediaPortal.Util; +using MediaPortal.Dialogs; +using System.Text.RegularExpressions; +#endregion + +namespace MediaPortal.GUI.GUIScript +{ + /// <summary> + /// Summary description for MPScript. + /// </summary> + public class MPScript + { + #region Private Variables + // funktions token + private const char tDebugOn='0'; + private const char tDebugOff='1'; + private const char tStatic='@'; + private const char tGlobal='\xB0'; + private const char tVar='@'; + private const char tIf='a'; + private const char tEndIf='b'; + private const char tElse='c'; + private const char tWhile='d'; + private const char tSwitch='e'; + private const char tFor='f'; + private const char tMp_action='g'; + private const char tEnd='h'; + private const char tEndWhile='i'; + private const char tEndSwitch='j'; + private const char tCase='k'; + private const char tMessageBox='l'; + private const char tEndFor='m'; + private const char tCall='n'; + private const char tDefault='o'; + private const char tContinue='p'; + private const char tBreak='q'; + + // regular expression + Regex rexStripOp = new Regex(@"\+|-|\*|/|%|&&|\|\||&|\||\^|==|!=|>=|<=|=|<|>|!|\(|\)|\:|true|false|,", RegexOptions.IgnoreCase); + Regex rexStripQuote = new Regex("\"", RegexOptions.IgnoreCase); + Regex rexStripString = new Regex( "\\\"(?<String>.*?[^\\\\])\\\"", RegexOptions.IgnoreCase); + + // static vars + private static string strTokenbuffer; + private static char[] DELIMITER = {' ','(','=','\"',')' }; + private static char[] BYPASSCODE = {'\t',' ','(','\"',')','=','%','\xA7','@','$','\xB0' }; + private static Hashtable global_variable = new Hashtable(); + private static int numScripts=0; + private static bool m_bForceShutdown = false; // Force shutdown + + private char oper=' '; + private String[] scriptArray; + private String[] debugArray; + private int progPointer=0; + private int ScriptEnd=0; + private long BreakTime=5000; + private string ScriptName=""; + private bool debuging=false; + private string debugName=""; + + // hashtables for vars and functions + private Hashtable tokens = new Hashtable(); + private Hashtable variable = new Hashtable(); + private Hashtable functions = new Hashtable(); + + // stack + private Stack stack = new Stack(); + + ExpressionEval eval = new ExpressionEval(); + + #endregion + + #region Constructor + public MPScript() + { + + eval.FunctionHandler += new FunctionHandler(MPFunctions); + + // save Tokens in hashtable + tokens.Add("static",tStatic); + tokens.Add("var",tVar); + tokens.Add("global",tGlobal); + tokens.Add("end",tEnd); + tokens.Add("if",tIf); + tokens.Add("endif",tEndIf); + tokens.Add("else",tElse); + tokens.Add("while",tWhile); + tokens.Add("endwhile",tEndWhile); + tokens.Add("switch",tSwitch); + tokens.Add("case",tCase); + tokens.Add("default",tCase); + tokens.Add("endswitch",tEndSwitch); + tokens.Add("for",tFor); + tokens.Add("continue",tContinue); + tokens.Add("break",tBreak); + tokens.Add("call",tCall); + tokens.Add("mp_action",tMp_action); + tokens.Add("messagebox",tMessageBox); + + // save functions in hashtable + functions.Add("yesnobox",'a'); + functions.Add("mp_var",'b'); + functions.Add("sin",'B'); + functions.Add("cos",'C'); + functions.Add("tan",'D'); + functions.Add("asin",'E'); + functions.Add("acos",'F'); + functions.Add("atan",'G'); + functions.Add("sinh",'H'); + functions.Add("cosh",'I'); + functions.Add("tanh",'J'); + functions.Add("abs",'K'); + functions.Add("sqrt",'L'); + functions.Add("ciel",'M'); + functions.Add("floor",'N'); + functions.Add("exp",'O'); + functions.Add("log10",'P'); + functions.Add("log",'Q'); + functions.Add("max",'R'); + functions.Add("min",'S'); + functions.Add("pow",'T'); + functions.Add("round",'U'); + functions.Add("e",'V'); + functions.Add("pi",'W'); + functions.Add("now",'X'); + functions.Add("today",'Y'); + functions.Add("calc",'2'); + functions.Add("rnd",'3'); + functions.Add("random",'4'); + } + #endregion + + #region Public helpers + /// <summary> + /// sets a global var + /// </summary> + public void setGlobalVar(string key,object val) + { + if (global_variable.ContainsKey(key)) + { + global_variable[key]=val; + } + else + { + global_variable.Add(key,val); + } + } + #endregion + + #region Load Script in Memory + /// <summary> + /// Reads the script into Memory and make preprocessing + /// </summary> + /// <returns>A string containing the button text.</returns> + // TODO: Add more commands and funktions + public string GetScript(string name) // Read the MPScript + { + numScripts++; + bool debugInit=false; + string work=""; + string scratch=""; + string buttonText=""; + string scriptdir=System.IO.Directory.GetCurrentDirectory()+"\\"+"scripts"; + try + { + StreamReader sr = new StreamReader(scriptdir+"\\"+name+".mps"); + String fileContent = sr.ReadToEnd(); + char[] separator = {'\n'}; + scriptArray = fileContent.Split(separator); + debugArray = fileContent.Split(separator); + ScriptName=name; + global_variable.Add(ScriptName,"Load"); + + //-------------------------------------------------------------------------- + for (int i=0;i<scriptArray.Length;i++) // little preprocessor + { + scriptArray[i]=scriptArray[i].Trim(); + work=scriptArray[i]; + if (work.Length<2) + { + scriptArray[i]="#"; + continue; + } + work=work.Trim().ToLower(); + if (work.StartsWith("#description:") ==true) + { + scriptArray[i]="#"; + continue; + } + if (work.StartsWith("#button:") ==true) + { + buttonText=checkText(scriptArray[i].Trim().Substring(8)); + scriptArray[i]="#"; + continue; + } + if (work.StartsWith("#debugon") ==true) + { + scriptArray[i]="\xA7"+tDebugOn; + if(debugInit==false) + { + InitDebugLog(); + debugInit=true; + } + continue; + } + if (work.StartsWith("#debugoff") ==true) + { + scriptArray[i]="\xA7"+tDebugOff; + continue; + } + if (work.StartsWith("#breaktime:") ==true) + { + string tx=work.Substring(11); + try + { + int bx=Convert.ToInt32(tx); + BreakTime=bx*1000; + } + catch(Exception) + { + BreakTime=5000; + } + scriptArray[i]="#"; + continue; + } + int indx=work.IndexOf("\"",0); + if (indx>0) + { + string w=work.Substring(0,indx); + w=w+scriptArray[i].Substring(indx); + scriptArray[i]=w; + } + else + { + scriptArray[i]=work; + } + indx=work.IndexOf("//"); // any remarks? + if (indx!=-1) + { + if (indx==0) + { + scriptArray[i]="#"; + continue; + } + else + { + scriptArray[i]=work.Substring(0,indx); + } + } + //------------------------------------------------------------ + // Replace any command with tokens + string tok=ParseToken(scriptArray[i]); + if (variable.ContainsKey(tok)) // is token a variable? + { + scriptArray[i]=tVar+tok+" "+changeFunc(strTokenbuffer); + } + if (global_variable.ContainsKey(tok)) + { + scriptArray[i]=tGlobal+tok+" "+changeFunc(strTokenbuffer); + } + if (tokens.ContainsKey(tok)) // is token a command + { + switch (tok) + { + case "static" : + scriptArray[i]="#"; + string k=ParseToken(strTokenbuffer); + if (strTokenbuffer.IndexOf("*",0)!=-1 || strTokenbuffer.IndexOf("/",0)!=-1 || strTokenbuffer.IndexOf("+",0)!=-1 || strTokenbuffer.IndexOf("-",0)!=-1) + { + eval.Expression = strTokenbuffer; + strTokenbuffer=eval.Evaluate().ToString(); + } + string b=ParseToken(strTokenbuffer); + variable.Add(k,b); + break; + case "global" : + k=ParseToken(strTokenbuffer); + if (strTokenbuffer.IndexOf("*",0)!=-1 || strTokenbuffer.IndexOf("/",0)!=-1 || strTokenbuffer.IndexOf("+",0)!=-1 || strTokenbuffer.IndexOf("-",0)!=-1) + { + eval.Expression = strTokenbuffer; + strTokenbuffer=eval.Evaluate().ToString(); + } + b=ParseToken(strTokenbuffer); + scriptArray[i]=tGlobal+k+"="+b; + global_variable.Add(k,b); + break; + case "var" : + k=ParseToken(strTokenbuffer); + if (strTokenbuffer.IndexOf("*",0)!=-1 || strTokenbuffer.IndexOf("/",0)!=-1 || strTokenbuffer.IndexOf("+",0)!=-1 || strTokenbuffer.IndexOf("-",0)!=-1) + { + eval.Expression = strTokenbuffer; + strTokenbuffer=eval.Evaluate().ToString(); + } + b=ParseToken(strTokenbuffer); + scriptArray[i]=tVar+k+"="+b; + variable.Add(k,b); + break; + case "if" : + scriptArray[i]="\xA7"+tokens[tok]+changeFunc(strTokenbuffer); + break; + case "endif" : + scriptArray[i]="\xA7"+tokens[tok]; + break; + case "else" : + scriptArray[i]="\xA7"+tokens[tok]; + break; + case "while" : + scriptArray[i]="\xA7"+tokens[tok]+changeFunc(strTokenbuffer); + break; + case "endwhile" : + scriptArray[i]="\xA7"+tokens[tok]; + break; + case "continue" : + scriptArray[i]="\xA7"+tokens[tok]; + break; + case "break" : + scriptArray[i]="\xA7"+tokens[tok]; + break; + case "switch" : + scriptArray[i]="\xA7"+tokens[tok]+changeFunc(strTokenbuffer); + break; + case "case" : + scriptArray[i]="\xA7"+tokens[tok]+changeFunc(strTokenbuffer); + break; + case "default" : + scriptArray[i]="\xA7"+tokens[tok]; + break; + case "endswitch" : + scriptArray[i]="\xA7"+tokens[tok]; + break; + case "for" : + scriptArray[i]="\xA7"+tokens[tok]+changeFunc(strTokenbuffer); + break; + case "messagebox" : + scriptArray[i]="\xA7"+tokens[tok]+changeFunc(strTokenbuffer); + break; + case "call" : + scratch=changeFunc(strTokenbuffer); + scratch = rexStripOp.Replace(scratch,""); + scratch = rexStripQuote.Replace(scratch,""); + scriptArray[i]="\xA7"+tokens[tok]+scratch.Trim(); + ScriptHandler gScript=new ScriptHandler(); + scratch=gScript.LoadScript(scratch.Trim()); + break; + case "mp_action" : + scriptArray[i]="\xA7"+tokens[tok]+ParseToken(strTokenbuffer); + break; + case "end" : + scriptArray[i]="\xA7"+tokens[tok]; + break; + } + } + } + } + catch(Exception ex) + { + Log.Info("Syntax Error!", ex.Message); + buttonText="SCRIPT ERROR!!"; + global_variable[ScriptName]="ERROR"; + } + global_variable[ScriptName]="Loaded"; + return buttonText; + } + #endregion + + #region Run MPScript + /// <summary> + /// Starts the Script + /// </summary> + // TODO: Add more commands and funktions + public bool RunScript() + { + bool debugHeader=false; + string progLine=""; + string leftvar=""; + long lStartTime = DateTime.Now.Ticks; + long lDiff = 0; + + ScriptEnd=scriptArray.Length; + try + { + global_variable[ScriptName]="Run"; + while (progPointer<ScriptEnd) + { + if (debuging==true) + { + if(debugHeader==false) + { + WriteDebugHeader(); + debugHeader=true; + } + WriteDebug("S:{0:000} L:{1:000}: {2}",stack.Count,progPointer,debugArray[progPointer]); + WriteLnDebug(" "); + WriteDebug(" > "); + } + if (BreakTime>0) + { + lDiff = (DateTime.Now.Ticks - lStartTime)/10000; + if(lDiff>BreakTime) + { + global_variable[ScriptName]="Time Break"; + if (debuging==true) WriteLnDebug(" Time Break! {0} ms",lDiff); + return false; + } + } + progLine=scriptArray[progPointer]; + if (progLine.Substring(0,1)=="#") // Nothing to do + { + if (debuging==true) WriteLnDebug(" NOP"); + progPointer++; + continue; + } + if (progLine.Substring(0,1)==tVar.ToString()) // var first + { + leftvar=ParseToken(progLine); + if (variable.ContainsKey(leftvar)) + { + if (oper=='=') // assignment + { + progLine=ChangeVar(strTokenbuffer); + { + if (progLine=="=") + { + variable[leftvar]=""; + } + else + { + eval.Expression = progLine; + progLine=eval.Evaluate().ToString(); + variable[leftvar]=progLine; + } + if (debuging==true) WriteLnDebug("Var {0} = {1}",leftvar,progLine); + progPointer++; + continue; + } + } + } + } + if (progLine.Substring(0,1)==tGlobal.ToString()) // global var first + { + leftvar=ParseToken(progLine); + if (global_variable.ContainsKey(leftvar)) + { + if (oper=='=') // assignment + { + progLine=ChangeVar(strTokenbuffer); + { + if (progLine=="=") + { + variable[leftvar]=""; + } + else + { + eval.Expression = progLine; + progLine=eval.Evaluate().ToString(); + global_variable[leftvar]=progLine; + } + if (debuging==true) WriteLnDebug("Global {0} = {1}",leftvar,progLine); + progPointer++; + continue; + } + } + } + } + if (progLine.Substring(0,1)=="\xA7") // command processing + { + char ch = Convert.ToChar(progLine.Substring(1,1)); + if (progLine.Length>2) + { + progLine=progLine.Substring(2); + progLine=ChangeVar(progLine); + } + switch (ch) + { + // If statement ------------------------------------------------ + case tIf: + eval.Expression = progLine; + progLine=eval.Evaluate().ToString(); + if (debuging==true) WriteLnDebug("IF = {0}",progLine); + if(progLine=="True") + { + progPointer++; + } + else + { + progPointer++; + jump(tElse,tIf,tEndIf); + } + break; + // While statement ----------------------------------------------- + case tWhile: + eval.Expression = progLine; + progLine=eval.Evaluate().ToString(); + if (debuging==true) WriteLnDebug("WHILE = {0}",progLine); + if(progLine=="True") + { + stack.Push(progPointer++); + } + else + { + progPointer++; + jump(tWhile,tWhile,tEndWhile); + } + break; + // Switch statement ---------------------------------------------- + case tSwitch: + eval.Expression = progLine; + progLine=eval.Evaluate().ToString(); + if (debuging==true) WriteLnDebug("SWITCH = {0}",progLine); + searchCase(progLine); + break; + // Case statement ------------------------------------------------ + case tCase: + progPointer++; + jump(tSwitch,tSwitch,tEndSwitch); + break; + // EndSwitch statement ------------------------------------------- + case tEndSwitch: + progPointer++; + break; + // Continue statement ------------------------------------------- + case tContinue: + if(stack.Count>0) + { + progPointer=Convert.ToInt32(stack.Pop()); + if (debuging==true) WriteLnDebug("JUMPTO {0:000}",progPointer); + } + else + { + if (debuging==true) WriteLnDebug("ERROR Continue!"); + } + break; + // Break statement ------------------------------------------- + case tBreak: + progPointer++; + jump(tWhile,tWhile,tEndWhile); + break; + // EndWhile statement -------------------------------------------- + case tEndWhile: + progPointer=Convert.ToInt32(stack.Pop()); + if (debuging==true) WriteLnDebug("JUMPTO {0:000}",progPointer); + break; + // End statement ------------------------------------------------- + case tEnd: + global_variable[ScriptName]="End"; + if (debuging==true) WriteLnDebug("Program End!"); + return true; + // Call statement ------------------------------------------------- + case tCall: + ScriptHandler gScript=new ScriptHandler(); + global_variable[ScriptName]="Call"; + if (debuging==true) WriteLnDebug("CALL {0}",progLine); + gScript.StartScriptName(progLine); + if (debuging==true) WriteLnDebug("RET {0}",progLine); + progPointer++; + break; + // MP_Action statement -------------------------------------------- + case tMp_action: + callAction(progLine); + progPointer++; + break; + // MessageBox statement ------------------------------------------- + case tMessageBox: + DialogBox(checkText(progLine.Substring(2))); + progPointer++; + break; + case tDebugOn: + debuging=true; + if (debuging==true) WriteLnDebug("DEBUG On"); + progPointer++; + break; + case tDebugOff: + debuging=false; + if (debuging==true) WriteLnDebug("DEBUG Off"); + progPointer++; + break; + default: + progPointer++; + break; + } + } + else + { + if (debuging==true) WriteLnDebug("ERROR in Line {0:000}",progPointer); + Log.Info("MPScript: Syntax error in Line {0}",progPointer); + progPointer++; + } + } + } + catch(Exception ex) + { + global_variable[ScriptName]="ERROR"; + Log.Info("Syntax Error!", ex.Message); + if (debuging==true) WriteLnDebug("ERROR in Line {0:000}",progPointer); + } + return true; + } + #endregion + + #region MPScript helpers + + private string changeFunc(string buffer) + { + string buf=""; + string tok=""; + int i=0; + + buf = rexStripString.Replace(buffer,""); + buf = rexStripOp.Replace(buf," "); + + strTokenbuffer=buf.Trim(); + while (strTokenbuffer.Length>=1) + { + tok=ParseToken(strTokenbuffer); + if(functions.ContainsKey(tok)) + { + i=buffer.IndexOf(tok,0); + buffer=buffer.Substring(0,i)+"$"+buffer.Substring(i); + continue; + } + if(variable.ContainsKey(tok)) + { + i=buffer.IndexOf(tok,0); + buffer=buffer.Substring(0,i)+tVar+buffer.Substring(i); + continue; + } + if(global_variable.ContainsKey(tok)) + { + i=buffer.IndexOf(tok,0); + buffer=buffer.Substring(0,i)+tGlobal+buffer.Substring(i); + continue; + } + } + return buffer; + } + + private string ChangeVar(string buffer) + { + string buf=buffer; + string buf2=""; + string tok; + + int i=buffer.IndexOf(tGlobal.ToString()); + while(i>-1) + { + buf = buffer; + buf = rexStripOp.Replace(buf," "); + buf2=buffer.Substring(0,i); + tok=ParseToken(buf.Substring(i)); + buffer=buf2+" "+global_variable[tok]+buffer.Substring(i+tok.Length+1); + i=buffer.IndexOf(tGlobal.ToString()); + } + i=buffer.IndexOf(tVar.ToString()); + while(i>-1) + { + buf = buffer; + buf = rexStripOp.Replace(buf," "); + buf2=buffer.Substring(0,i); + tok=ParseToken(buf.Substring(i)); + buffer=buf2+" "+variable[tok]+buffer.Substring(i+tok.Length+1); + i=buffer.IndexOf(tVar.ToString()); + } + return buffer; + } + + private void searchCase(string cond) + { + string scratch; + string buffer; + while (progPointer<ScriptEnd) + { + if (scriptArray[progPointer].Substring(0,1)=="\xA7") + { + if (Convert.ToChar(scriptArray[progPointer].Substring(1,1))==tCase) + { + buffer=scriptArray[progPointer].Substring(1); + scratch=ParseToken(buffer); + buffer=ParseToken(strTokenbuffer); + buffer=rexStripOp.Replace(buffer," "); + buffer=buffer.Trim(); + if (buffer==cond) + { + progPointer++; + break; + } + } + } + progPointer++; + } + } + + private void jump(char tst,char skip,char end) + { + int skipCnt=0; + while (progPointer<ScriptEnd) + { + if (scriptArray[progPointer].Substring(0,1)=="\xA7") + { + if (Convert.ToChar(scriptArray[progPointer].Substring(1,1))==skip) + { + skipCnt++; + progPointer++; + continue; + } + if (Convert.ToChar(scriptArray[progPointer].Substring(1,1))==end) + { + if (skipCnt==0) + { + progPointer++; + break; + } + else + { + skipCnt--; + progPointer++; + continue; + } + } + if (Convert.ToChar(scriptArray[progPointer].Substring(1,1))==tst) + { + if(skipCnt==0) + { + progPointer++; + break; + } + } + } + progPointer++; + } + } + + /// <summary> + /// Reads the next token and operant + /// </summary> + /// <returns>A string containing the next token</returns> + private string ParseToken(string line) + { + int i = 0; + int j = line.Length; + bool foundFg = false; + + char[] p; + int k; + + p = line.ToCharArray(); + + do + { + for(int ii = 0; ii < BYPASSCODE.Length; ii++) + { + if( p[i] == BYPASSCODE[ii] ) + { + foundFg = true; + break; + } + } + if( foundFg ) + { + i++; + foundFg = false; + } + else + break; + } while(i < j); + + k = i; + int d=0; + while(i < j && p[i] != DELIMITER[d]) + { + if (d<DELIMITER.Length-1) + { + d++; + } + else + { + i++; + d=0; + } + } + oper=DELIMITER[d]; + if (oper==' ') + { + int ii=i; + while(ii < j && p[ii]==' ') + { + ii++; + } + if (ii<j) + { + oper=p[ii]; + } + } + strTokenbuffer = line.Substring(i, j-i); + + return(line.Substring(k, i-k)); + } + #endregion + + #region MPScript functions + private void DialogBox(string text) + { + GUIDialogOK dlgOk = (GUIDialogOK)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_OK); + dlgOk.SetHeading(""); + dlgOk.SetLine(1,text); + dlgOk.DoModal(GUIWindowManager.ActiveWindow); + } + + private void callAction(string ac) + { + Action act; + switch (ac) + { + case "reboot" : + act = new Action(Action.ActionType.ACTION_REBOOT,0,0); + GUIGraphicsContext.OnAction(act); + break; + case "shutdown" : + act = new Action(Action.ActionType.ACTION_SHUTDOWN,0,0); + GUIGraphicsContext.OnAction(act); + break; + case "hibernate" : + WindowsController.ExitWindows(RestartOptions.Hibernate, m_bForceShutdown); + break; + case "ejectcd" : + act = new Action(Action.ActionType.ACTION_EJECTCD,0,0); + GUIGraphicsContext.OnAction(act); + break; + case "previous_menu" : + act = new Action(Action.ActionType.ACTION_PREVIOUS_MENU,0,0); + GUIGraphicsContext.OnAction(act); + break; + } + } + #endregion + + #region Private Static Functions + + /// <summary> + /// Call user functions + /// </summary> + private static object MPFunctions(string strName, object[] a_params) + { + switch (strName.ToLower()) + { + case "yesnobox" : string t=a_params[0].ToString(); + t=checkText(t); + bool yn=YesNoBox(t); + return yn; + case "mp_var" : t=a_params[0].ToString(); + t=checkText(t); + return null; + case "testit" : return "0"; + default: + return null; + } + } + + /// <summary> + /// Converts MP nums in localize text + /// </summary> + private static string checkText(string text) + { + string conv=text.Trim(); + try + { + int bx=Convert.ToInt32(text); + if (bx>0) + { + conv=GUILocalizeStrings.Get(bx); + } + } + catch(Exception) + { + } + return conv; + } + + /// <summary> + /// Shows Yes No Box + /// </summary> + private static bool YesNoBox(string text) + { + GUIDialogYesNo dlgYesNo = (GUIDialogYesNo)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_YES_NO); + if (null==dlgYesNo) return false; + dlgYesNo.SetHeading(""); + dlgYesNo.SetLine(1,text); + dlgYesNo.DoModal(GUIWindowManager.ActiveWindow); + return dlgYesNo.IsConfirmed; + } + #endregion + + #region Debug helpers + + private void InitDebugLog() + { + try + { + debugName=@"log\script"+ScriptName+".log"; + System.IO.File.Delete(debugName.Replace(".log",".bak")); + System.IO.File.Move(debugName,debugName.Replace(".log",".bak")); + } + catch(Exception) + { + } + } + + public void WriteDebug(string strFormat, params object[] arg) + { + try + { + using (StreamWriter writer = new StreamWriter(debugName,true)) + { + writer.BaseStream.Seek(0, SeekOrigin.End); // set the file pointer to the end of + writer.WriteLine(" "); + writer.Write(DateTime.Now.ToLongTimeString()+" "); + writer.Write(strFormat,arg); + writer.Close(); + } + } + catch(Exception) + { + } + } + + public void WriteLnDebug(string strFormat, params object[] arg) + { + try + { + using (StreamWriter writer = new StreamWriter(debugName,true)) + { + writer.BaseStream.Seek(0, SeekOrigin.End); // set the file pointer to the end of + writer.Write(strFormat,arg); + writer.Close(); + } + } + catch(Exception) + { + } + } + + public void WriteDebugHeader() + { + try + { + using (StreamWriter writer = new StreamWriter(debugName,true)) + { + writer.BaseStream.Seek(0, SeekOrigin.End); // set the file pointer to the end of + writer.WriteLine("MPScript V0.1 Debug Output from {0}",debugName); + writer.WriteLine(DateTime.Now.ToShortDateString()+ " "+DateTime.Now.ToLongTimeString()+ " "); + writer.WriteLine("\n-------------------------------------"); + writer.WriteLine("Global Vars:"); + foreach (DictionaryEntry de in global_variable) + { + writer.WriteLine("Global Var {0}={1}",de.Key,de.Value); + } + writer.WriteLine("\n-------------------------------------"); + writer.WriteLine("Local Vars:"); + foreach (DictionaryEntry de in variable) + { + writer.WriteLine("Local Var {0}={1}",de.Key,de.Value); + } + writer.WriteLine("\n-------------------------------------\n"); + writer.Close(); + } + } + catch(Exception) + { + } + } + + #endregion + } +} Added: trunk/plugins/GUIScript/RegexObjects.cs =================================================================== --- trunk/plugins/GUIScript/RegexObjects.cs (rev 0) +++ trunk/plugins/GUIScript/RegexObjects.cs 2008-04-21 23:01:33 UTC (rev 1690) @@ -0,0 +1,86 @@ +#region Copyright (C) 2005-2008 Team MediaPortal + +/* + * Copyright (C) 2005-2008 Team MediaPortal + * http://www.team-mediaportal.com + * + * This Program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2, or (at your option) + * any later version. + * + * This Program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with GNU Make; see the file COPYING. If not, write to + * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. + * http://www.gnu.org/copyleft/gpl.html + * + */ + +#endregion + +// Code based on source from "The Code Project" +// by railerb + +using System; +using System.Text; +using System.Text.RegularExpressions; + +namespace MediaPortal.GUI.GUIScript +{ + internal class DefinedRegex + { + private const string c_strNumeric = @"(?:[0-9]+)?(?:\.[0-9]+)?(?:E-?[0-9]+)?(?=\b)"; + private const string c_strHex = @"0x([0-9a-fA-F]+)"; + private const string c_strUnaryOp = @"(?:\+|-|!|~)(?=\w|\()"; + private const string c_strBinaryOp = @"\+|-|\*|/|%|&&|\|\||&|\||\^|==|!=|>=|<=|=|<|>"; + private const string c_strBool = @"true|false"; + private const string c_strFunction = @"\$(?<Function>\w+)\("; + private const string c_strString = "\\\"(?<String>.*?[^\\\\])\\\""; + + internal static Regex Numeric = new Regex( + c_strNumeric, + RegexOptions.Compiled + ); + + internal static Regex Hexadecimal = new Regex( + c_strHex, + RegexOptions.Compiled + ); + + internal static Regex Boolean = new Regex( + c_strBool, + RegexOptions.Compiled | RegexOptions.IgnoreCase + ); + + internal static Regex UnaryOp = new Regex( + @"(?<=(?:" + c_strBinaryOp + @")\s*|\A)(?:" + c_strUnaryOp + @")", + RegexOptions.Compiled + ); + + internal static Regex BinaryOp = new Regex( + @"(?<!(?:" + c_strBinaryOp + @")\s*|^\A)(?:" + c_strBinaryOp + @")", + RegexOptions.Compiled + ); + + internal static Regex Parenthesis = new Regex( + @"\(", + RegexOptions.Compiled + ); + + internal static Regex Function = new Regex( + c_strFunction, + RegexOptions.Compiled + ); + + internal static Regex String = new Regex( + c_strString, + RegexOptions.Compiled + ); + + } +} Added: trunk/plugins/GUIScript/ScriptHandler.cs =================================================================== --- trunk/plugins/GUIScript/ScriptHandler.cs (rev 0) +++ trunk/plugins/GUIScript/ScriptHandler.cs 2008-04-21 23:01:33 UTC (rev 1690) @@ -0,0 +1,138 @@ +#region Copyright (C) 2005-2008 Team MediaPortal + +/* + * Copyright (C) 2005-2008 Team MediaPortal + * http://www.team-mediaportal.com + * + * This Program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2, or (at your option) + * any later version. + * + * This Program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with GNU Make; see the file COPYING. If not, write to + * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. + * http://www.gnu.org/copyleft/gpl.html + * + */ + +#endregion + +#region Usings +using System; +using System.IO; +using System.Collections; +using System.Management; +#endregion + +namespace MediaPortal.GUI.GUIScript +{ + /// <summary> + /// Summary description for ScriptHandler. + /// </summary> + public class ScriptHandler + { + + private struct script + { + public string name; + public string button; + public MPScript mpScript; + } + private static MPScript gscript=new MPScript(); + private static ArrayList scripts = new ArrayList(); + + public ScriptHandler() + { + // + // TODO: Add constructor logic here + // + } + + /// <summary> + /// sets a global bool var + /// </summary> + public void SetGlobalVar(string key,object val) + { + gscript.setGlobalVar(key,val); + } + + /// <summary> + /// start a script with Button Name + /// </summary> + public void StartScript(string name) // starts script "name" + { + foreach (script scr in scripts) + { + if (scr.button==name) + { + bool b=scr.mpScript.RunScript(); + break; + } + } + } + + /// <summary> + /// start a script with Script Name + /// </summary> + public void StartScriptName(string name) // starts script "name" + { + foreach (script scr in scripts) + { + if (scr.name==name) + { + bool b=scr.mpScript.RunScript(); + break; + } + } + } + + /// <summary> + /// load a script in memory + /// </summary> + public string LoadScript(string name) // loads a script in memory + { + string btnTxt=""; + if (scripts.Count>0) + { + bool found=false; + foreach (script scr in scripts) // is script already here? + { + if (scr.name==name) + { + found=true; + btnTxt=scr.button; + break; + } + } + if (found==false) + { + script sc = new script(); + sc.name=name; + MPScript mpScript = new MPScript(); + sc.button=mpScript.GetScript(name); + sc.mpScript=mpScript; + scripts.Add(sc); + btnTxt=sc.button; + } + } + else + { + script sc = new script(); + sc.name=name; + MPScript mpScript = new MPScript(); + btnTxt=mpScript.GetScript(name); + sc.button=btnTxt; + sc.mpScript=mpScript; + scripts.Add(sc); + } + return btnTxt; + } + + } +} Added: trunk/plugins/GUIScript/SetupForm.cs =================================================================== --- trunk/plugins/GUIScript/SetupForm.cs (rev 0) +++ trunk/plugins/GUIScript/SetupForm.cs 2008-04-21 23:01:33 UTC (rev 1690) @@ -0,0 +1,236 @@ +#region Copyright (C) 2005-2008 Team MediaPortal + +/* + * Copyright (C) 2005-2008 Team MediaPortal + * http://www.team-mediaportal.com + * + * This Program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2, or (at your option) + * any later version. + * + * This Program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with GNU Make; see the file COPYING. If not, write to + * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. + * http://www.gnu.org/copyleft/gpl.html + * + */ + +#endregion + +using System; +using System.IO; +using System.Drawing; +using System.Collections; +using System.ComponentModel; +using System.Windows.Forms; +using MediaPortal.GUI.Library; + +namespace GUIScript +{ + /// <summary> + /// Summary description for SetupForm. + /// </summary> + public class SetupForm : System.Windows.Forms.Form, ISetupForm, IShowPlugin + { + private System.Windows.Forms.ListBox ScriptsFunctions; + /// <summary> + /// Required designer variable. + /// </summary> + ... [truncated message content] |