Пример #1
0
 private void Initialize()
 {
     _js = _webView.CreateGlobalJavascriptObject("sharpAngieBridge");
     _js.Bind("initialize", false, (x, y) => _bridge.Initialize(string.Empty));
     _js.Bind("setProperty", false, SetViewModelProperty);
     _js.Bind("invokeMethod", false, InvokeViewModelMethod);
 }
Пример #2
0
        /// <summary>
        /// Handle a request.
        /// </summary>
        /// <param name="pDisplay">The display which called this function.</param>
        /// <param name="pSurface">The surface which this display is hosted on.</param>
        /// <param name="dArguments">A dictionary of arguments which are passed to the function as parameters.</param>
        /// <returns>True if the request was processed sucessfully.  False if there was an error.</returns>
        public bool ProcessRequest(Display pDisplay, Surface pSurface, JSObject dArguments)
        {
            // Find the new surface.
            var pTargetSurface = Authority.FindSurface(dArguments.GetValueOrDefault("target", ""));
            if (pTargetSurface == null)
            {
                Log.Write("Cannot swap display to target surface.  Missing valid 'target' parameter.", pDisplay.ToString(), Log.Type.DisplayWarning);
                return false;
            }

            // Check the surface this view is on is not our target.
            if (pTargetSurface == pDisplay.ActiveSurface)
            {
                Log.Write("Cannot swap display to target surface because it is already there.", pDisplay.ToString(), Log.Type.DisplayWarning);
                return false;
            }

            // If the target surface has a display, get a reference and remove it.
            Display pOtherView = pTargetSurface.ActiveDisplay;
            if (pOtherView != null)
                Authority.RemoveDisplay(pOtherView);

            // Remove this display from this surface and put it on the target surface.
            Authority.RemoveDisplay(pDisplay);
            Authority.ShowDisplay(pDisplay, pTargetSurface);

            // Now put the other display on the original surface.
            if (pOtherView != null)
                Authority.ShowDisplay(pOtherView, pSurface);

            // Boom.
            return true;
        }
Пример #3
0
    // Use this for initialization
    public void Create()
    {
        ship = GetComponent<Ship> ();
        fleetAILoader = ship.fleet.GetComponent<FleetAILoader>();

        jsobj = new JSObject(fleetAILoader.GetEngine(),ship);
    }
Пример #4
0
 internal static JSObject parseInt(JSObject thisBind, Arguments args)
 {
     double result = double.NaN;
     var radixo = args[1];
     double dradix = radixo.IsExist ? Tools.JSObjectToDouble(radixo) : 0;
     int radix;
     if (double.IsNaN(dradix) || double.IsInfinity(dradix))
         radix = 0;
     else
         radix = (int)((long)dradix & 0xFFFFFFFF);
     if (radix != 0 && (radix < 2 || radix > 36))
         return Number.NaN;
     var source = args[0];
     if (source.valueType == JSObjectType.Int)
         return source;
     if (source.valueType == JSObjectType.Double)
         return double.IsInfinity(source.dValue) || double.IsNaN(source.dValue) ?
             Number.NaN : source.dValue == 0.0 ? (Number)0 : // +0 и -0 должны стать равными
             (Number)System.Math.Truncate(source.dValue);
     var arg = source.ToString().Trim(Tools.TrimChars);
     if (!string.IsNullOrEmpty(arg))
         Tools.ParseNumber(arg, out result, radix, Tools.ParseNumberOptions.AllowAutoRadix);
     if (double.IsInfinity(result))
         return Number.NaN;
     return System.Math.Truncate(result);
 }
Пример #5
0
 public override JSObject Invoke(JSObject thisBind, Arguments args)
 {
     var res = del(thisBind, args);
     if (res == null)
         return JSObject.Null;
     return res;
 }
Пример #6
0
        public Ribbon()
        {
            InitializeComponent();
            BrowserUtility.InitBrowserUtility();

            // Register the test page component with command info
            _testComponent = new TestPageComponent();
            PageManager.Instance.AddPageComponent(_testComponent);

            _ribbon = new JSObject();
            _ribbon.SetField<bool>("initStarted", false);
            _ribbon.SetField<bool>("buildMinimized", true);
            _ribbon.SetField<bool>("launchedByKeyboard", false);
            _ribbon.SetField<bool>("initialTabSelectedByUser", false);
            _ribbon.SetField<string>("initialTabId", "Ribbon.Read");

            Anchor readTabA = (Anchor)Browser.Document.GetById(ReadTabId).FirstChild;
            Anchor libraryTabA = (Anchor)Browser.Document.GetById(LibraryTabId).FirstChild;
            Anchor documentTabA = (Anchor)Browser.Document.GetById(DocumentTabId).FirstChild;

            readTabA.Click += RibbonStartInit;
            libraryTabA.Click += RibbonStartInit;
            documentTabA.Click += RibbonStartInit;

            Browser.Window.Resize += HandleWindowResize;
        }
        private JSGenericObject MappNested(object ifrom, JSObject resobject, JSGenericObject gres)
        {
            if (ifrom == null)
                return gres;

            IEnumerable<PropertyInfo> propertyInfos = ifrom.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);

            foreach (PropertyInfo propertyInfo in propertyInfos.Where(p => p.CanRead))
            {
                string pn = propertyInfo.Name;
                object childvalue = null;
                try
                {
                    childvalue = propertyInfo.GetValue(ifrom, null); 
                }
                catch(Exception e)
                {
                    Trace.WriteLine(string.Format("MVVM for awesomium: Unable to convert property {0} from {1} exception {2}", pn, ifrom, e));
                    continue;
                }

                IJSCSGlue childres = Map(childvalue);

                resobject[pn] = childres.JSValue;
                gres.Attributes[pn] = childres;
            }

            return gres;
        }      
Пример #8
0
 internal static JSObject refreshGlobalObjectProto()
 {
     thisProto = CreateObject();
     thisProto.oValue = thisProto;
     thisProto.attributes |= JSObjectAttributesInternal.ReadOnly | JSObjectAttributesInternal.Immutable | JSObjectAttributesInternal.DoNotEnum | JSObjectAttributesInternal.DoNotDelete;
     return thisProto;
 }
Пример #9
0
 private JSValue Fib_1 (JSFunction function, JSObject @this, JSValue [] args)
 {
     return args[0].NumberValue <= 1 ? new JSValue (@this.Context, 1) : new JSValue (@this.Context,
         Fib_1 (function, @this, new [] { new JSValue (@this.Context, args[0].NumberValue - 1) }).NumberValue +
         Fib_1 (function, @this, new [] { new JSValue (@this.Context, args[0].NumberValue - 2) }).NumberValue
     );
 }
Пример #10
0
        private JSValue Check(JSObject ires)
        {
            if (ires == null)
                throw ExceptionHelper.NoKoExtension();

            return ires;
        }
Пример #11
0
        /// <summary>
        /// Handle a request.
        /// </summary>
        /// <param name="pDisplay">The display which called this function.</param>
        /// <param name="pSurface">The surface which this display is hosted on.</param>
        /// <param name="dArguments">A dictionary of arguments which are passed to the function as parameters.</param>
        /// <returns>True if the request was processed sucessfully.  False if there was an error.</returns>
        public bool ProcessRequest(Display pDisplay, Surface pSurface, JSObject dArguments)
        {
            // Check we have a function to return the results too.
            if (!dArguments.HasProperty("callback")) throw new Exception("Missing 'callback' argument.");

            // Return a list of surface names.
            JSValue[] lSurfaces = (from pSurf in Authority.Surfaces select new JSValue(pSurf.Identifier)).ToArray();

            // If that function is a string.
            var jsValue = dArguments["callback"];
            if (jsValue.IsString)
            {
                pDisplay.AsyncCallGlobalFunction(jsValue.ToString(), lSurfaces);
                return true;
            }

            /*
            // If it is a function.
            else if (jsValue.IsObject)
            {
                ((JSObject)jsValue).Invoke("call", lSurfaces);
                return true;
            }
            */

            // Throw the error.
            throw new Exception("Unknown type specified in 'callback' argument.  Expected string.");
        }
Пример #12
0
        public override dynamic GetPrototype()
        {
            dynamic p = new JSObject();
            p.toString = p.valueOf = new Func<dynamic, string>((self) => self._primitiveValue);

            return GetPrototype(this.GetType().Name, p);
        }
Пример #13
0
        /// <summary>
        /// Handle a request.
        /// </summary>
        /// <param name="pDisplay">The display which called this function.</param>
        /// <param name="pSurface">The surface which this display is hosted on.</param>
        /// <param name="dArguments">A dictionary of arguments which are passed to the function as parameters.</param>
        /// <returns>True if the request was processed sucessfully.  False if there was an error.</returns>
        public bool ProcessRequest(Display pDisplay, Surface pSurface, JSObject dArguments)
        {
            // Check we have a sound file.
            var sSound = dArguments.GetValueOrDefault("file", "");
            if (sSound == null || sSound == "")
            {
                Log.Write("Cannot play sound.  Are you missing a 'file' parameter.", pDisplay.ToString(), Log.Type.DisplayWarning);
                return false;
            }

            // Attempt to play it.
            try
            {
                SoundPlayer pSound = new SoundPlayer(sSound);
                pSound.Play();
                return true;
            }
            
            // Log warnings.
            catch (Exception e)
            {
                Log.Write("Cannot play sound. " + e.Message, pDisplay.ToString(), Log.Type.DisplayWarning);
                return false;
            }
        }
Пример #14
0
 public static String charAt(JSObject self, Arguments pos)
 {
     var strValue = self.ToString();
     int p = Tools.JSObjectToInt32(pos[0], true);
     if ((p < 0) || (p >= strValue.Length))
         return "";
     return strValue[p].ToString();//Tools.charStrings[strValue[p]];
 }
Пример #15
0
 public void DeleteDontDeletePropertyTest()
 {
     var obj = new JSObject (context, null);
     obj.SetProperty ("foo", new JSValue (context, "i am permanent"), JSPropertyAttribute.DontDelete);
     Assert.IsTrue (obj.HasProperty ("foo"));
     Assert.IsFalse (obj.DeleteProperty ("foo"));
     Assert.IsTrue (obj.HasProperty ("foo"));
 }
Пример #16
0
        private void onDocumentReady(object sender, UrlEventArgs urlEventArgs)
        {
            webControl.DocumentReady -= onDocumentReady;

            jsObject = webControl.CreateGlobalJavascriptObject("jsObject");
            ButtonHandler jsHandler = new ButtonHandler();
            jsHandler.bind(jsObject);
        }
Пример #17
0
		public void TestAddObjectKey ()
		{
			JSObject o = new JSObject (null);
			o.AddObjectKey (0, 1);

			Assert.AreEqual (1, o.Count, "A1");
			Assert.IsTrue (o.ContainsObjectKey (0), "A2");
		}
Пример #18
0
 private static string BestMessage(JSObject obj)
 {
     var err = obj as JSError;
     if (err != null)
         return err.Message;
     else
         return obj.ToString();
 }
Пример #19
0
 public JSValue ToAwesomiumJavaObject()
 {
     JSObject Entry = new JSObject();
     Entry["Version"] = Version;
     //Entry["Base"] = new JSValue(Base.Select(dr => { return new JSValue(dr); }).ToArray());
     //Entry["Assets"] = new JSValue(Assets.Select(dr => { return new JSValue(dr); }).ToArray());
     return new JSValue(Entry);
 }
Пример #20
0
 /// <summary>
 /// Construct a new Kinect Trigger Space Cuboid based on some arguments.
 /// </summary>
 /// <param name="pSurface"></param>
 /// <param name="dArguments"></param>
 public LowestPointCube(Display pView, JSObject dArguments)
     : base(pView, dArguments)
 {
     // Store the point limit.
     iPointLimit = Math.Max(0, dArguments.GetValueOrDefault("point_limit", iPointLimit));
     bSendEmptyFrames = dArguments.GetValueOrDefault("sendemptyframes", bSendEmptyFrames);
     bSendEmptySuccessiveFrames = dArguments.GetValueOrDefault("sendemptysucessiveframes", bSendEmptyFrames);
 }
Пример #21
0
		public void TestAdd ()
		{
			JSObject o = new JSObject (null);
			SymbolId si = new SymbolId (0);

			o.Add (si, 1);
			Assert.AreEqual (1, o.Count, "A1");
			Assert.IsTrue (o.ContainsKey (si), "A2");
		}
Пример #22
0
        public override void Assign(JSObject value)
        {
            if ((attributes & JSObjectAttributesInternal.ReadOnly) == 0)
            {
#if DEBUG
                System.Diagnostics.Debugger.Break();
#endif
                throw new InvalidOperationException("Try to assign to " + this.GetType().Name);
            }
        }
Пример #23
0
 public static JSObject After(this JSObject self, JSObject other)
 {
     // Get the next element (to insert before)
     JSObject theNext = self.Next();
     // If there is no next, then use Append
     if (theNext == null) self.Parent().Invoke("appendChild", other);
     // Otherwise, use insertBefore
     else self.Parent().Invoke("insertBefore", other, theNext);
     return self;
 }
Пример #24
0
 private void makeCallStack()
 {
     StringBuilder res = new StringBuilder();
     var context = Context.CurrentContext;
     while (context != null)
     {
         res.Append("in ").AppendLine(context.caller == null ? "" : (context.caller.name ?? "<anonymous method>"));
         context = context.oldContext;
     }
     callstack = res.ToString();
 }
Пример #25
0
        public JSObject GetExports(JSObject thisBind)
        {
            var exports = JSObject.CreateObject();

            exports.DefineMember("settings")
                .Assign(new CefFunctions().__proto__ = TypeProxy.GetPrototype(typeof(CefFunctions)));

            exports.DefineMember("WebBrowser");
            exports["WebBrowser"] = TypeProxy.GetConstructor(typeof(WebBrowser));

            return exports;
        }
Пример #26
0
 protected internal override JSObject GetMember(JSObject name, bool forWrite, bool own)
 {
     oValue = instance as JSObject ?? this;
     try
     {
         return base.GetMember(name, forWrite, own);
     }
     finally
     {
         oValue = this;
     }
 }
Пример #27
0
 protected internal override void SetMember(JSObject name, JSObject value, bool strict)
 {
     oValue = instance as JSObject ?? this;
     try
     {
         base.SetMember(name, value, strict);
     }
     finally
     {
         oValue = this;
     }
 }
Пример #28
0
 public void DeletePropertyTest()
 {
     var obj = new JSObject (context, null);
     obj.SetProperty ("foo", new JSValue (context, "bar"));
     Assert.IsTrue (obj.HasProperty ("foo"));
     Assert.IsTrue (obj.DeleteProperty ("foo"));
     Assert.IsFalse (obj.HasProperty ("foo"));
     obj.SetProperty ("foo", new JSValue (context, 99));
     Assert.IsTrue (obj.HasProperty ("foo"));
     Assert.IsTrue (obj.DeleteProperty ("foo"));
     Assert.IsFalse (obj.HasProperty ("foo"));
 }
Пример #29
0
 private static JSObject loadTemplateRaw(Context context, JSObject args)
 {
     string templateName = args.GetField("0").ToString();
     var sect = (WebConfigurationManager.GetSection("templates") as Html.TemplateElementCollection)[templateName];
     templateName = sect.Path ?? templateName;
     templateName = validatePath(templateName);
     string templateText = "";
     var file = new FileStream(templateName, FileMode.Open, FileAccess.Read);
     templateText = new StreamReader(file).ReadToEnd();
     file.Close();
     return templateText;
 }
Пример #30
0
 public ObjectContainer(object instance, JSObject proto)
 {
     __prototype = proto;
     this.instance = instance;
     if (instance is Date)
         valueType = JSObjectType.Date;
     else
         valueType = JSObjectType.Object;
     oValue = this;
     attributes = JSObjectAttributesInternal.SystemObject;
     attributes |= proto.attributes & JSObjectAttributesInternal.Immutable;
 }
Пример #31
0
        public static CfrV8Value GetCfrObject(this JSObject _, object item)
        {
            var nameDict = new Dictionary <string, string>();

            var accessor = new CfrV8Accessor();

            var o = CfrV8Value.CreateObject(accessor);

            var t = item.GetType();

            foreach (var p in t.GetProperties())
            {
                var name = p.Name.Substring(0, 1).ToLower() + p.Name.Substring(1);

                nameDict[name] = p.Name;


                o.SetValue(name, CfxV8AccessControl.Default, CfxV8PropertyAttribute.DontDelete);
            }

            accessor.Get += (s, e) =>
            {
                var name = nameDict[e.Name];

                var p = t.GetProperty(name);

                var value     = p.GetValue(item, null);
                var valueType = value?.GetType();



                if (value == null)
                {
                    e.Retval = CfrV8Value.CreateNull();
                }
                else if (valueType == typeof(string) || valueType == typeof(Guid))
                {
                    e.Retval = CfrV8Value.CreateString((string)value);
                }
                else if (valueType == typeof(int) || valueType == typeof(short) || valueType == typeof(long))
                {
                    e.Retval = CfrV8Value.CreateInt((int)value);
                }
                else if (valueType == typeof(decimal))
                {
                    e.Retval = CfrV8Value.CreateDouble(Convert.ToDouble(value));
                }
                else if (valueType == typeof(float) || valueType == typeof(double))
                {
                    e.Retval = CfrV8Value.CreateDouble(Convert.ToDouble(value));
                }
                else if (valueType == typeof(bool))
                {
                    e.Retval = CfrV8Value.CreateBool(Convert.ToBoolean(value));
                }
                else if (valueType == typeof(DateTime))
                {
                    e.Retval = CfrV8Value.CreateDate(CfrTime.FromUniversalTime((DateTime)value));
                }
                else
                {
                    e.Retval = CfrV8Value.CreateNull();
                }



                e.SetReturnValue(true);
            };


            return(o);
        }
 public RTCSessionDescriptionInit(JSObject hostObj)
 {
     this.HostObject = hostObj;
 }
Пример #33
0
 internal HTMLMediaElement(JSObject handle) : base(handle)
 {
 }
Пример #34
0
 internal HTMLHtmlElement(JSObject handle) : base(handle)
 {
 }
Пример #35
0
        public ConstructorProxy(Context context, StaticProxy staticProxy, JSObject prototype)
            : base(context)
        {
            if (staticProxy == null)
            {
                throw new ArgumentNullException(nameof(staticProxy));
            }
            if (prototype == null)
            {
                throw new ArgumentNullException(nameof(prototype));
            }

            _fields      = staticProxy._fields;
            _staticProxy = staticProxy;
            _prototype   = prototype;

#if (PORTABLE || NETCORE)
            if (_staticProxy._hostedType.GetTypeInfo().ContainsGenericParameters)
            {
                ExceptionHelper.Throw(new TypeError(_staticProxy._hostedType.Name + " can't be created because it's generic type."));
            }
#else
            if (_staticProxy._hostedType.ContainsGenericParameters)
            {
                ExceptionHelper.ThrowTypeError(_staticProxy._hostedType.Name + " can't be created because it's generic type.");
            }
#endif
            var withNewOnly    = staticProxy._hostedType.GetTypeInfo().IsDefined(typeof(RequireNewKeywordAttribute), true);
            var withoutNewOnly = staticProxy._hostedType.GetTypeInfo().IsDefined(typeof(DisallowNewKeywordAttribute), true);

            if (withNewOnly && withoutNewOnly)
            {
                ExceptionHelper.Throw(new InvalidOperationException("Unacceptably use of " + typeof(RequireNewKeywordAttribute).Name + " and " + typeof(DisallowNewKeywordAttribute).Name + " for same type."));
            }

            if (withNewOnly)
            {
                RequireNewKeywordLevel = RequireNewKeywordLevel.WithNewOnly;
            }
            if (withoutNewOnly)
            {
                RequireNewKeywordLevel = RequireNewKeywordLevel.WithoutNewOnly;
            }

            if (_length == null)
            {
                _length = new Number(0)
                {
                    _attributes = JSValueAttributesInternal.ReadOnly | JSValueAttributesInternal.DoNotDelete | JSValueAttributesInternal.DoNotEnumerate
                }
            }
            ;

#if (PORTABLE || NETCORE)
            var ctors  = staticProxy._hostedType.GetTypeInfo().DeclaredConstructors.Where(x => x.IsPublic).ToArray();
            var ctorsL = new List <MethodProxy>(ctors.Length + (staticProxy._hostedType.GetTypeInfo().IsValueType ? 1 : 0));
#else
            var ctors  = staticProxy._hostedType.GetConstructors(BindingFlags.Public | BindingFlags.Instance);
            var ctorsL = new List <MethodProxy>(ctors.Length + (staticProxy._hostedType.IsValueType ? 1 : 0));
#endif
            for (int i = 0; i < ctors.Length; i++)
            {
                if (ctors[i].IsStatic)
                {
                    continue;
                }

                if (!ctors[i].IsDefined(typeof(HiddenAttribute), false) || ctors[i].IsDefined(typeof(ForceUseAttribute), true))
                {
                    ctorsL.Add(new MethodProxy(context, ctors[i]));
                    length._iValue = System.Math.Max(ctorsL[ctorsL.Count - 1]._length._iValue, _length._iValue);
                }
            }

            ctorsL.Sort((x, y) =>
                        x.Parameters.Length == 1 && x.Parameters[0].ParameterType == typeof(Arguments) ? 1 :
                        y.Parameters.Length == 1 && y.Parameters[0].ParameterType == typeof(Arguments) ? -1 :
                        x.Parameters.Length - y.Parameters.Length);

            constructors = ctorsL.ToArray();
        }
Пример #36
0
        public static JSValue parse(string code, Function reviewer)
        {
            var stack   = new Stack <StackFrame>();
            var pos     = 0;
            var revargs = reviewer != null ? new Arguments()
            {
                _iValue = 2
            } : null;

            stack.Push(new StackFrame()
            {
                container = null, value = null, state = ParseState.Value
            });

            while (code.Length > pos && isSpace(code[pos]))
            {
                pos++;
            }

            while (pos < code.Length)
            {
                var newObject = false;
                var start     = pos;
                var frame     = stack.Peek();
                if (NumberUtils.IsDigit(code[start]) || (code[start] == '-' && NumberUtils.IsDigit(code[start + 1])))
                {
                    if (frame.state != ParseState.Value)
                    {
                        ExceptionHelper.ThrowSyntaxError("Unexpected token at position " + pos);
                    }

                    double value;
                    if (!Tools.ParseJsNumber(code, ref pos, out value))
                    {
                        ExceptionHelper.ThrowSyntaxError("Invalid number definition.");
                    }

                    var intValue = (int)value;

                    frame.state = ParseState.End;
                    if (intValue == value)
                    {
                        frame.value = intValue;
                    }
                    else
                    {
                        frame.value = value;
                    }
                }
                else if (code[start] == '"')
                {
                    if (!Parser.ValidateString(code, ref pos, true))
                    {
                        ExceptionHelper.ThrowSyntaxError("Unexpected token at position " + pos);
                    }

                    var value = code.Substring(start + 1, pos - start - 2);
                    for (var i = value.Length; i-- > 0;)
                    {
                        if ((value[i] >= 0 && value[i] <= 0x1f))
                        {
                            ExceptionHelper.ThrowSyntaxError("Invalid string char '\\u000" + (int)value[i] + "'.");
                        }
                    }

                    if (frame.state == ParseState.Name)
                    {
                        frame.fieldName = value;
                        frame.state     = ParseState.Value;

                        while (isSpace(code[pos]))
                        {
                            pos++;
                        }

                        if (code[pos] != ':')
                        {
                            ExceptionHelper.ThrowSyntaxError("Unexpected token at position " + pos);
                        }

                        pos++;
                    }
                    else
                    {
                        if (frame.state != ParseState.Value)
                        {
                            ExceptionHelper.ThrowSyntaxError("Unexpected token at position " + pos);
                        }

                        value = Tools.Unescape(value, false);

                        var v = frame;
                        v.state = ParseState.End;
                        v.value = value;
                    }
                }
                else if (Parser.Validate(code, "null", ref pos))
                {
                    if (frame.state != ParseState.Value)
                    {
                        ExceptionHelper.ThrowSyntaxError("Unexpected token at position " + pos);
                    }

                    var v = frame;
                    v.state = ParseState.End;
                    v.value = JSValue.@null;
                }
                else if (Parser.Validate(code, "true", ref pos))
                {
                    if (frame.state != ParseState.Value)
                    {
                        ExceptionHelper.ThrowSyntaxError("Unexpected token at position " + pos);
                    }

                    var v = frame;
                    v.state = ParseState.End;
                    v.value = true;
                }
                else if (Parser.Validate(code, "false", ref pos))
                {
                    if (frame.state != ParseState.Value)
                    {
                        ExceptionHelper.ThrowSyntaxError("Unexpected token at position " + pos);
                    }

                    frame.state = ParseState.End;
                    frame.value = false;
                }
                else if (code[pos] == '{')
                {
                    if (frame.state != ParseState.Value)
                    {
                        ExceptionHelper.ThrowSyntaxError("Unexpected token at position " + pos);
                    }

                    frame.value = JSObject.CreateObject();
                    frame.state = ParseState.Object;
                    newObject   = true;
                    pos++;
                }
                else if (code[pos] == '[')
                {
                    if (frame.state != ParseState.Value)
                    {
                        ExceptionHelper.ThrowSyntaxError("Unexpected token at position " + pos);
                    }

                    frame.value = new Array();
                    frame.state = ParseState.Array;
                    newObject   = true;
                    pos++;
                }
                else if (frame.state == ParseState.Value)
                {
                    ExceptionHelper.ThrowSyntaxError("Unexpected token at position " + pos);
                }

                while (code.Length > pos && isSpace(code[pos]))
                {
                    pos++;
                }

                if (frame.state == ParseState.End)
                {
                    stack.Pop();
                    if (reviewer != null)
                    {
                        revargs[0] = frame.fieldName;
                        revargs[1] = frame.value;
                        var value = reviewer.Call(revargs);
                        if (value.Defined)
                        {
                            if (frame.container != null)
                            {
                                frame.container.GetProperty(frame.fieldName, true, PropertyScope.Own).Assign(value);
                            }
                            else
                            {
                                frame.value = value;
                                stack.Push(frame);
                            }
                        }
                    }
                    else if (frame.container != null)
                    {
                        frame.container.GetProperty(frame.fieldName, true, PropertyScope.Own).Assign(frame.value);
                    }
                    else
                    {
                        stack.Push(frame);
                    }

                    frame = stack.Peek();
                }

                if (code.Length <= pos)
                {
                    if (frame.state != ParseState.End)
                    {
                        ExceptionHelper.ThrowSyntaxError(Strings.UnexpectedEndOfSource);
                    }
                    else
                    {
                        break;
                    }
                }

                switch (code[pos])
                {
                case ',':
                {
                    if (newObject)
                    {
                        ExceptionHelper.ThrowSyntaxError("Unexpected token at position " + pos);
                    }

                    if (frame.state == ParseState.Array)
                    {
                        frame = new StackFrame()
                        {
                            state = ParseState.Value, fieldName = (frame.valuesCount++).ToString(CultureInfo.InvariantCulture), container = frame.value
                        }
                    }
                    ;
                    else if (frame.state == ParseState.Object)
                    {
                        frame = new StackFrame()
                        {
                            state = ParseState.Name, container = frame.value
                        }
                    }
                    ;
                    else
                    {
                        ExceptionHelper.ThrowSyntaxError("Unexpected token at position " + pos);
                    }

                    stack.Push(frame);
                    pos++;
                    break;
                }

                case ']':
                {
                    if (frame.state != ParseState.Array)
                    {
                        ExceptionHelper.ThrowSyntaxError("Unexpected token at position " + pos);
                    }

                    frame.state = ParseState.End;
                    pos++;
                    break;
                }

                case '}':
                {
                    if (frame.state != ParseState.Object)
                    {
                        ExceptionHelper.ThrowSyntaxError("Unexpected token at position " + pos);
                    }

                    frame.state = ParseState.End;
                    pos++;
                    break;
                }

                default:
                {
                    if (newObject)
                    {
                        pos--;
                        newObject = false;
                        goto case ',';
                    }

                    if (frame.state != ParseState.Value)
                    {
                        ExceptionHelper.ThrowSyntaxError("Unexpected token at position " + pos);
                    }

                    break;
                }
                }

                while (code.Length > pos && isSpace(code[pos]))
                {
                    pos++;
                }

                if (code.Length <= pos && frame.state != ParseState.End)
                {
                    ExceptionHelper.ThrowSyntaxError(Strings.UnexpectedEndOfSource);
                }
            }

            if ((stack.Count != 1) ||
                (code.Length > pos) ||
                (stack.Peek().state != ParseState.End))
            {
                ExceptionHelper.ThrowSyntaxError(Strings.UnexpectedEndOfSource);
            }

            return(stack.Pop().value);
        }
Пример #37
0
        public override async void Run(JSObject canvas, float canvasWidth, float canvasHeight, Color clearColor)
        {
            base.Run(canvas, canvasWidth, canvasHeight, clearColor);

            InitializeShaders(
                vertexShaderCode:
                @"attribute vec4 aVertexPosition;
attribute vec2 aTextureCoord;

uniform mat4 uModelViewMatrix;
uniform mat4 uProjectionMatrix;

varying highp vec2 vTextureCoord;

void main(void) {
    gl_Position = uProjectionMatrix * uModelViewMatrix * aVertexPosition;
    vTextureCoord = aTextureCoord;
}",
                fragmentShaderCode:
                @"varying highp vec2 vTextureCoord;

uniform sampler2D uSampler;

void main(void) {
    gl_FragColor = texture2D(uSampler, vTextureCoord);
}");

            vertexPositionAttribute = gl.GetAttribLocation(shaderProgram, "aVertexPosition");
            textureCoordAttribute   = gl.GetAttribLocation(shaderProgram, "aTextureCoord");
            projectionMatrixUniform = gl.GetUniformLocation(shaderProgram, "uProjectionMatrix");
            modelViewMatrixUniform  = gl.GetUniformLocation(shaderProgram, "uModelViewMatrix");
            samplerUniform          = gl.GetUniformLocation(shaderProgram, "uSampler");

            var positions = new float[]
            {
                // Front face
                -1.0f, -1.0f, 1.0f,
                1.0f, -1.0f, 1.0f,
                1.0f, 1.0f, 1.0f,
                -1.0f, 1.0f, 1.0f,
                // Back face
                -1.0f, -1.0f, -1.0f,
                -1.0f, 1.0f, -1.0f,
                1.0f, 1.0f, -1.0f,
                1.0f, -1.0f, -1.0f,
                // Top face
                -1.0f, 1.0f, -1.0f,
                -1.0f, 1.0f, 1.0f,
                1.0f, 1.0f, 1.0f,
                1.0f, 1.0f, -1.0f,
                // Bottom face
                -1.0f, -1.0f, -1.0f,
                1.0f, -1.0f, -1.0f,
                1.0f, -1.0f, 1.0f,
                -1.0f, -1.0f, 1.0f,
                // Right face
                1.0f, -1.0f, -1.0f,
                1.0f, 1.0f, -1.0f,
                1.0f, 1.0f, 1.0f,
                1.0f, -1.0f, 1.0f,
                // Left face
                -1.0f, -1.0f, -1.0f,
                -1.0f, -1.0f, 1.0f,
                -1.0f, 1.0f, 1.0f,
                -1.0f, 1.0f, -1.0f
            };

            positionBuffer = CreateArrayBuffer(positions);

            var textureCoordinates = new float[]
            {
                // Front
                0.0f, 0.0f,
                1.0f, 0.0f,
                1.0f, 1.0f,
                0.0f, 1.0f,
                // Back
                0.0f, 0.0f,
                1.0f, 0.0f,
                1.0f, 1.0f,
                0.0f, 1.0f,
                // Top
                0.0f, 0.0f,
                1.0f, 0.0f,
                1.0f, 1.0f,
                0.0f, 1.0f,
                // Bottom
                0.0f, 0.0f,
                1.0f, 0.0f,
                1.0f, 1.0f,
                0.0f, 1.0f,
                // Right
                0.0f, 0.0f,
                1.0f, 0.0f,
                1.0f, 1.0f,
                0.0f, 1.0f,
                // Left
                0.0f, 0.0f,
                1.0f, 0.0f,
                1.0f, 1.0f,
                0.0f, 1.0f
            };

            textureCoordBuffer = CreateArrayBuffer(textureCoordinates);

            indices = new ushort[]
            {
                0, 1, 2, 0, 2, 3,           // front
                4, 5, 6, 4, 6, 7,           // back
                8, 9, 10, 8, 10, 11,        // top
                12, 13, 14, 12, 14, 15,     // bottom
                16, 17, 18, 16, 18, 19,     // right
                20, 21, 22, 20, 22, 23      // left
            };
            indexBuffer = CreateElementArrayBuffer(indices);

            texture = gl.CreateTexture();

            var file = "Assets/spongebob.bmp";
            var img  = await GetImageFromAssets(file);

            var colors = GetRGBAColors(img);

            var imageData = new ImageData(colors, img.Width, img.Height);

            gl.BindTexture(gl.Texture2D, texture);

            gl.TexParameteri(gl.Texture2D, gl.TextureWrapS, gl.ClampToEdge);
            gl.TexParameteri(gl.Texture2D, gl.TextureWrapT, gl.ClampToEdge);
            gl.TexParameteri(gl.Texture2D, gl.TextureMinFilter, gl.Nearest);
            gl.TexParameteri(gl.Texture2D, gl.TextureMagFilter, gl.Nearest);

            gl.TexImage2D(gl.Texture2D, 0, gl.RGB, gl.RGB, gl.UnsignedByte, imageData);

            gl.VertexAttribPointer(vertexPositionAttribute, 3, gl.Float, false, 0, 0);
            gl.EnableVertexAttribArray(vertexPositionAttribute);

            gl.EnableVertexAttribArray(textureCoordAttribute);
            gl.VertexAttribPointer(textureCoordAttribute, 2, gl.Float, false, 0, 0);

            projectionMatrix = Matrix.CreatePerspectiveFieldOfView(
                MathHelper.ToRadians(45),
                canvasWidth / canvasHeight,
                0.1f,
                100f);
        }
Пример #38
0
 internal HTMLDataListElement(JSObject handle) : base(handle)
 {
 }
Пример #39
0
 internal HTMLFrameSetElement(JSObject handle) : base(handle)
 {
 }
 internal HTMLCanvasElement(JSObject handle) : base(handle)
 {
 }
Пример #41
0
        static void GeoFindMe(JSObject output)
        {
            GeoLocation geoLocation;

            try
            {
                geoLocation = new GeoLocation(navigator.GetProperty("geolocation"));
            }
            catch
            {
                output.SetObjectProperty("innerHTML", "<p>Geolocation is not supported by your browser</p>");
                return;
            }

            output.SetObjectProperty("innerHTML", "<p>Locating…</p>");

            geoLocation.OnSuccess += async(object sender, Position position) =>
            {
                using (position)
                {
                    using (var coords = position.Coordinates)
                    {
                        var latitude  = coords.Latitude;
                        var longitude = coords.Longitude;

                        output.SetObjectProperty("innerHTML", $"<p>Latitude is {latitude} ° <br>Longitude is {longitude} °</p>");

                        try {
                            var ApiFile = $"https://maps.googleapis.com/maps/api/staticmap?center={latitude},{longitude}&zoom=13&size=300x300&sensor=false";

                            var rspMsg = await httpClient.GetAsync(ApiFile);

                            if (rspMsg.IsSuccessStatusCode)
                            {
                                var mimeType = getMimeType(rspMsg.Content?.ReadAsByteArrayAsync().Result);
                                Console.WriteLine($"Request: {++requests}  ByteAsync: {rspMsg.Content?.ReadAsByteArrayAsync().Result.Length}  MimeType: {mimeType}");
                                global.Invoke("showMyPosition", mimeType, Convert.ToBase64String(rspMsg.Content?.ReadAsByteArrayAsync().Result));
                            }
                            else
                            {
                                output.SetObjectProperty("innerHTML", $"<p>Latitude is {latitude} ° <br>Longitude is {longitude} </p><br>StatusCode: {rspMsg.StatusCode} <br>Response Message: {rspMsg.Content?.ReadAsStringAsync().Result}</p>");
                            }
                        }
                        catch (Exception exc2)
                        {
                            Console.WriteLine($"GeoLocation HttpClient Exception: {exc2.Message}");
                            Console.WriteLine($"GeoLocation HttpClient InnerException: {exc2.InnerException?.Message}");
                        }
                    }
                }
            };

            geoLocation.OnError += (object sender, PositionError e) =>
            {
                output.SetObjectProperty("innerHTML", $"Unable to retrieve your location: Code: {e.Code} - {e.message}");
            };

            geoLocation.GetCurrentPosition();

            geoLocation = null;
        }
Пример #42
0
 internal CDATASection(JSObject handle) : base(handle)
 {
 }
Пример #43
0
 internal Event(JSObject handle) : base(handle)
 {
 }
Пример #44
0
 public TestPrototype(VirtualMachine vm, JSObject inherited)
     : base(vm, GetLazyMembers(), inherited)
 {
 }
Пример #45
0
        private async Task ConnectAsyncJavaScript(Uri uri, CancellationToken cancellationToken)
        {
            var tcsConnect = new TaskCompletionSource <bool> ();

            // For Abort/Dispose.  Calling Abort on the request at any point will close the connection.
            cts.Token.Register(AbortRequest);

            // Wrap the cancellationToken in a using so that it can be disposed of whether
            // we successfully connected or failed trying.
            // Otherwise any timeout/cancellation would apply to the full session.
            // In the failure case we need to release the references and dispose of the objects.
            using (cancellationToken.Register(() => tcsConnect.TrySetCanceled())) {
                try {
                    JSObject subProtocols = null;
                    if (Options.RequestedSubProtocols.Count > 0)
                    {
                        subProtocols = Runtime.NewJSArray();
                        foreach (var item in Options.RequestedSubProtocols)
                        {
                            subProtocols.Invoke("push", item);
                        }
                    }
                    innerWebSocket = Runtime.NewJSObject(wsFunctionPtr, uri.ToString(), subProtocols);

                    subProtocols?.Dispose();

                    onError = new Action <JSObject> ((errorEvt) => {
                        if (cancellationToken.CanBeCanceled &&
                            (!tcsConnect.Task.IsCanceled && !tcsConnect.Task.IsCompleted && !tcsConnect.Task.IsFaulted))
                        {
                            tcsConnect.SetException(new WebSocketException(WebSocketError.NativeError));
                        }
                        errorEvt.Dispose();
                    });

                    innerWebSocket.SetObjectProperty("onerror", onError);

                    onOpen = new Action <JSObject> ((evt) => {
                        if (!cancellationToken.IsCancellationRequested)
                        {
                            // Change internal state to 'connected' to enable the other methods
                            if (Interlocked.CompareExchange(ref state, connected, connecting) != connecting)
                            {
                                // Aborted/Disposed during connect.
                                throw new ObjectDisposedException(GetType().FullName);
                            }

                            tcsConnect.SetResult(true);
                        }

                        evt.Dispose();
                    });

                    innerWebSocket.SetObjectProperty("onopen", onOpen);


                    onClose = new Action <JSObject> ((closeEvt) => {
                        innerWebSocketCloseStatus            = (WebSocketCloseStatus)closeEvt.GetObjectProperty("code");
                        innerWebSocketCloseStatusDescription = closeEvt.GetObjectProperty("reason")?.ToString();
                        tcsClose?.SetResult(true);
                        var mess = new ReceivePayload(WebSocketHelpers.EmptyPayload, WebSocketMessageType.Close);
                        receiveMessageQueue.BufferPayload(mess);
                        closeEvt.Dispose();
                    });

                    innerWebSocket.SetObjectProperty("onclose", onClose);

                    onMessage = new Action <JSObject> ((messageEvent) => {
                        ThrowIfNotConnected();

                        // get the events "data"
                        var eventData = messageEvent.GetObjectProperty("data");

                        // If the messageEvent's data property is marshalled as a JSObject then we are dealing with
                        // binary data
                        if (eventData is JSObject)
                        {
                            // TODO: Handle ArrayBuffer binary type but have only seen 'blob' so far without
                            // changing the default websocket binary type manually.
                            if (innerWebSocket.GetObjectProperty("binaryType").ToString() == "blob")
                            {
                                Action <JSObject> loadend = null;
                                // Obtain a reference to "FileReader" object
                                using (var readerF = (JSObject)Runtime.GetGlobalObject("FileReader"))
                                    // Create a new "FileReader" object
                                    using (var reader = Runtime.NewJSObject(readerF)) {
                                        loadend = new Action <JSObject> ((loadEvent) => {
                                            using (var target = (JSObject)loadEvent.GetObjectProperty("target")) {
                                                if ((int)target.GetObjectProperty("readyState") == 2)
                                                {
                                                    byte [] result = (byte [])target.GetObjectProperty("result");
                                                    var mess       = new ReceivePayload(result, WebSocketMessageType.Binary);
                                                    receiveMessageQueue.BufferPayload(mess);
                                                    Runtime.FreeObject(loadend);
                                                }
                                            }
                                            loadEvent.Dispose();
                                        });

                                        reader.Invoke("addEventListener", "loadend", loadend);

                                        using (var blobData = (JSObject)messageEvent.GetObjectProperty("data"))
                                            reader.Invoke("readAsArrayBuffer", blobData);
                                    }
                            }
                            else
                            {
                                throw new NotImplementedException($"WebSocket bynary type '{innerWebSocket.GetObjectProperty ("binaryType").ToString ()}' not supported.");
                            }
                        }
                        else if (eventData is string)
                        {
                            var mess = new ReceivePayload(Encoding.UTF8.GetBytes(((string)eventData).ToString()), WebSocketMessageType.Text);
                            receiveMessageQueue.BufferPayload(mess);
                        }
                        messageEvent.Dispose();
                    });

                    innerWebSocket.SetObjectProperty("onmessage", onMessage);

                    await tcsConnect.Task;
                } catch (Exception wse) {
                    ConnectExceptionCleanup();
                    WebSocketException wex = new WebSocketException("WebSocket connection failure.", wse);
                    throw wex;
                }
            }
        }
Пример #46
0
 internal KeyboardEvent(JSObject handle) : base(handle)
 {
 }
Пример #47
0
 public WebGLBackendTests(JSObject canvas)
 {
     this.canvas = canvas;
 }