Ejemplo n.º 1
0
        ///////////////////////////////////////////////////////////////////////////////////////////////

        public bool Add(IEnumerable <Regex> keys, Type enumType, IEnumerable <Enum> values, ref Result error)
        {
            object zeroValue = EnumOps.TryGetEnum(enumType, 0, ref error);

            if (zeroValue != null)
            {
                IEnumerator <Enum> enumerator = values.GetEnumerator(); /* throw */
                bool moveNext = true;

                foreach (Regex key in keys)
                {
                    //
                    // NOTE: If we run out of values before keys, zero fill the
                    //       rest.
                    //
                    object value = zeroValue;

                    //
                    // NOTE: Are we able to continue moving through the items?
                    //
                    if (moveNext)
                    {
                        //
                        // NOTE: Move to the next item.  If this fails, there are
                        //       no more items and we cannot move any farther.
                        //
                        if (!enumerator.MoveNext())
                        {
                            moveNext = false;
                        }

                        //
                        // NOTE: Get the value of the current item.
                        //
                        value = enumerator.Current;
                    }

                    //
                    // NOTE: Add this key/value pair to the dictionary.
                    //
                    this.Add(key, (Enum)value); /* throw */
                }

                return(true);
            }

            return(false);
        }
Ejemplo n.º 2
0
        ///////////////////////////////////////////////////////////////////////

        //
        // WARNING: Do not use this method from the GlobalConfiguration class.
        //
        public static bool TryGetEnumAppSetting(
            string name,      /* in */
            Type enumType,    /* in */
            string oldValue,  /* in */
            out object value, /* out */
            ref Result error  /* out */
            )
        {
            string stringValue;

            if (!TryGetAppSetting(name, out stringValue, ref error))
            {
                value = null;
                return(false);
            }

            object enumValue = null;

            if (EnumOps.IsFlagsEnum(enumType))
            {
                enumValue = Utility.TryParseFlagsEnum(
                    null, enumType, oldValue, stringValue,
                    null, true, true, true, ref error);
            }
            else
            {
                enumValue = Utility.TryParseEnum(
                    enumType, stringValue, true, true,
                    ref error);
            }

            if (!(enumValue is Enum))
            {
                value = null;
                return(false);
            }

            value = enumValue;
            return(true);
        }
Ejemplo n.º 3
0
        ///////////////////////////////////////////////////////////////////////

        public bool TryGetValue(
            string key,
            Type enumType,
            out object value,
            ref Result error
            )
        {
            Enum enumValue;

            if (this.TryGetValue(key, out enumValue))
            {
                value = EnumOps.TryGetEnum(enumType, enumValue, ref error);

                return(true);
            }
            else
            {
                value = EnumOps.TryGetEnum(enumType, 0, ref error);

                return(false);
            }
        }
Ejemplo n.º 4
0
        ///////////////////////////////////////////////////////////////////////////////////////////////

        #region IExecute Members
        public override ReturnCode Execute(
            Interpreter interpreter,
            IClientData clientData,
            ArgumentList arguments,
            ref Result result
            )
        {
            ReturnCode code = ReturnCode.Ok;

            if (interpreter != null)
            {
                if (arguments != null)
                {
                    if (arguments.Count >= 2)
                    {
                        string subCommand = arguments[1];
                        bool   tried      = false;

                        code = ScriptOps.TryExecuteSubCommandFromEnsemble(
                            interpreter, this, clientData, arguments, true,
                            false, ref subCommand, ref tried, ref result);

                        if ((code == ReturnCode.Ok) && !tried)
                        {
                            switch (subCommand)
                            {
                            case "forget":
                            {
                                if (arguments.Count >= 2)
                                {
                                    code = interpreter.PkgForget(
                                        new StringList(arguments, 2), ref result);
                                }
                                else
                                {
                                    result = "wrong # args: should be \"package forget ?package package ...?\"";
                                    code   = ReturnCode.Error;
                                }
                                break;
                            }

                            case "ifneeded":
                            {
                                if ((arguments.Count == 4) || (arguments.Count == 5))
                                {
                                    Version version = null;

                                    code = Value.GetVersion(
                                        arguments[3], interpreter.CultureInfo,
                                        ref version, ref result);

                                    if (code == ReturnCode.Ok)
                                    {
                                        string text = null;

                                        if (arguments.Count == 5)
                                        {
                                            text = arguments[4];
                                        }

                                        code = interpreter.PkgIfNeeded(
                                            arguments[2], version, text, interpreter.PackageFlags,
                                            ref result);
                                    }
                                }
                                else
                                {
                                    result = "wrong # args: should be \"package ifneeded package version ?script?\"";
                                    code   = ReturnCode.Error;
                                }
                                break;
                            }

                            case "indexes":
                            {
                                if ((arguments.Count == 2) || (arguments.Count == 3))
                                {
                                    string pattern = null;

                                    if (arguments.Count == 3)
                                    {
                                        pattern = arguments[2];
                                    }

                                    code = interpreter.PkgIndexes(
                                        pattern, false, ref result);
                                }
                                else
                                {
                                    result = "wrong # args: should be \"package indexes ?pattern?\"";
                                    code   = ReturnCode.Error;
                                }
                                break;
                            }

                            case "info":
                            {
                                if (arguments.Count == 3)
                                {
                                    IPackage package = null;

                                    code = interpreter.GetPackage(
                                        arguments[2], LookupFlags.Default,
                                        ref package, ref result);

                                    if (code == ReturnCode.Ok)
                                    {
                                        bool         scrub = interpreter.IsSafe();
                                        PackageFlags flags = package.Flags;
                                        Guid         id    = AttributeOps.GetObjectId(package);

                                        result = StringList.MakeList(
                                            "kind", package.Kind,
                                            "id", package.Id.Equals(Guid.Empty) ? id : package.Id,
                                            "name", package.Name,
                                            "description", package.Description,
                                            "indexFileName", scrub ? PathOps.ScrubPath(
                                                GlobalState.GetBasePath(), package.IndexFileName) :
                                            package.IndexFileName,
                                            "provideFileName", scrub ? PathOps.ScrubPath(
                                                GlobalState.GetBasePath(), package.ProvideFileName) :
                                            package.ProvideFileName,
                                            "flags", flags,
                                            "loaded", (package.Loaded != null) ? package.Loaded : null,
                                            "ifNeeded", (!scrub && (package.IfNeeded != null)) ?
                                            package.IfNeeded.KeysAndValuesToString(null, false) :
                                            null);
                                    }
                                }
                                else
                                {
                                    result = "wrong # args: should be \"package info name\"";
                                    code   = ReturnCode.Error;
                                }
                                break;
                            }

                            case "loaded":
                            {
                                if ((arguments.Count == 2) || (arguments.Count == 3))
                                {
                                    string pattern = null;

                                    if (arguments.Count == 3)
                                    {
                                        pattern = arguments[2];
                                    }

                                    code = interpreter.PkgLoaded(
                                        pattern, false, false, ref result);
                                }
                                else
                                {
                                    result = "wrong # args: should be \"package loaded ?pattern?\"";
                                    code   = ReturnCode.Error;
                                }
                                break;
                            }

                            case "names":
                            {
                                if ((arguments.Count == 2) || (arguments.Count == 3))
                                {
                                    string pattern = null;

                                    if (arguments.Count == 3)
                                    {
                                        pattern = arguments[2];
                                    }

                                    code = interpreter.PkgNames(
                                        pattern, false, ref result);
                                }
                                else
                                {
                                    result = "wrong # args: should be \"package names ?pattern?\"";
                                    code   = ReturnCode.Error;
                                }
                                break;
                            }

                            case "present":
                            {
                                if (arguments.Count >= 3)
                                {
                                    OptionDictionary options = new OptionDictionary(
                                        new IOption[] {
                                            new Option(null, OptionFlags.None, Index.Invalid, Index.Invalid, "-exact", null),
                                            new Option(null, OptionFlags.None, Index.Invalid, Index.Invalid, Option.EndOfOptions, null)
                                        });

                                    int argumentIndex = Index.Invalid;

                                    code = interpreter.GetOptions(options, arguments, 0, 2, Index.Invalid, false, ref argumentIndex, ref result);

                                    if (code == ReturnCode.Ok)
                                    {
                                        if ((argumentIndex != Index.Invalid) &&
                                            ((argumentIndex + 2) >= arguments.Count))
                                        {
                                            bool exact = false;

                                            if (options.IsPresent("-exact"))
                                            {
                                                exact = true;
                                            }

                                            Version version = null;

                                            if ((argumentIndex + 1) < arguments.Count)
                                            {
                                                code = Value.GetVersion(
                                                    arguments[argumentIndex + 1], interpreter.CultureInfo,
                                                    ref version, ref result);
                                            }

                                            if (code == ReturnCode.Ok)
                                            {
                                                code = interpreter.PresentPackage(
                                                    arguments[argumentIndex], version, exact, ref result);
                                            }
                                        }
                                        else
                                        {
                                            if ((argumentIndex != Index.Invalid) &&
                                                Option.LooksLikeOption(arguments[argumentIndex]))
                                            {
                                                result = OptionDictionary.BadOption(options, arguments[argumentIndex]);
                                            }
                                            else
                                            {
                                                result = "wrong # args: should be \"package present ?-exact? package ?version?\"";
                                            }

                                            code = ReturnCode.Error;
                                        }
                                    }
                                }
                                else
                                {
                                    result = "wrong # args: should be \"package present ?-exact? package ?version?\"";
                                    code   = ReturnCode.Error;
                                }
                                break;
                            }

                            case "provide":
                            {
                                if ((arguments.Count == 3) || (arguments.Count == 4))
                                {
                                    PackageFlags flags = interpreter.PackageFlags;

                                    if (!FlagOps.HasFlags(flags, PackageFlags.NoProvide, true))
                                    {
                                        Version version = null;

                                        if (arguments.Count == 4)
                                        {
                                            code = Value.GetVersion(arguments[3], interpreter.CultureInfo, ref version, ref result);
                                        }

                                        if (code == ReturnCode.Ok)
                                        {
                                            code = interpreter.PkgProvide(arguments[2], version, flags, ref result);
                                        }
                                    }
                                    else
                                    {
                                        //
                                        // HACK: Do nothing, provide no package, and return nothing.
                                        //
                                        result = String.Empty;
                                        code   = ReturnCode.Ok;
                                    }
                                }
                                else
                                {
                                    result = "wrong # args: should be \"package provide package ?version?\"";
                                    code   = ReturnCode.Error;
                                }
                                break;
                            }

                            case "relativefilename":
                            {
                                if ((arguments.Count == 3) || (arguments.Count == 4))
                                {
                                    PathComparisonType pathComparisonType = PathComparisonType.Default;

                                    if (arguments.Count == 4)
                                    {
                                        object enumValue = EnumOps.TryParseFlagsEnum(
                                            interpreter, typeof(PathComparisonType),
                                            pathComparisonType.ToString(), arguments[3],
                                            interpreter.CultureInfo, true, true, true,
                                            ref result);

                                        if (enumValue is EventFlags)
                                        {
                                            pathComparisonType = (PathComparisonType)enumValue;
                                        }
                                        else
                                        {
                                            code = ReturnCode.Error;
                                        }
                                    }

                                    if (code == ReturnCode.Ok)
                                    {
                                        string fileName = null;

                                        code = PackageOps.GetRelativeFileName(
                                            interpreter, arguments[2], pathComparisonType,
                                            ref fileName, ref result);

                                        if (code == ReturnCode.Ok)
                                        {
                                            result = fileName;
                                        }
                                    }
                                }
                                else
                                {
                                    result = "wrong # args: should be \"package relativefilename fileName ?type?\"";
                                    code   = ReturnCode.Error;
                                }
                                break;
                            }

                            case "require":
                            {
                                if (arguments.Count >= 3)
                                {
                                    OptionDictionary options = new OptionDictionary(
                                        new IOption[] {
                                            new Option(null, OptionFlags.None, Index.Invalid, Index.Invalid, "-exact", null),
                                            new Option(null, OptionFlags.None, Index.Invalid, Index.Invalid, Option.EndOfOptions, null)
                                        });

                                    int argumentIndex = Index.Invalid;

                                    code = interpreter.GetOptions(options, arguments, 0, 2, Index.Invalid, false, ref argumentIndex, ref result);

                                    if (code == ReturnCode.Ok)
                                    {
                                        if ((argumentIndex != Index.Invalid) && ((argumentIndex + 2) >= arguments.Count))
                                        {
                                            bool exact = false;

                                            if (options.IsPresent("-exact"))
                                            {
                                                exact = true;
                                            }

                                            Version version = null;

                                            if ((argumentIndex + 1) < arguments.Count)
                                            {
                                                code = Value.GetVersion(
                                                    arguments[argumentIndex + 1], interpreter.CultureInfo,
                                                    ref version, ref result);
                                            }

                                            if (code == ReturnCode.Ok)
                                            {
                                                code = interpreter.RequirePackage(
                                                    arguments[argumentIndex], version, exact, ref result);
                                            }

                                            //
                                            // NOTE: This is a new feature.  If the initial attempt to
                                            //       require a package fails, call the package fallback
                                            //       delegate for the interpreter and then try requiring
                                            //       the package again.
                                            //
                                            if ((code != ReturnCode.Ok) && !ScriptOps.HasFlags(
                                                    interpreter, InterpreterFlags.NoPackageFallback, true))
                                            {
                                                PackageCallback packageFallback = interpreter.PackageFallback;

                                                if (packageFallback != null)
                                                {
                                                    code = packageFallback(
                                                        interpreter, arguments[argumentIndex], version, null,
                                                        interpreter.PackageFlags, exact, ref result);

                                                    if (code == ReturnCode.Ok)
                                                    {
                                                        code = interpreter.RequirePackage(
                                                            arguments[argumentIndex], version, exact, ref result);
                                                    }
                                                }
                                            }

                                            //
                                            // BUGFIX: This is really a new feature.  In the event of a failure
                                            //         here, we now fallback to the "unknown package handler",
                                            //         just like Tcl does.
                                            //
                                            if ((code != ReturnCode.Ok) && !ScriptOps.HasFlags(
                                                    interpreter, InterpreterFlags.NoPackageUnknown, true))
                                            {
                                                string text = interpreter.PackageUnknown + Characters.Space +
                                                              Parser.Quote(arguments[argumentIndex]);

                                                if (version != null)
                                                {
                                                    text += Characters.Space + Parser.Quote(version.ToString());
                                                }

                                                code = interpreter.EvaluateScript(text, ref result);         /* EXEMPT */

                                                if (code == ReturnCode.Ok)
                                                {
                                                    code = interpreter.RequirePackage(
                                                        arguments[argumentIndex], version, exact, ref result);
                                                }
                                            }
                                        }
                                        else
                                        {
                                            if ((argumentIndex != Index.Invalid) &&
                                                Option.LooksLikeOption(arguments[argumentIndex]))
                                            {
                                                result = OptionDictionary.BadOption(options, arguments[argumentIndex]);
                                            }
                                            else
                                            {
                                                result = "wrong # args: should be \"package require ?-exact? package ?version?\"";
                                            }

                                            code = ReturnCode.Error;
                                        }
                                    }
                                }
                                else
                                {
                                    result = "wrong # args: should be \"package require ?-exact? package ?version?\"";
                                    code   = ReturnCode.Error;
                                }
                                break;
                            }

                            case "reset":
                            {
                                if (arguments.Count == 2)
                                {
                                    code = interpreter.ResetPkgIndexes(ref result);

                                    if (code == ReturnCode.Ok)
                                    {
                                        result = String.Empty;
                                    }
                                }
                                else
                                {
                                    result = "wrong # args: should be \"package reset\"";
                                    code   = ReturnCode.Error;
                                }
                                break;
                            }

                            case "scan":
                            {
                                if (arguments.Count >= 2)
                                {
                                    OptionDictionary options = new OptionDictionary(
                                        new IOption[] {
                                            new Option(null, OptionFlags.None, Index.Invalid, Index.Invalid, "-interpreter", null),
                                            new Option(null, OptionFlags.None, Index.Invalid, Index.Invalid, "-preferfilesystem", null),
                                            new Option(null, OptionFlags.None, Index.Invalid, Index.Invalid, "-preferhost", null),
                                            new Option(null, OptionFlags.None, Index.Invalid, Index.Invalid, "-host", null),
                                            new Option(null, OptionFlags.None, Index.Invalid, Index.Invalid, "-normal", null),
                                            new Option(null, OptionFlags.None, Index.Invalid, Index.Invalid, "-nonormal", null),
                                            new Option(null, OptionFlags.None, Index.Invalid, Index.Invalid, "-recursive", null),
                                            new Option(null, OptionFlags.None, Index.Invalid, Index.Invalid, "-resolve", null),
                                            new Option(null, OptionFlags.None, Index.Invalid, Index.Invalid, "-refresh", null),
                                            new Option(null, OptionFlags.None, Index.Invalid, Index.Invalid, "-autopath", null),
                                            new Option(null, OptionFlags.None, Index.Invalid, Index.Invalid, Option.EndOfOptions, null)
                                        });

                                    int argumentIndex = Index.Invalid;

                                    if (arguments.Count > 2)
                                    {
                                        code = interpreter.GetOptions(options, arguments, 0, 2, Index.Invalid, true, ref argumentIndex, ref result);
                                    }
                                    else
                                    {
                                        code = ReturnCode.Ok;
                                    }

                                    if (code == ReturnCode.Ok)
                                    {
                                        lock (interpreter.SyncRoot)         /* TRANSACTIONAL */
                                        {
                                            PackageIndexFlags flags;

                                            if (options.IsPresent("-interpreter"))
                                            {
                                                flags = interpreter.PackageIndexFlags;
                                            }
                                            else
                                            {
                                                flags = PackageIndexFlags.Default;
                                            }

                                            if (options.IsPresent("-preferfilesystem"))
                                            {
                                                flags |= PackageIndexFlags.PreferFileSystem;
                                            }

                                            if (options.IsPresent("-preferhost"))
                                            {
                                                flags |= PackageIndexFlags.PreferHost;
                                            }

                                            if (options.IsPresent("-host"))
                                            {
                                                flags |= PackageIndexFlags.Host;
                                            }

                                            if (options.IsPresent("-normal"))
                                            {
                                                flags |= PackageIndexFlags.Normal;
                                            }

                                            if (options.IsPresent("-nonormal"))
                                            {
                                                flags |= PackageIndexFlags.NoNormal;
                                            }

                                            if (options.IsPresent("-recursive"))
                                            {
                                                flags |= PackageIndexFlags.Recursive;
                                            }

                                            if (options.IsPresent("-refresh"))
                                            {
                                                flags |= PackageIndexFlags.Refresh;
                                            }

                                            if (options.IsPresent("-resolve"))
                                            {
                                                flags |= PackageIndexFlags.Resolve;
                                            }

                                            bool autoPath = false;

                                            if (options.IsPresent("-autopath"))
                                            {
                                                autoPath = true;
                                            }

                                            StringList paths;

                                            if (argumentIndex != Index.Invalid)
                                            {
                                                //
                                                // NOTE: Refresh the specified path list.
                                                //
                                                paths = new StringList(arguments, argumentIndex);
                                            }
                                            else
                                            {
                                                //
                                                // NOTE: Refresh the default path list.
                                                //
                                                paths = GlobalState.GetAutoPathList(interpreter, autoPath);

                                                //
                                                // NOTE: Did they request the auto-path be rebuilt?
                                                //
                                                if (autoPath)
                                                {
                                                    //
                                                    // NOTE: Since the actual auto-path may have changed,
                                                    //       update the variable now.  We disable traces
                                                    //       here because we manually rescan, if necessary,
                                                    //       below.
                                                    //
                                                    code = interpreter.SetLibraryVariableValue(
                                                        VariableFlags.SkipTrace, TclVars.AutoPath,
                                                        (paths != null) ? paths.ToString() : null,
                                                        ref result);
                                                }
                                            }

                                            if (code == ReturnCode.Ok)
                                            {
                                                PackageIndexDictionary packageIndexes = interpreter.CopyPackageIndexes();

                                                if (code == ReturnCode.Ok)
                                                {
                                                    code = PackageOps.FindAll(
                                                        interpreter, paths, flags, ref packageIndexes,
                                                        ref result);
                                                }

                                                if (code == ReturnCode.Ok)
                                                {
                                                    interpreter.PackageIndexes = packageIndexes;
                                                    result = String.Empty;
                                                }
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    result = "wrong # args: should be \"package scan ?options? ?dir dir ...?\"";
                                    code   = ReturnCode.Error;
                                }
                                break;
                            }

                            case "unknown":
                            {
                                if ((arguments.Count == 2) || (arguments.Count == 3))
                                {
                                    if (arguments.Count == 3)
                                    {
                                        interpreter.PackageUnknown = arguments[2];
                                        result = String.Empty;
                                    }
                                    else
                                    {
                                        result = interpreter.PackageUnknown;
                                    }

                                    code = ReturnCode.Ok;
                                }
                                else
                                {
                                    result = "wrong # args: should be \"package unknown ?command?\"";
                                    code   = ReturnCode.Error;
                                }
                                break;
                            }

                            case "vcompare":
                            {
                                if (arguments.Count == 4)
                                {
                                    Version version1 = null;

                                    code = Value.GetVersion(
                                        arguments[2], interpreter.CultureInfo,
                                        ref version1, ref result);

                                    Version version2 = null;

                                    if (code == ReturnCode.Ok)
                                    {
                                        code = Value.GetVersion(
                                            arguments[3], interpreter.CultureInfo,
                                            ref version2, ref result);
                                    }

                                    if (code == ReturnCode.Ok)
                                    {
                                        result = PackageOps.VersionCompare(version1, version2);
                                    }
                                }
                                else
                                {
                                    result = "wrong # args: should be \"package vcompare version1 version2\"";
                                    code   = ReturnCode.Error;
                                }
                                break;
                            }

                            case "versions":
                            {
                                if (arguments.Count == 3)
                                {
                                    code = interpreter.PkgVersions(
                                        arguments[2], ref result);
                                }
                                else
                                {
                                    result = "wrong # args: should be \"package versions package\"";
                                    code   = ReturnCode.Error;
                                }
                                break;
                            }

                            case "vloaded":
                            {
                                if ((arguments.Count == 2) || (arguments.Count == 3))
                                {
                                    string pattern = null;

                                    if (arguments.Count == 3)
                                    {
                                        pattern = arguments[2];
                                    }

                                    code = interpreter.PkgLoaded(
                                        pattern, false, true, ref result);
                                }
                                else
                                {
                                    result = "wrong # args: should be \"package vloaded ?pattern?\"";
                                    code   = ReturnCode.Error;
                                }
                                break;
                            }

                            case "vsatisfies":
                            {
                                if (arguments.Count == 4)
                                {
                                    PackageFlags flags = interpreter.PackageFlags;

                                    if (!FlagOps.HasFlags(flags, PackageFlags.AlwaysSatisfy, true))
                                    {
                                        Version version1 = null;

                                        code = Value.GetVersion(arguments[2], interpreter.CultureInfo, ref version1, ref result);

                                        Version version2 = null;

                                        if (code == ReturnCode.Ok)
                                        {
                                            code = Value.GetVersion(
                                                arguments[3], interpreter.CultureInfo,
                                                ref version2, ref result);
                                        }

                                        if (code == ReturnCode.Ok)
                                        {
                                            result = PackageOps.VersionSatisfies(
                                                version1, version2, false);
                                        }
                                    }
                                    else
                                    {
                                        //
                                        // HACK: Always fake that this was a satisfied package request.
                                        //
                                        result = true;
                                        code   = ReturnCode.Ok;
                                    }
                                }
                                else
                                {
                                    result = "wrong # args: should be \"package vsatisfies version1 version2\"";
                                    code   = ReturnCode.Error;
                                }
                                break;
                            }

                            case "withdraw":
                            {
                                if ((arguments.Count == 3) || (arguments.Count == 4))
                                {
                                    Version version = null;

                                    if (arguments.Count == 4)
                                    {
                                        code = Value.GetVersion(
                                            arguments[3], interpreter.CultureInfo,
                                            ref version, ref result);
                                    }

                                    if (code == ReturnCode.Ok)
                                    {
                                        code = interpreter.WithdrawPackage(
                                            arguments[2], version, ref result);
                                    }
                                }
                                else
                                {
                                    result = "wrong # args: should be \"package withdraw package ?version?\"";
                                    code   = ReturnCode.Error;
                                }
                                break;
                            }

                            default:
                            {
                                result = ScriptOps.BadSubCommand(
                                    interpreter, null, null, subCommand, this, null, null);

                                code = ReturnCode.Error;
                                break;
                            }
                            }
                        }
                    }
                    else
                    {
                        result = "wrong # args: should be \"package arg ?arg ...?\"";
                        code   = ReturnCode.Error;
                    }
                }
                else
                {
                    result = "invalid argument list";
                    code   = ReturnCode.Error;
                }
            }
            else
            {
                result = "invalid interpreter";
                code   = ReturnCode.Error;
            }

            return(code);
        }
Ejemplo n.º 5
0
        public override ReturnCode Execute(
            Interpreter interpreter,
            IClientData clientData,
            ArgumentList arguments,
            ref Result result
            )
        {
            ReturnCode code = ReturnCode.Ok;

            if (interpreter != null)
            {
                if (arguments != null)
                {
                    if (arguments.Count >= 2)
                    {
                        string fileName = arguments[1];

                        if (interpreter.HasChannels(ref result))
                        {
                            MapOpenAccess access      = MapOpenAccess.Default;
                            int           permissions = 0; // NOTE: This is ONLY parsed, NOT used for opening the file.
                            string        type        = null;

                            if (arguments.Count >= 3)
                            {
                                Result enumString = arguments[2];

                                if (!String.IsNullOrEmpty(enumString))
                                {
                                    //
                                    // HACK: Translate illegal mode char "+" to what our Enum uses.
                                    //       This strategy will backfire later if we ever decide to
                                    //       allow parsing of the access mode as "flags" (via GetOptions).
                                    //
                                    enumString = enumString.Replace(Characters.PlusSign.ToString(), "Plus");
                                }

                                code = StringOps.StringToEnumList(interpreter, enumString, ref enumString);

                                if (code == ReturnCode.Ok)
                                {
                                    object enumValue = EnumOps.TryParseEnum(
                                        typeof(MapOpenAccess), enumString,
                                        true, true);

                                    if (enumValue is MapOpenAccess)
                                    {
                                        access = (MapOpenAccess)enumValue;
                                    }
                                    else
                                    {
                                        enumString = ScriptOps.BadValue(
                                            "invalid", "access mode", arguments[2],
                                            Enum.GetNames(typeof(MapOpenAccess)), null, null);

                                        code = ReturnCode.Error;
                                    }
                                }

                                if (code != ReturnCode.Ok)
                                {
                                    //
                                    // NOTE: Transfer local result from above and add to the error info.
                                    //
                                    result = enumString;

                                    Engine.AddErrorInformation(interpreter, result,
                                                               String.Format("{0}    while processing open access modes \"{1}\"",
                                                                             Environment.NewLine, FormatOps.Ellipsis(arguments[2])));
                                }
                            }

                            if ((code == ReturnCode.Ok) && (arguments.Count >= 4))
                            {
                                code = Value.GetInteger2(
                                    (IGetValue)arguments[3], ValueFlags.AnyInteger,
                                    interpreter.CultureInfo, ref permissions, ref result);
                            }

                            if (code == ReturnCode.Ok)
                            {
                                if (arguments.Count >= 5)
                                {
                                    type = arguments[4];
                                }

                                OptionDictionary options = new OptionDictionary(
                                    new IOption[] {
#if CONSOLE
                                    new Option(null, OptionFlags.None, 1, Index.Invalid, "-stdin", null),
                                    new Option(null, OptionFlags.None, 1, Index.Invalid, "-stdout", null),
                                    new Option(null, OptionFlags.None, 1, Index.Invalid, "-stderr", null),
#else
                                    new Option(null, OptionFlags.Unsupported, 1, Index.Invalid, "-stdin", null),
                                    new Option(null, OptionFlags.Unsupported, 1, Index.Invalid, "-stdout", null),
                                    new Option(null, OptionFlags.Unsupported, 1, Index.Invalid, "-stderr", null),
#endif
                                    new Option(null, OptionFlags.MustHaveValue, Index.Invalid, Index.Invalid, "-channelid", null),
                                    new Option(null, OptionFlags.MustHaveIntegerValue, Index.Invalid, Index.Invalid, "-buffersize", null),
                                    new Option(null, OptionFlags.None, Index.Invalid, Index.Invalid, "-autoflush", null),
                                    new Option(typeof(HostStreamFlags), OptionFlags.MustHaveEnumValue, Index.Invalid, Index.Invalid, "-streamflags",
                                               new Variant(HostStreamFlags.Default)),
                                    new Option(typeof(FileOptions), OptionFlags.MustHaveEnumValue, Index.Invalid, Index.Invalid, "-options",
                                               new Variant(FileOptions.None)),
                                    new Option(typeof(FileShare), OptionFlags.MustHaveEnumValue, Index.Invalid, Index.Invalid, "-share",
                                               new Variant(FileShare.Read))
                                });

                                int argumentIndex = Index.Invalid;

                                if (arguments.Count > 5)
                                {
                                    code = interpreter.GetOptions(options, arguments, 0, 5, Index.Invalid, true, ref argumentIndex, ref result);
                                }
                                else
                                {
                                    code = ReturnCode.Ok;
                                }

                                if (code == ReturnCode.Ok)
                                {
                                    if (argumentIndex == Index.Invalid)
                                    {
                                        Variant value     = null;
                                        string  channelId = null;

                                        if (options.IsPresent("-channelid", ref value))
                                        {
                                            channelId = value.ToString();
                                        }

                                        if ((channelId == null) ||
                                            (interpreter.DoesChannelExist(channelId) != ReturnCode.Ok))
                                        {
#if CONSOLE
                                            if (options.IsPresent("-stdin"))
                                            {
                                                //
                                                // NOTE: Enforce the proper access for the standard input
                                                //       channel.
                                                //
                                                if (access == MapOpenAccess.RdOnly)
                                                {
                                                    try
                                                    {
                                                        IStreamHost streamHost = interpreter.Host;

                                                        //
                                                        // NOTE: *WARNING* This option causes the "fileName",
                                                        //       "access", "permissions", and "type" arguments
                                                        //       to be ignored.
                                                        //
                                                        lock (interpreter.SyncRoot) /* TRANSACTIONAL */
                                                        {
                                                            if (streamHost.In == null)
                                                            {
                                                                int?bufferSize = null;

                                                                if (options.IsPresent("-buffersize", ref value))
                                                                {
                                                                    bufferSize = (int)value.Value;
                                                                }

                                                                streamHost.In = (bufferSize != null) ?
                                                                                Console.OpenStandardInput((int)bufferSize) :
                                                                                Console.OpenStandardInput();
                                                            }
                                                        }

                                                        code = interpreter.ModifyStandardChannels(
                                                            streamHost, channelId, ChannelType.Input |
                                                            ChannelType.ErrorOnExist, ref result);

                                                        if (code == ReturnCode.Ok)
                                                        {
                                                            result = (channelId != null) ? channelId : StandardChannel.Input;
                                                        }
                                                    }
                                                    catch (Exception e)
                                                    {
                                                        Engine.SetExceptionErrorCode(interpreter, e);

                                                        result = e;
                                                        code   = ReturnCode.Error;
                                                    }
                                                }
                                                else
                                                {
                                                    result = String.Format(
                                                        "illegal access mode \"{0}\", standard input " +
                                                        "can only be opened using access mode \"{1}\"",
                                                        access, MapOpenAccess.RdOnly);

                                                    code = ReturnCode.Error;
                                                }
                                            }
                                            else if (options.IsPresent("-stdout"))
                                            {
                                                //
                                                // NOTE: Enforce the proper access for the standard output
                                                //       channel.
                                                //
                                                if (access == MapOpenAccess.WrOnly)
                                                {
                                                    try
                                                    {
                                                        IStreamHost streamHost = interpreter.Host;

                                                        //
                                                        // NOTE: *WARNING* This option causes the "fileName",
                                                        //       "access", "permissions", and "type" arguments
                                                        //       to be ignored.
                                                        //
                                                        lock (interpreter.SyncRoot) /* TRANSACTIONAL */
                                                        {
                                                            if (streamHost.Out == null)
                                                            {
                                                                int?bufferSize = null;

                                                                if (options.IsPresent("-buffersize", ref value))
                                                                {
                                                                    bufferSize = (int)value.Value;
                                                                }

                                                                streamHost.Out = (bufferSize != null) ?
                                                                                 Console.OpenStandardOutput((int)bufferSize) :
                                                                                 Console.OpenStandardOutput();
                                                            }
                                                        }

                                                        code = interpreter.ModifyStandardChannels(
                                                            streamHost, channelId, ChannelType.Output |
                                                            ChannelType.ErrorOnExist, ref result);

                                                        if (code == ReturnCode.Ok)
                                                        {
                                                            result = (channelId != null) ? channelId : StandardChannel.Output;
                                                        }
                                                    }
                                                    catch (Exception e)
                                                    {
                                                        Engine.SetExceptionErrorCode(interpreter, e);

                                                        result = e;
                                                        code   = ReturnCode.Error;
                                                    }
                                                }
                                                else
                                                {
                                                    result = String.Format(
                                                        "illegal access mode \"{0}\", standard output " +
                                                        "can only be opened using access mode \"{1}\"",
                                                        access, MapOpenAccess.WrOnly);

                                                    code = ReturnCode.Error;
                                                }
                                            }
                                            else if (options.IsPresent("-stderr"))
                                            {
                                                //
                                                // NOTE: Enforce the proper access for the standard error
                                                //       channel.
                                                //
                                                if (access == MapOpenAccess.WrOnly)
                                                {
                                                    try
                                                    {
                                                        IStreamHost streamHost = interpreter.Host;

                                                        //
                                                        // NOTE: *WARNING* This option causes the "fileName",
                                                        //       "access", "permissions", and "type" arguments
                                                        //       to be ignored.
                                                        //
                                                        lock (interpreter.SyncRoot) /* TRANSACTIONAL */
                                                        {
                                                            if (streamHost.Error == null)
                                                            {
                                                                int?bufferSize = null;

                                                                if (options.IsPresent("-buffersize", ref value))
                                                                {
                                                                    bufferSize = (int)value.Value;
                                                                }

                                                                streamHost.Error = (bufferSize != null) ?
                                                                                   Console.OpenStandardError((int)bufferSize) :
                                                                                   Console.OpenStandardError();
                                                            }
                                                        }

                                                        code = interpreter.ModifyStandardChannels(
                                                            streamHost, channelId, ChannelType.Error |
                                                            ChannelType.ErrorOnExist, ref result);

                                                        if (code == ReturnCode.Ok)
                                                        {
                                                            result = (channelId != null) ? channelId : StandardChannel.Error;
                                                        }
                                                    }
                                                    catch (Exception e)
                                                    {
                                                        Engine.SetExceptionErrorCode(interpreter, e);

                                                        result = e;
                                                        code   = ReturnCode.Error;
                                                    }
                                                }
                                                else
                                                {
                                                    result = String.Format(
                                                        "illegal access mode \"{0}\", standard error " +
                                                        "can only be opened using access mode \"{1}\"",
                                                        access, MapOpenAccess.WrOnly);

                                                    code = ReturnCode.Error;
                                                }
                                            }
                                            else
#endif
                                            {
                                                Stream stream    = null;
                                                bool   autoFlush = false;

                                                switch (type)
                                                {
                                                case null:                      /* FALL-THROUGH */
                                                case /* String.Empty */ "":     /* FALL-THROUGH */
                                                case "file":
                                                {
                                                    try
                                                    {
                                                        HostStreamFlags hostStreamFlags = HostStreamFlags.OpenCommand;
                                                        FileAccess      fileAccess      = FileOps.FileAccessFromAccess(access);
                                                        FileMode        fileMode        = FileOps.FileModeFromAccess(access);
                                                        FileShare       fileShare       = FileShare.Read;

                                                        if (options.IsPresent("-streamflags", ref value))
                                                        {
                                                            hostStreamFlags = (HostStreamFlags)value.Value;
                                                        }

                                                        if (options.IsPresent("-share", ref value))
                                                        {
                                                            fileShare = (FileShare)value.Value;
                                                        }

                                                        int bufferSize = Channel.DefaultBufferSize;

                                                        if (options.IsPresent("-buffersize", ref value))
                                                        {
                                                            bufferSize = (int)value.Value;
                                                        }

                                                        FileOptions fileOptions = FileOptions.None;

                                                        if (options.IsPresent("-options", ref value))
                                                        {
                                                            fileOptions = (FileOptions)value.Value;
                                                        }

                                                        if (options.IsPresent("-autoflush"))
                                                        {
                                                            autoFlush = true;
                                                        }

                                                        bool seekToEof = false;

                                                        //
                                                        // HACK: Check for special case where they want to Append
                                                        //       and Read/ReadWrite.
                                                        //
                                                        if (((fileAccess == FileAccess.Read) ||
                                                             (fileAccess == FileAccess.ReadWrite)) &&
                                                            (FlagOps.HasFlags(access, MapOpenAccess.SeekToEof, true) ||
                                                             FlagOps.HasFlags(access, MapOpenAccess.Append, true)))
                                                        {
                                                            seekToEof = true;
                                                        }

                                                        code = interpreter.GetStream(
                                                            fileName, fileMode, fileAccess, fileShare, bufferSize,
                                                            fileOptions, Channel.StrictGetStream, ref hostStreamFlags,
                                                            ref stream, ref result);

                                                        if (code == ReturnCode.Ok)
                                                        {
                                                            if ((stream != null) && seekToEof)
                                                            {
                                                                stream.Seek(0, SeekOrigin.End);
                                                            }
                                                        }
                                                    }
                                                    catch (Exception e)
                                                    {
                                                        Engine.SetExceptionErrorCode(interpreter, e);

                                                        result = e;
                                                        code   = ReturnCode.Error;
                                                    }
                                                    break;
                                                }

                                                default:
                                                {
                                                    result = String.Format(
                                                        "unsupported channel type \"{0}\"",
                                                        type);

                                                    code = ReturnCode.Error;
                                                    break;
                                                }
                                                }

                                                //
                                                // NOTE: Did we manage to open the file successfully?
                                                //
                                                if (code == ReturnCode.Ok)
                                                {
                                                    StreamFlags flags = StreamFlags.PreventClose;

                                                    if (channelId == null)
                                                    {
                                                        channelId = FormatOps.Id("file", null, interpreter.NextId());
                                                    }

                                                    code = interpreter.AddFileOrSocketChannel(
                                                        channelId, stream, options, flags,
                                                        FlagOps.HasFlags(access, MapOpenAccess.Append, true),
                                                        autoFlush, null, ref result);

                                                    if (code == ReturnCode.Ok)
                                                    {
                                                        result = channelId;
                                                    }
                                                }
                                            }
                                        }
                                        else
                                        {
                                            result = String.Format(
                                                "can't add \"{0}\": channel already exists",
                                                channelId);

                                            code = ReturnCode.Error;
                                        }
                                    }
                                    else
                                    {
                                        result = "wrong # args: should be \"open fileName ?access? ?permissions? ?type? ?options?\"";
                                        code   = ReturnCode.Error;
                                    }
                                }
                            }
                        }
                        else
                        {
                            code = ReturnCode.Error;
                        }
                    }
                    else
                    {
                        result = "wrong # args: should be \"open fileName ?access? ?permissions? ?type? ?options?\"";
                        code   = ReturnCode.Error;
                    }
                }
                else
                {
                    result = "invalid argument list";
                    code   = ReturnCode.Error;
                }
            }
            else
            {
                result = "invalid interpreter";
                code   = ReturnCode.Error;
            }

            return(code);
        }
Ejemplo n.º 6
0
        public override ReturnCode Execute(
            Interpreter interpreter,
            IClientData clientData,
            ArgumentList arguments,
            ref Result result
            )
        {
            ReturnCode code;

            if (interpreter != null)
            {
                if (arguments != null)
                {
                    if (arguments.Count >= 1)
                    {
                        OptionDictionary options = new OptionDictionary(
                            new IOption[] {
                            new Option(null, OptionFlags.Unsafe, Index.Invalid, Index.Invalid, "-force", null),
                            new Option(null, OptionFlags.Unsafe, Index.Invalid, Index.Invalid, "-fail", null),
                            new Option(null, OptionFlags.MustHaveValue, Index.Invalid, Index.Invalid, "-message", null),
                            new Option(null, OptionFlags.None, Index.Invalid, Index.Invalid, "-current", null),
                            new Option(null, OptionFlags.None, Index.Invalid, Index.Invalid, Option.EndOfOptions, null)
                        });

                        int argumentIndex = Index.Invalid;

                        if (arguments.Count > 1)
                        {
                            code = interpreter.GetOptions(options, arguments, 0, 1, Index.Invalid, false, ref argumentIndex, ref result);
                        }
                        else
                        {
                            code = ReturnCode.Ok;
                        }

                        if (code == ReturnCode.Ok)
                        {
                            if ((argumentIndex == Index.Invalid) ||
                                ((argumentIndex + 1) == arguments.Count))
                            {
                                bool force = false;

                                if (options.IsPresent("-force"))
                                {
                                    force = true;
                                }

                                bool fail = false;

                                if (options.IsPresent("-fail"))
                                {
                                    fail = true;
                                }

                                Variant value   = null;
                                string  message = null;

                                if (options.IsPresent("-message", ref value))
                                {
                                    message = value.ToString();
                                }

                                //
                                // NOTE: The default exit code is "success" (i.e. zero).
                                //
                                ExitCode exitCode = ResultOps.SuccessExitCode();

                                if (options.IsPresent("-current"))
                                {
                                    exitCode = interpreter.ExitCode;
                                }

                                //
                                // NOTE: Was an exit code specified in the command?
                                //
                                if (argumentIndex != Index.Invalid)
                                {
                                    object enumValue = EnumOps.TryParseEnum(
                                        typeof(ExitCode), arguments[argumentIndex],
                                        true, true, ref result);

                                    if (enumValue is ExitCode)
                                    {
                                        exitCode = (ExitCode)enumValue;
                                    }
                                    else
                                    {
                                        result = ScriptOps.BadValue(
                                            null, "exit code", arguments[argumentIndex],
                                            Enum.GetNames(typeof(ExitCode)), null, ", or an integer");

                                        code = ReturnCode.Error;
                                    }
                                }

                                //
                                // NOTE: Make sure we succeeded at coverting the exit code to an integer.
                                //
                                if (code == ReturnCode.Ok)
                                {
                                    //
                                    // NOTE: Make sure the interpreter host, if any, agrees to exit (i.e. it may deny the
                                    //       request if the application is doing something that should not be interrupted).
                                    //
                                    code = interpreter.CanExit(exitCode, force, fail, message, ref result);

                                    if (code == ReturnCode.Ok)
                                    {
                                        //
                                        // NOTE: Exit the application (either by marking the current interpreter as "exited"
                                        //       or physically exiting the containing process).
                                        //
                                        TraceOps.DebugTrace(String.Format(
                                                                "Execute: {0}, interpreter = {1}, message = {2}",
                                                                force && fail ?
                                                                "forcibly failing" : force ? "forcibly exiting" : "exiting",
                                                                FormatOps.InterpreterNoThrow(interpreter), FormatOps.WrapOrNull(message)),
                                                            typeof(Exit).Name, TracePriority.Command);

                                        if (force)
                                        {
#if !MONO
                                            if (fail && !CommonOps.Runtime.IsMono())
                                            {
                                                try
                                                {
                                                    //
                                                    // NOTE: Using this method to exit a script is NOT recommended unless
                                                    //       you are trying to prevent damaging another part of the system.
                                                    //
                                                    // MONO: This method is not supported by the Mono runtime.
                                                    //
                                                    Environment.FailFast(message);

                                                    /* NOT REACHED */
                                                    result = "failed to exit process";
                                                    code   = ReturnCode.Error;
                                                }
                                                catch (Exception e)
                                                {
                                                    result = e;
                                                    code   = ReturnCode.Error;
                                                }
                                            }
                                            else
#endif
                                            {
                                                //
                                                // BUGFIX: Try to dispose our containing interpreter now.  We must do
                                                //         this to prevent it from being disposed on a random GC thread.
                                                //
                                                try
                                                {
                                                    interpreter.Dispose();
                                                    interpreter = null;
                                                }
                                                catch (Exception e)
                                                {
                                                    result = e;
                                                    code   = ReturnCode.Error;
                                                }

                                                //
                                                // NOTE: If we could not dispose the interpreter properly, complain;
                                                //       however, keep exiting anyway.
                                                //
                                                if (code != ReturnCode.Ok)
                                                {
                                                    DebugOps.Complain(interpreter, code, result);
                                                }

                                                try
                                                {
                                                    //
                                                    // NOTE: Using this method to exit a script is NOT recommended unless
                                                    //       you are running a standalone script in the Eagle Shell (i.e.
                                                    //       you are not hosted within another application).
                                                    //
                                                    Environment.Exit((int)exitCode);

                                                    /* NOT REACHED */
                                                    result = "failed to exit process";
                                                    code   = ReturnCode.Error;
                                                }
                                                catch (Exception e)
                                                {
                                                    result = e;
                                                    code   = ReturnCode.Error;
                                                }
                                            }
                                        }
                                        else
                                        {
                                            interpreter.ExitCode = exitCode;
                                            interpreter.Exit     = true;

                                            result = String.Empty;
                                            code   = ReturnCode.Ok;
                                        }
                                    }
                                }
                            }
                            else
                            {
                                if ((argumentIndex != Index.Invalid) &&
                                    Option.LooksLikeOption(arguments[argumentIndex]))
                                {
                                    result = OptionDictionary.BadOption(options, arguments[argumentIndex]);
                                }
                                else
                                {
                                    result = "wrong # args: should be \"exit ?options? ?returnCode?\"";
                                }

                                code = ReturnCode.Error;
                            }
                        }
                    }
                    else
                    {
                        result = "wrong # args: should be \"exit ?options? ?returnCode?\"";
                        code   = ReturnCode.Error;
                    }
                }
                else
                {
                    result = "invalid argument list";
                    code   = ReturnCode.Error;
                }
            }
            else
            {
                result = "invalid interpreter";
                code   = ReturnCode.Error;
            }

            return(code);
        }
Ejemplo n.º 7
0
        public override ReturnCode Execute(
            Interpreter interpreter,
            IClientData clientData,
            ArgumentList arguments,
            ref Result result
            )
        {
            ReturnCode code = ReturnCode.Ok;

            if (interpreter != null)
            {
                if (arguments != null)
                {
                    if (arguments.Count >= 2)
                    {
                        string subCommand = arguments[1];
                        bool   tried      = false;

                        code = ScriptOps.TryExecuteSubCommandFromEnsemble(
                            interpreter, this, clientData, arguments, false,
                            false, ref subCommand, ref tried, ref result);

                        if ((code == ReturnCode.Ok) && !tried)
                        {
                            switch (subCommand)
                            {
                            case "active":
                            {
                                if (arguments.Count == 2)
                                {
                                    IEventManager eventManager = interpreter.EventManager;

                                    if (EventOps.ManagerIsOk(eventManager))
                                    {
                                        result = eventManager.Active;
                                        code   = ReturnCode.Ok;
                                    }
                                    else
                                    {
                                        result = "event manager not available";
                                        code   = ReturnCode.Error;
                                    }
                                }
                                else
                                {
                                    result = "wrong # args: should be \"after active\"";
                                    code   = ReturnCode.Error;
                                }
                                break;
                            }

                            case "cancel":
                            {
                                if (arguments.Count >= 3)
                                {
                                    string text;

                                    if (arguments.Count == 3)
                                    {
                                        text = arguments[2];
                                    }
                                    else
                                    {
                                        text = ListOps.Concat(arguments, 2);
                                    }

                                    IEventManager eventManager = interpreter.EventManager;

                                    if (EventOps.ManagerIsOk(eventManager))
                                    {
                                        code = eventManager.CancelEvents(
                                            text, false, false, ref result);
                                    }
                                    else
                                    {
                                        result = "event manager not available";
                                        code   = ReturnCode.Error;
                                    }
                                }
                                else
                                {
                                    result = "wrong # args: should be \"after cancel arg ?arg ...?\"";
                                    code   = ReturnCode.Error;
                                }
                                break;
                            }

                            case "clear":
                            {
                                if (arguments.Count == 2)
                                {
                                    IEventManager eventManager = interpreter.EventManager;

                                    if (EventOps.ManagerIsOk(eventManager))
                                    {
                                        code = eventManager.ClearEvents(ref result);

                                        if (code == ReturnCode.Ok)
                                        {
                                            result = String.Empty;
                                        }
                                    }
                                    else
                                    {
                                        result = "event manager not available";
                                        code   = ReturnCode.Error;
                                    }
                                }
                                else
                                {
                                    result = "wrong # args: should be \"after clear\"";
                                    code   = ReturnCode.Error;
                                }
                                break;
                            }

                            case "counts":
                            {
                                if (arguments.Count == 2)
                                {
                                    IEventManager eventManager = interpreter.EventManager;

                                    if (EventOps.ManagerIsOk(eventManager))
                                    {
                                        result = StringList.MakeList(
                                            "enabled", eventManager.Enabled,
                                            "active", eventManager.Active,
                                            "createEventCount", Event.CreateCount,
                                            "disposeEventCount", Event.DisposeCount,
                                            "queueEventCount", eventManager.QueueEventCount,
                                            "queueIdleEventCount", eventManager.QueueIdleEventCount,
                                            "eventCount", eventManager.EventCount,
                                            "idleEventCount", eventManager.IdleEventCount,
                                            "totalEventCount", eventManager.TotalEventCount,
                                            "maximumEventCount", eventManager.MaximumEventCount,
                                            "maximumIdleEventCount", eventManager.MaximumIdleEventCount,
                                            "maybeDisposeEventCount", eventManager.MaybeDisposeEventCount,
                                            "reallyDisposeEventCount", eventManager.ReallyDisposeEventCount,
                                            "interpreterEventCount", interpreter.EventCount,
#if NATIVE && TCL
                                            "interpreterTclEventCount", interpreter.TclEventCount,
#endif
                                            "interpreterWaitCount", interpreter.WaitCount,
                                            "interpreterWaitSpinCount", interpreter.WaitSpinCount);

                                        code = ReturnCode.Ok;
                                    }
                                    else
                                    {
                                        result = "event manager not available";
                                        code   = ReturnCode.Error;
                                    }
                                }
                                else
                                {
                                    result = "wrong # args: should be \"after counts\"";
                                    code   = ReturnCode.Error;
                                }
                                break;
                            }

                            case "dump":
                            {
                                if (arguments.Count == 2)
                                {
                                    IEventManager eventManager = interpreter.EventManager;

                                    if (EventOps.ManagerIsOk(eventManager))
                                    {
                                        code = eventManager.Dump(ref result);
                                    }
                                    else
                                    {
                                        result = "event manager not available";
                                        code   = ReturnCode.Error;
                                    }
                                }
                                else
                                {
                                    result = "wrong # args: should be \"after dump\"";
                                    code   = ReturnCode.Error;
                                }
                                break;
                            }

                            case "enable":
                            {
                                if ((arguments.Count == 2) || (arguments.Count == 3))
                                {
                                    IEventManager eventManager = interpreter.EventManager;

                                    if (EventOps.ManagerIsOk(eventManager))
                                    {
                                        if (arguments.Count == 3)
                                        {
                                            bool enabled = false;

                                            code = Value.GetBoolean2(
                                                arguments[2], ValueFlags.AnyBoolean,
                                                interpreter.CultureInfo, ref enabled, ref result);

                                            if (code == ReturnCode.Ok)
                                            {
                                                eventManager.Enabled = enabled;
                                            }
                                        }

                                        if (code == ReturnCode.Ok)
                                        {
                                            result = eventManager.Enabled;
                                        }
                                    }
                                    else
                                    {
                                        result = "event manager not available";
                                        code   = ReturnCode.Error;
                                    }
                                }
                                else
                                {
                                    result = "wrong # args: should be \"after enable ?enabled?\"";
                                    code   = ReturnCode.Error;
                                }
                                break;
                            }

                            case "flags":
                            {
                                if ((arguments.Count == 2) || (arguments.Count == 3))
                                {
                                    lock (interpreter.SyncRoot)         /* TRANSACTIONAL */
                                    {
                                        if (arguments.Count == 3)
                                        {
                                            object enumValue = EnumOps.TryParseFlagsEnum(
                                                interpreter, typeof(EventFlags),
                                                interpreter.AfterEventFlags.ToString(),
                                                arguments[2], interpreter.CultureInfo,
                                                true, true, true, ref result);

                                            if (enumValue is EventFlags)
                                            {
                                                interpreter.AfterEventFlags = (EventFlags)enumValue;
                                            }
                                            else
                                            {
                                                code = ReturnCode.Error;
                                            }
                                        }

                                        if (code == ReturnCode.Ok)
                                        {
                                            result = interpreter.AfterEventFlags;
                                        }
                                    }
                                }
                                else
                                {
                                    result = "wrong # args: should be \"after flags ?flags?\"";
                                    code   = ReturnCode.Error;
                                }
                                break;
                            }

                            case "idle":
                            {
                                if (arguments.Count >= 3)
                                {
                                    IEventManager eventManager = interpreter.EventManager;

                                    if (EventOps.ManagerIsOk(eventManager))
                                    {
                                        //
                                        // FIXME: PRI 5: Somewhat arbitrary, we cannot be "idle" with no
                                        //        windows message loop.
                                        //
                                        string   name     = FormatOps.Id(this.Name, null, interpreter.NextId());
                                        DateTime now      = TimeOps.GetUtcNow();
                                        DateTime dateTime = now.AddMilliseconds(EventManager.MinimumIdleWaitTime);
                                        string   text;

                                        if (arguments.Count == 3)
                                        {
                                            text = arguments[2];
                                        }
                                        else
                                        {
                                            text = ListOps.Concat(arguments, 2);
                                        }

                                        IScript script = interpreter.CreateAfterScript(
                                            name, null, null, ScriptTypes.Idle, text,
                                            now, EngineMode.EvaluateScript, ScriptFlags.None,
                                            clientData, true);

                                        code = eventManager.QueueScript(
                                            name, dateTime, script, script.EventFlags,
                                            EventPriority.Idle, ref result);

                                        if (code == ReturnCode.Ok)
                                        {
                                            result = name;
                                        }
                                    }
                                    else
                                    {
                                        result = "event manager not available";
                                        code   = ReturnCode.Error;
                                    }
                                }
                                else
                                {
                                    result = "wrong # args: should be \"after idle arg ?arg ...?\"";
                                    code   = ReturnCode.Error;
                                }
                                break;
                            }

                            case "info":
                            {
                                if ((arguments.Count == 2) || (arguments.Count == 3))
                                {
                                    IEventManager eventManager = interpreter.EventManager;

                                    if (EventOps.ManagerIsOk(eventManager))
                                    {
                                        if (arguments.Count == 3)
                                        {
                                            IEvent @event = null;

                                            code = eventManager.GetEvent(
                                                arguments[2], ref @event, ref result);

                                            if (code == ReturnCode.Ok)
                                            {
                                                if (EventManager.IsScriptEvent(@event))
                                                {
                                                    if (@event.ClientData != null)
                                                    {
                                                        IScript script = @event.ClientData.Data as IScript;

                                                        if (script != null)
                                                        {
                                                            result = script.ToString();
                                                        }
                                                        else
                                                        {
                                                            result = String.Format(
                                                                "event \"{0}\" clientData is not a script",
                                                                arguments[2]);

                                                            code = ReturnCode.Error;
                                                        }
                                                    }
                                                    else
                                                    {
                                                        result = String.Format(
                                                            "event \"{0}\" has invalid clientData",
                                                            arguments[2]);

                                                        code = ReturnCode.Error;
                                                    }
                                                }
                                                else
                                                {
                                                    result = String.Format(
                                                        "event \"{0}\" is not an after event",
                                                        arguments[2]);

                                                    code = ReturnCode.Error;
                                                }
                                            }
                                        }
                                        else
                                        {
                                            StringList list = null;

                                            code = eventManager.ListEvents(null, false, ref list, ref result);

                                            if (code == ReturnCode.Ok)
                                            {
                                                result = list;
                                            }
                                        }
                                    }
                                    else
                                    {
                                        result = "event manager not available";
                                        code   = ReturnCode.Error;
                                    }
                                }
                                else
                                {
                                    result = "wrong # args: should be \"after info ?id?\"";
                                    code   = ReturnCode.Error;
                                }
                                break;
                            }

                            default:
                            {
                                long milliseconds = 0;         // for idle, execute the script right now.

                                code = Value.GetWideInteger2(
                                    subCommand, ValueFlags.AnyWideInteger,
                                    interpreter.CultureInfo, ref milliseconds, ref result);

                                if (code == ReturnCode.Ok)
                                {
                                    if (arguments.Count == 2)
                                    {
                                        //
                                        // BUGBUG: This call will never timeout if we cannot obtain
                                        //         the interpreter lock.
                                        //
                                        code = EventOps.Wait(
                                            interpreter, PerformanceOps.GetMicroseconds(milliseconds),
                                            false, false, ref result);

                                        if (code == ReturnCode.Ok)
                                        {
                                            result = String.Empty;
                                        }
                                    }
                                    else if (arguments.Count >= 3)
                                    {
                                        IEventManager eventManager = interpreter.EventManager;

                                        if (EventOps.ManagerIsOk(eventManager))
                                        {
                                            string   name     = FormatOps.Id(this.Name, null, interpreter.NextId());
                                            DateTime now      = TimeOps.GetUtcNow();
                                            DateTime dateTime = now.AddMilliseconds(milliseconds);
                                            string   text;

                                            if (arguments.Count == 3)
                                            {
                                                text = arguments[2];
                                            }
                                            else
                                            {
                                                text = ListOps.Concat(arguments, 2);
                                            }

                                            IScript script = interpreter.CreateAfterScript(
                                                name, null, null, ScriptTypes.Timer, text,
                                                now, EngineMode.EvaluateScript, ScriptFlags.None,
                                                clientData, false);

                                            code = eventManager.QueueScript(
                                                name, dateTime, script, script.EventFlags,
                                                EventPriority.After, ref result);

                                            if (code == ReturnCode.Ok)
                                            {
                                                result = name;
                                            }
                                        }
                                        else
                                        {
                                            result = "event manager not available";
                                            code   = ReturnCode.Error;
                                        }
                                    }
                                    else
                                    {
                                        result = "wrong # args: should be \"after milliseconds arg ?arg ...?\"";
                                        code   = ReturnCode.Error;
                                    }
                                }
                                else
                                {
                                    result = ScriptOps.BadSubCommand(
                                        interpreter, null, "argument", subCommand, this, null, ", or a number");
                                }
                                break;
                            }
                            }
                        }
                    }
                    else
                    {
                        result = "wrong # args: should be \"after option ?arg ...?\"";
                        code   = ReturnCode.Error;
                    }
                }
                else
                {
                    result = "invalid argument list";
                    code   = ReturnCode.Error;
                }
            }
            else
            {
                result = "invalid interpreter";
                code   = ReturnCode.Error;
            }

            return(code);
        }
Ejemplo n.º 8
0
        ///////////////////////////////////////////////////////////////////////////////////////////////

        #region IExecuteArgument Members
        public override ReturnCode Execute(
            Interpreter interpreter,
            IClientData clientData,
            ArgumentList arguments,
            ref Argument value,
            ref Result error
            )
        {
            ReturnCode code = ReturnCode.Ok;

            if (interpreter != null)
            {
                if (arguments != null)
                {
                    if (arguments.Count == (this.Arguments + 1))
                    {
                        Variant variant1 = null;

                        code = Value.GetVariant(interpreter,
                                                (IGetValue)arguments[1], ValueFlags.AnyVariant,
                                                interpreter.CultureInfo, ref variant1, ref error);

                        int intValue = 0;

                        if (code == ReturnCode.Ok)
                        {
                            code = Value.GetInteger2(
                                (IGetValue)arguments[2], ValueFlags.AnyInteger,
                                interpreter.CultureInfo, ref intValue, ref error);
                        }

                        MidpointRounding rounding = MidpointRounding.ToEven; // TODO: Good default?

                        if (code == ReturnCode.Ok)
                        {
                            object enumValue = EnumOps.TryParseEnum(
                                typeof(MidpointRounding), arguments[3], true,
                                true, ref error);

                            if (enumValue is MidpointRounding)
                            {
                                rounding = (MidpointRounding)enumValue;
                            }
                            else
                            {
                                code = ReturnCode.Error;
                            }
                        }

                        if (code == ReturnCode.Ok)
                        {
                            try
                            {
                                if (variant1.IsDouble())
                                {
                                    //
                                    // NOTE: No FixPrecision, Already rounding.
                                    //
                                    value = Math.Round((double)variant1.Value, intValue, rounding);
                                }
                                else if (variant1.IsDecimal())
                                {
                                    //
                                    // NOTE: No FixPrecision, Already rounding.
                                    //
                                    value = Math.Round((decimal)variant1.Value, intValue, rounding);
                                }
                                else if (variant1.IsWideInteger())
                                {
                                    value = ((long)variant1.Value);
                                }
                                else if (variant1.IsInteger())
                                {
                                    value = ((int)variant1.Value);
                                }
                                else if (variant1.IsBoolean())
                                {
                                    value = ((bool)variant1.Value);
                                }
                                else
                                {
                                    error = String.Format(
                                        "unsupported variant type for function \"{0}\"",
                                        base.Name);

                                    code = ReturnCode.Error;
                                }
                            }
                            catch (Exception e)
                            {
                                Engine.SetExceptionErrorCode(interpreter, e);

                                error = String.Format(
                                    "caught math exception: {0}",
                                    e);

                                code = ReturnCode.Error;
                            }
                        }
                    }
                    else
                    {
                        if (arguments.Count > (this.Arguments + 1))
                        {
                            error = String.Format(
                                "too many arguments for math function \"{0}\"",
                                base.Name);
                        }
                        else
                        {
                            error = String.Format(
                                "too few arguments for math function \"{0}\"",
                                base.Name);
                        }

                        code = ReturnCode.Error;
                    }
                }
                else
                {
                    error = "invalid argument list";
                    code  = ReturnCode.Error;
                }
            }
            else
            {
                error = "invalid interpreter";
                code  = ReturnCode.Error;
            }

            return(code);
        }
Ejemplo n.º 9
0
        ///////////////////////////////////////////////////////////////////////////////////////////////

        #region IExecuteArgument Members
        public override ReturnCode Execute(
            Interpreter interpreter,
            IClientData clientData,
            ArgumentList arguments,
            ref Argument value,
            ref Result error
            )
        {
            ReturnCode code = ReturnCode.Ok;

            if (interpreter != null)
            {
                if (arguments != null)
                {
                    if (arguments.Count == (this.Arguments + 1))
                    {
                        lock (interpreter.SyncRoot) /* TRANSACTIONAL */
                        {
                            object enumValue = EnumOps.TryParseFlagsEnum(
                                interpreter, typeof(ExpressionFlags),
                                interpreter.ExpressionFlags.ToString(),
                                arguments[1], interpreter.CultureInfo,
                                true, true, true, ref error);

                            if (enumValue is ExpressionFlags)
                            {
                                try
                                {
                                    interpreter.ExpressionFlags = (ExpressionFlags)enumValue;
                                    value = interpreter.ExpressionFlags;
                                }
                                catch (Exception e)
                                {
                                    Engine.SetExceptionErrorCode(interpreter, e);

                                    error = String.Format(
                                        "caught math exception: {0}",
                                        e);

                                    code = ReturnCode.Error;
                                }
                            }
                            else
                            {
                                code = ReturnCode.Error;
                            }
                        }
                    }
                    else
                    {
                        if (arguments.Count > (this.Arguments + 1))
                        {
                            error = String.Format(
                                "too many arguments for math function \"{0}\"",
                                base.Name);
                        }
                        else
                        {
                            error = String.Format(
                                "too few arguments for math function \"{0}\"",
                                base.Name);
                        }

                        code = ReturnCode.Error;
                    }
                }
                else
                {
                    error = "invalid argument list";
                    code  = ReturnCode.Error;
                }
            }
            else
            {
                error = "invalid interpreter";
                code  = ReturnCode.Error;
            }

            return(code);
        }
Ejemplo n.º 10
0
        ///////////////////////////////////////////////////////////////////////

        public static IOption FromString(
            Interpreter interpreter,
            string text,
            AppDomain appDomain,
            ValueFlags valueFlags,
            CultureInfo cultureInfo,
            ref Result error
            )
        {
            StringList list = null;

            if (Parser.SplitList(
                    interpreter, text, 0, Length.Invalid, true,
                    ref list, ref error) != ReturnCode.Ok)
            {
                return(null);
            }

            if (list.Count < MinimumElementCount)
            {
                error = String.Format(
                    "cannot create option, only {0} of {1} " +
                    "required elements were specified", list.Count,
                    MinimumElementCount);

                return(null);
            }

            bool allowInteger;
            bool strict;
            bool verbose;
            bool noCase;

            _Public.Value.ExtractTypeValueFlags(
                valueFlags, out allowInteger, out strict,
                out verbose, out noCase);

            object enumValue = EnumOps.TryParseFlagsEnum(
                interpreter, typeof(OptionFlags), null,
                list[0], cultureInfo, allowInteger, strict,
                noCase, ref error);

            if (!(enumValue is OptionFlags))
            {
                return(null);
            }

            OptionFlags optionFlags = (OptionFlags)enumValue;
            string      name        = list[1];

            if (name == null)
            {
                error = "invalid option name";
                return(null);
            }

            int  nextIndex = MinimumElementCount;
            Type type      = null;

            if (FlagOps.HasFlags(
                    optionFlags, OptionFlags.MustBeEnumMask, false))
            {
                if (nextIndex >= list.Count)
                {
                    error = String.Format(
                        "option with {0} or {1} flags must have type name",
                        FormatOps.WrapOrNull(OptionFlags.MustBeEnum),
                        FormatOps.WrapOrNull(OptionFlags.MustBeEnumList));

                    return(null);
                }

                ResultList errors = null;

                if (_Public.Value.GetType(
                        interpreter, list[nextIndex], null, appDomain,
                        _Public.Value.GetTypeValueFlags(optionFlags),
                        cultureInfo, ref type, ref errors) != ReturnCode.Ok)
                {
                    error = errors;
                    return(null);
                }

                nextIndex++;
            }

            Variant value = null;

            if (ScriptOps.GetOptionValue(
                    interpreter, list, type, optionFlags, false, allowInteger,
                    strict, noCase, cultureInfo, ref value, ref nextIndex,
                    ref error) != ReturnCode.Ok)
            {
                return(null);
            }

            int groupIndex = _Constants.Index.Invalid;

            if (nextIndex < list.Count)
            {
                if (_Public.Value.GetInteger2(
                        list[nextIndex], ValueFlags.AnyInteger, cultureInfo,
                        ref groupIndex, ref error) != ReturnCode.Ok)
                {
                    return(null);
                }

                nextIndex++;
            }

            return(new Option(
                       type, optionFlags, groupIndex, _Constants.Index.Invalid,
                       name, value));
        }
Ejemplo n.º 11
0
        ///////////////////////////////////////////////////////////////////////

        public static IOption FromString( /* COMPAT: Eagle beta. */
            Interpreter interpreter,
            string text,
            AppDomain appDomain,
            bool allowInteger,
            bool strict,
            bool verbose,
            bool noCase,
            CultureInfo cultureInfo,
            ref Result error
            )
        {
            StringList list = null;

            if (Parser.SplitList(
                    interpreter, text, 0, Length.Invalid, true,
                    ref list, ref error) != ReturnCode.Ok)
            {
                return(null);
            }

            if (list.Count < StandardElementCount)
            {
                error = String.Format(
                    "cannot create option, only {0} of {1} " +
                    "required elements were specified", list.Count,
                    StandardElementCount);

                return(null);
            }

            Type       type   = null;
            ResultList errors = null;

            if (_Public.Value.GetType(
                    interpreter, list[0], null, appDomain,
                    _Public.Value.GetTypeValueFlags(
                        allowInteger, strict, verbose,
                        noCase), cultureInfo, ref type,
                    ref errors) != ReturnCode.Ok)
            {
                error = errors;
                return(null);
            }

            object enumValue = EnumOps.TryParseFlagsEnum(
                interpreter, typeof(OptionFlags), null,
                list[1], cultureInfo, allowInteger, strict,
                noCase, ref error);

            if (!(enumValue is OptionFlags))
            {
                return(null);
            }

            OptionFlags optionFlags = (OptionFlags)enumValue;
            int         groupIndex  = 0;

            if (_Public.Value.GetInteger2(
                    list[2], ValueFlags.AnyInteger, cultureInfo,
                    ref groupIndex, ref error) != ReturnCode.Ok)
            {
                return(null);
            }

            int index = 0;

            if (_Public.Value.GetInteger2(
                    list[3], ValueFlags.AnyInteger, cultureInfo,
                    ref index, ref error) != ReturnCode.Ok)
            {
                return(null);
            }

            string name = list[4];

            if (name == null)
            {
                error = "invalid option name";
                return(null);
            }

            int     nextIndex = StandardElementCount;
            Variant value     = null;

            if (ScriptOps.GetOptionValue(
                    interpreter, list, type, optionFlags, true, allowInteger,
                    strict, noCase, cultureInfo, ref value, ref nextIndex,
                    ref error) != ReturnCode.Ok)
            {
                return(null);
            }

            return(new Option(
                       type, optionFlags, groupIndex, index, name, value));
        }
Ejemplo n.º 12
0
        public override ReturnCode Execute(
            Interpreter interpreter,
            IClientData clientData,
            ArgumentList arguments,
            ref Result result
            )
        {
            ReturnCode code = ReturnCode.Ok;

            if (interpreter != null)
            {
                if (arguments != null)
                {
                    if ((arguments.Count == 3) || (arguments.Count == 4))
                    {
                        string  channelId = arguments[1];
                        Channel channel   = interpreter.GetChannel(channelId, ref result);

                        if (channel != null)
                        {
                            long offset = 0;

                            code = Value.GetWideInteger2(
                                (IGetValue)arguments[2], ValueFlags.AnyWideInteger,
                                interpreter.CultureInfo, ref offset, ref result);

                            if (code == ReturnCode.Ok)
                            {
                                SeekOrigin origin = SeekOrigin.Begin;

                                if (arguments.Count >= 4)
                                {
                                    object enumValue = EnumOps.TryParseEnum(
                                        typeof(MapSeekOrigin), arguments[3],
                                        true, true);

                                    if (enumValue is MapSeekOrigin)
                                    {
                                        origin = (SeekOrigin)enumValue;
                                    }
                                    else
                                    {
                                        result = String.Format(
                                            "bad origin \"{0}\": must be start, current, or end",
                                            arguments[3]);

                                        code = ReturnCode.Error;
                                    }
                                }

                                if (code == ReturnCode.Ok)
                                {
                                    try
                                    {
                                        if (channel.CanSeek)
                                        {
                                            channel.Seek(offset, origin);
                                            result = String.Empty;
                                        }
                                        else
                                        {
                                            result = String.Format(
                                                "error during seek on \"{0}\": invalid argument",
                                                channelId);

                                            code = ReturnCode.Error;
                                        }
                                    }
                                    catch (Exception e)
                                    {
                                        Engine.SetExceptionErrorCode(interpreter, e);

                                        result = e;
                                        code   = ReturnCode.Error;
                                    }
                                }
                            }
                        }
                        else
                        {
                            code = ReturnCode.Error;
                        }
                    }
                    else
                    {
                        result = "wrong # args: should be \"seek channelId offset ?origin?\"";
                        code   = ReturnCode.Error;
                    }
                }
                else
                {
                    result = "invalid argument list";
                    code   = ReturnCode.Error;
                }
            }
            else
            {
                result = "invalid interpreter";
                code   = ReturnCode.Error;
            }

            return(code);
        }
Ejemplo n.º 13
0
        ///////////////////////////////////////////////////////////////////////////////////////

        #region IExecute Members
        public override ReturnCode Execute(
            Interpreter interpreter,
            IClientData clientData,
            ArgumentList arguments,
            ref Result result
            )
        {
            if (interpreter != null)
            {
                if (arguments != null)
                {
                    if (arguments.Count >= 2)
                    {
                        VariableFlags flags = VariableFlags.None;

                        object enumValue = EnumOps.TryParseFlagsEnum(
                            interpreter, typeof(VariableFlags),
                            flags.ToString(), arguments[1],
                            interpreter.CultureInfo, true, true,
                            true, ref result);

                        if (enumValue is VariableFlags)
                        {
                            flags = (VariableFlags)enumValue;

                            if (arguments.Count > 2)
                            {
                                for (int argumentIndex = 2;
                                     argumentIndex < arguments.Count;
                                     argumentIndex++)
                                {
                                    if (interpreter.UnsetVariable(flags,
                                                                  arguments[argumentIndex],
                                                                  ref result) != ReturnCode.Ok)
                                    {
                                        return(ReturnCode.Error);
                                    }
                                }

                                result = String.Empty;
                                return(ReturnCode.Ok);
                            }

                            //
                            // NOTE: Do nothing if no more arguments supplied,
                            //       so as to match command documentation
                            //       (COMPAT: Tcl).
                            //
                            result = String.Empty;
                            return(ReturnCode.Ok);
                        }
                        else
                        {
                            return(ReturnCode.Error);
                        }
                    }
                    else
                    {
                        result = "wrong # args: should be \"unsetf varFlags ?varName varName ...?\"";
                        return(ReturnCode.Error);
                    }
                }
                else
                {
                    result = "invalid argument list";
                    return(ReturnCode.Error);
                }
            }
            else
            {
                result = "invalid interpreter";
                return(ReturnCode.Error);
            }
        }
Ejemplo n.º 14
0
        ///////////////////////////////////////////////////////////////////////

#if XML
        private static ReturnCode FromDocument(
            XmlDocument document,
            InterpreterSettings interpreterSettings,
            ref Result error
            )
        {
            if (document == null)
            {
                error = "invalid xml document";
                return(ReturnCode.Error);
            }

            if (interpreterSettings == null)
            {
                error = "invalid interpreter settings";
                return(ReturnCode.Error);
            }

            XmlElement documentElement = document.DocumentElement;

            if (documentElement == null)
            {
                error = "invalid xml document element";
                return(ReturnCode.Error);
            }

            XmlNode node;

            node = documentElement.SelectSingleNode("Args");

            if ((node != null) && !String.IsNullOrEmpty(node.InnerText))
            {
                StringList list = null;

                if (Parser.SplitList(
                        null, node.InnerText, 0, Length.Invalid, false,
                        ref list, ref error) == ReturnCode.Ok)
                {
                    interpreterSettings.Args = list;
                }
                else
                {
                    return(ReturnCode.Error);
                }
            }

            node = documentElement.SelectSingleNode("CreateFlags");

            if ((node != null) && !String.IsNullOrEmpty(node.InnerText))
            {
                object enumValue = EnumOps.TryParseEnum(
                    typeof(CreateFlags), node.InnerText,
                    true, true, ref error);

                if (enumValue is CreateFlags)
                {
                    interpreterSettings.CreateFlags = (CreateFlags)enumValue;
                }
                else
                {
                    return(ReturnCode.Error);
                }
            }

            node = documentElement.SelectSingleNode("InitializeFlags");

            if ((node != null) && !String.IsNullOrEmpty(node.InnerText))
            {
                object enumValue = EnumOps.TryParseEnum(
                    typeof(InitializeFlags), node.InnerText,
                    true, true, ref error);

                if (enumValue is InitializeFlags)
                {
                    interpreterSettings.InitializeFlags = (InitializeFlags)enumValue;
                }
                else
                {
                    return(ReturnCode.Error);
                }
            }

            node = documentElement.SelectSingleNode("ScriptFlags");

            if ((node != null) && !String.IsNullOrEmpty(node.InnerText))
            {
                object enumValue = EnumOps.TryParseEnum(
                    typeof(ScriptFlags), node.InnerText,
                    true, true, ref error);

                if (enumValue is ScriptFlags)
                {
                    interpreterSettings.ScriptFlags = (ScriptFlags)enumValue;
                }
                else
                {
                    return(ReturnCode.Error);
                }
            }

            node = documentElement.SelectSingleNode("InterpreterFlags");

            if ((node != null) && !String.IsNullOrEmpty(node.InnerText))
            {
                object enumValue = EnumOps.TryParseEnum(
                    typeof(InterpreterFlags), node.InnerText,
                    true, true, ref error);

                if (enumValue is InterpreterFlags)
                {
                    interpreterSettings.InterpreterFlags = (InterpreterFlags)enumValue;
                }
                else
                {
                    return(ReturnCode.Error);
                }
            }

            node = documentElement.SelectSingleNode("AutoPathList");

            if ((node != null) && !String.IsNullOrEmpty(node.InnerText))
            {
                StringList list = null;

                if (Parser.SplitList(
                        null, node.InnerText, 0, Length.Invalid, false,
                        ref list, ref error) == ReturnCode.Ok)
                {
                    interpreterSettings.AutoPathList = list;
                }
                else
                {
                    return(ReturnCode.Error);
                }
            }

            return(ReturnCode.Ok);
        }
Ejemplo n.º 15
0
        ///////////////////////////////////////////////////////////////////////

        //
        // HACK: This is a horrible hack to workaround the issue with not being
        //       able to use plugin enumerated types from the "primary"
        //       application domain when the plugin has been loaded in isolated
        //       mode.
        //
        public static ReturnCode FixupOptions(
            IPluginData pluginData,
            OptionDictionary options,
            bool strict,
            ref Result error
            )
        {
            if (pluginData == null)
            {
                if (strict)
                {
                    error = "invalid plugin data";
                    return(ReturnCode.Error);
                }

                return(ReturnCode.Ok);
            }

            if (options == null)
            {
                if (strict)
                {
                    error = "invalid options";
                    return(ReturnCode.Error);
                }

                return(ReturnCode.Ok);
            }

            if (!IsIsolated(pluginData))
            {
                return(ReturnCode.Ok);
            }

            Assembly assembly = pluginData.Assembly;

            foreach (KeyValuePair <string, IOption> pair in options)
            {
                IOption option = pair.Value;

                if (option == null)
                {
                    continue;
                }

                //
                // HACK: Skip options that do not have enumerated types.
                //       For now, these are the only options we really have to
                //       worry about because they are the only ones that can
                //       directly refer to user-defined types [of any kind].
                //
                if (!option.HasFlags(OptionFlags.MustBeEnum, true))
                {
                    continue;
                }

                //
                // NOTE: Grab the enumerated (?) type and figure out if it
                //       came from the plugin assembly.  If not, ignore it and
                //       continue.
                //
                Type type = option.Type;

                if ((type == null) || !type.IsEnum ||
                    !Object.ReferenceEquals(type.Assembly, assembly))
                {
                    continue;
                }

                //
                // NOTE: Get the current value of the option.
                //
                object   oldValue = option.InnerValue;
                TypeCode typeCode = TypeCode.Empty;

                //
                // NOTE: Attempt to get the new value for the integral type for
                //       the enumeration value of this option, if any.  We must
                //       do this even if the original value is null because we
                //       must have the type code to properly reset the option
                //       flags.
                //
                object newValue = EnumOps.ConvertToTypeCodeValue(
                    type, (oldValue != null) ? oldValue : 0, ref typeCode,
                    ref error);

                if (newValue == null)
                {
                    return(ReturnCode.Error);
                }

                //
                // NOTE: Get the option flags required for the integral type.
                //
                OptionFlags flags = GetEnumOptionFlags(typeCode, strict);

                if (flags == OptionFlags.None)
                {
                    error = String.Format(
                        "unsupported type code for enumerated type \"{0}\"",
                        type);

                    return(ReturnCode.Error);
                }

                //
                // NOTE: Special handling for "flags" enumerations here.
                //
                if (EnumOps.IsFlagsEnum(type))
                {
                    //
                    // HACK: Substitute our placeholder flags enumerated type.
                    //       It does not know about the textual values provided
                    //       by the actual enumerated type; however, at least
                    //       they can use the custom flags enumeration handling
                    //       (i.e. the "+" and "-" operators, etc).
                    //
                    option.Type = typeof(StubFlagsEnum);
                }
                else
                {
                    //
                    // NOTE: Remove the MustBeEnum flag for this option and add
                    //       the flag(s) needed for its integral type.
                    //
                    option.Flags &= ~OptionFlags.MustBeEnum;
                    option.Flags |= flags;

                    //
                    // NOTE: Clear the type for the option.  The type property
                    //       is only meaningful for enumeration-based options
                    //       and we are converting this option to use some kind
                    //       of integral type.
                    //
                    option.Type = null;
                }

                //
                // NOTE: If necessary, set the new [default] value for this
                //       option to the one we converted to an integral type
                //       value above.  If the old (original) value was null, we
                //       just discard the new value which will be zero anyhow.
                //
                option.Value = (oldValue != null) ? new Variant(newValue) : null;
            }

            return(ReturnCode.Ok);
        }
Ejemplo n.º 16
0
        ///////////////////////////////////////////////////////////////////////////////////////

        #region IExecute Members
        public override ReturnCode Execute(
            Interpreter interpreter,
            IClientData clientData,
            ArgumentList arguments,
            ref Result result
            )
        {
            ReturnCode code = ReturnCode.Ok;

            if (interpreter != null)
            {
                if (arguments != null)
                {
                    if ((arguments.Count == 3) || (arguments.Count == 4))
                    {
                        VariableFlags flags = VariableFlags.None;

                        object enumValue = EnumOps.TryParseFlagsEnum(
                            interpreter, typeof(VariableFlags),
                            flags.ToString(), arguments[1],
                            interpreter.CultureInfo, true, true,
                            true, ref result);

                        if (enumValue is VariableFlags)
                        {
                            flags = (VariableFlags)enumValue;

                            if (arguments.Count == 3)
                            {
                                code = interpreter.GetVariableValue(
                                    flags, arguments[2], ref result, ref result);
                            }
                            else if (arguments.Count == 4)
                            {
                                code = interpreter.SetVariableValue(
                                    flags, arguments[2], arguments[3], null, ref result);

                                if (code == ReturnCode.Ok)
                                {
                                    //
                                    // NOTE: Maybe it was append mode?  Re-get the value now.
                                    //
                                    code = interpreter.GetVariableValue(
                                        flags, arguments[2], ref result, ref result);
                                }
                            }
                        }
                        else
                        {
                            code = ReturnCode.Error;
                        }
                    }
                    else
                    {
                        result = "wrong # args: should be \"setf varFlags varName ?newValue?\"";
                        code   = ReturnCode.Error;
                    }
                }
                else
                {
                    result = "invalid argument list";
                    code   = ReturnCode.Error;
                }
            }
            else
            {
                result = "invalid interpreter";
                code   = ReturnCode.Error;
            }

            return(code);
        }
Ejemplo n.º 17
0
        public override ReturnCode Execute(
            Interpreter interpreter,
            IClientData clientData,
            ArgumentList arguments,
            ref Result result
            )
        {
            ReturnCode code = ReturnCode.Ok;

            if (interpreter != null)
            {
                if (arguments != null)
                {
                    if (arguments.Count >= 2)
                    {
                        string  channelId = arguments[1];
                        Channel channel   = interpreter.GetChannel(channelId, ref result);

                        if (channel != null)
                        {
                            try
                            {
                                if (arguments.Count >= 4)
                                {
                                    OptionDictionary options = new OptionDictionary(
                                        new IOption[] {
                                        new Option(null, OptionFlags.MustHaveBooleanValue, Index.Invalid, Index.Invalid, "-blocking", null),
                                        new Option(null, OptionFlags.MustHaveEncodingValue, Index.Invalid, Index.Invalid, "-encoding", null),
                                        new Option(null, OptionFlags.MustHaveListValue, Index.Invalid, Index.Invalid, "-translation", null)
                                    });

                                    int argumentIndex = Index.Invalid;

                                    code = interpreter.GetOptions(options, arguments, 0, 2, Index.Invalid, true, ref argumentIndex, ref result);

                                    if (code == ReturnCode.Ok)
                                    {
                                        if (argumentIndex == Index.Invalid)
                                        {
                                            Variant value        = null;
                                            bool?   blockingMode = null;

                                            if (options.IsPresent("-blocking"))
                                            {
                                                blockingMode = (bool)value.Value;
                                            }

                                            Encoding encoding = null;

                                            if (options.IsPresent("-encoding", ref value))
                                            {
                                                encoding = (Encoding)value.Value;
                                            }

                                            StringList translationNames = null;

                                            if (options.IsPresent("-translation", ref value))
                                            {
                                                translationNames = (StringList)value.Value;
                                            }

                                            StreamTranslationList translation = null;

                                            if (translationNames != null)
                                            {
                                                if ((translationNames.Count == 1) || (translationNames.Count == 2))
                                                {
                                                    translation = new StreamTranslationList();

                                                    foreach (string translationName in translationNames)
                                                    {
                                                        object enumValue = EnumOps.TryParseEnum(
                                                            typeof(StreamTranslation), translationName,
                                                            true, true);

                                                        if (enumValue is StreamTranslation)
                                                        {
                                                            translation.Add((StreamTranslation)enumValue);
                                                        }
                                                        else
                                                        {
                                                            result = ScriptOps.BadValue(
                                                                null, "value for -translation", translationName,
                                                                Enum.GetNames(typeof(StreamTranslation)),
                                                                null, null);

                                                            code = ReturnCode.Error;
                                                            break;
                                                        }
                                                    }
                                                }
                                                else
                                                {
                                                    result = "bad value for -translation: must be a one or two element list";
                                                    code   = ReturnCode.Error;
                                                }
                                            }

                                            if (code == ReturnCode.Ok)
                                            {
                                                if (blockingMode != null)
                                                {
                                                    channel.SetBlockingMode((bool)blockingMode);
                                                }

                                                if (encoding != null)
                                                {
                                                    channel.SetEncoding(encoding);
                                                }

                                                if (translation != null)
                                                {
                                                    channel.SetTranslation(translation);
                                                }

                                                result = String.Empty;
                                            }
                                        }
                                        else
                                        {
                                            result = "wrong # args: should be \"fconfigure channelId ?optionName? ?value?\"";
                                            code   = ReturnCode.Error;
                                        }
                                    }
                                }
                                else if (arguments.Count == 3)
                                {
                                    OptionDictionary options = new OptionDictionary(
                                        new IOption[] {
                                        new Option(null, OptionFlags.MustHaveBooleanValue, Index.Invalid, Index.Invalid, "-blocking", null),
                                        new Option(null, OptionFlags.None, Index.Invalid, Index.Invalid, "-encoding", null),
                                        new Option(null, OptionFlags.None, Index.Invalid, Index.Invalid, "-translation", null)
                                    });

                                    int argumentIndex = Index.Invalid;

                                    code = interpreter.GetOptions(options, arguments, 0, 2, Index.Invalid, true, ref argumentIndex, ref result);

                                    if (code == ReturnCode.Ok)
                                    {
                                        if (argumentIndex == Index.Invalid)
                                        {
                                            StringList list = new StringList();

                                            if (options.IsPresent("-blocking"))
                                            {
                                                list.Add(channel.GetBlockingMode().ToString());
                                            }

                                            if (options.IsPresent("-encoding"))
                                            {
                                                list.Add(channel.GetEncoding().WebName);
                                            }

                                            if (options.IsPresent("-translation"))
                                            {
                                                list.Add(channel.GetTranslation().ToString());
                                            }

                                            if (list.Count > 1)
                                            {
                                                result = list;
                                            }
                                            else if (list.Count == 1)
                                            {
                                                result = list[0];
                                            }
                                            else
                                            {
                                                result = String.Empty;
                                            }
                                        }
                                        else
                                        {
                                            result = "wrong # args: should be \"fconfigure channelId ?optionName? ?value?\"";
                                            code   = ReturnCode.Error;
                                        }
                                    }
                                }
                                else
                                {
                                    Encoding encoding = channel.GetEncoding();
                                    StreamTranslationList translation = channel.GetTranslation();

                                    result = StringList.MakeList(
                                        "-blocking", channel.GetBlockingMode(),
                                        "-encoding", (encoding != null) ?
                                        encoding.WebName : StringOps.NullEncodingName,
                                        "-translation", translation);
                                }
                            }
                            catch (Exception e)
                            {
                                Engine.SetExceptionErrorCode(interpreter, e);

                                result = e;
                                code   = ReturnCode.Error;
                            }
                        }
                        else
                        {
                            code = ReturnCode.Error;
                        }
                    }
                    else
                    {
                        result = "wrong # args: should be \"fconfigure channelId ?optionName? ?value?\"";
                        code   = ReturnCode.Error;
                    }
                }
                else
                {
                    result = "invalid argument list";
                    code   = ReturnCode.Error;
                }
            }
            else
            {
                result = "invalid interpreter";
                code   = ReturnCode.Error;
            }

            return(code);
        }