public UltraApplication(IHTMLElement e)
		{
			var Title = new IHTMLDiv
				{
					innerHTML = @"
<img border='0' src='http://www.w3schools.com/images/compatible_ie.gif' width='31' height='30' alt='Internet Explorer' title='Internet Explorer' />
<img border='0' src='http://www.w3schools.com/images/compatible_firefox.gif' width='31' height='30' alt='Firefox' title='Firefox' />
<img border='0' src='http://www.w3schools.com/images/compatible_opera.gif' width='28' height='30' alt='Opera' title='Opera' />
<img border='0' src='http://www.w3schools.com/images/compatible_chrome.gif' width='31' height='30' alt='Google Chrome' title='Google Chrome' />
<img border='0' src='http://www.w3schools.com/images/compatible_safari.gif' width='28' height='30' alt='Safari' title='Safari' />
"
				};


			var TitleLogo = new IHTMLImage("assets/ScriptCoreLib/jsc.png");
			var TitleText = new IHTMLSpan("UltraApplication");
			TitleText.style.fontFamily = ScriptCoreLib.JavaScript.DOM.IStyle.FontFamilyEnum.Verdana;
			TitleText.style.paddingLeft = "2em";
			TitleText.style.fontSize = "xx-large";
			TitleLogo.style.verticalAlign = "middle";


			Title.appendChild(TitleLogo);
			Title.appendChild(TitleText);

			Title.style.height = "128px";

			Title.AttachToDocument();
			Title.FadeIn(2500, 1000,
				delegate
				{
					1500.AtDelay(ContinueBuildingApplication);
				}
			);
		}
        public __RadioButton()
        {
            // http://msdn2.microsoft.com/en-us/library/system.windows.forms.radiobutton.aspx
            /* Use the Checked property to get or set the state of a RadioButton. 
             * The option button's appearance can be altered to appear as a toggle-style 
             * button or as a standard option button by setting the Appearance property.
             */

            // http://javascript.about.com/library/blradio2.htm
            /* The solution here is to give all of the radio buttons within the group 
             * the same name but different values. Here is the code used to code just 
             * radio button themselves on the previous page that shows you how this is done.
             */

            // http://www.thescripts.com/forum/thread468483.html

            // IE support
            // http://www.gtalbot.org/DHTMLSection/DynamicallyCreateRadioButtons.html

            HTMLTarget = new IHTMLDiv();
            HTMLTarget.style.whiteSpace = ScriptCoreLib.JavaScript.DOM.IStyle.WhiteSpaceEnum.nowrap;

            button = new IHTMLInput(ScriptCoreLib.Shared.HTMLInputTypeEnum.radio);
            label = new IHTMLLabel("", button);

            HTMLTarget.appendChild(button, label);
        }
示例#3
0
		static IHTMLDiv InternalConstructor(params INode[] e)
		{
			IHTMLDiv u = new IHTMLDiv();

			u.appendChild(e);

			return u;
		}
示例#4
0
        static IHTMLDiv InternalConstructor(params INode[] e)
        {
            IHTMLDiv u = new IHTMLDiv();

            u.appendChild(e);

            return(u);
        }
		private void Start1()
		{

			//concept.AttachToDocument();

			var Title = new IHTMLDiv
			{

			};

			new Browsers
			{
			}.Container.AttachTo(Title);

			new HTML.Images.FromBase64.twitter_small().AttachToDocument();
			new HTML.Images.FromAssets.twitter_small().AttachToDocument();




			var TitleLogo = new IHTMLImage("assets/ScriptCoreLib/jsc.png");
			var TitleText = new IHTMLSpan("UltraApplication");
			TitleText.style.fontFamily = ScriptCoreLib.JavaScript.DOM.IStyle.FontFamilyEnum.Verdana;
			TitleText.style.paddingLeft = "2em";
			TitleText.style.fontSize = "xx-large";
			TitleLogo.style.verticalAlign = "middle";


			Title.appendChild(TitleLogo);
			Title.appendChild(TitleText);

			Title.style.height = "128px";

			Title.AttachToDocument();
			Title.FadeIn(2500, 1000,
				delegate
				{
					1500.AtDelay(
						delegate
						{
							ContinueBuildingApplication();
						}
					);
				}
			);
		}
        // advertise in ScriptCoreLib.Extensions
        public static global::CSSMinimizeFormToSidebar.HTML.Pages.IApp InitializeSidebarBehaviour(
            Form f,
            bool HandleClosed = true,
            bool HandleDragToLeft = true)
        {

            // can we do a dynamic upgrade?

            var newlayout = new global::CSSMinimizeFormToSidebar.HTML.Pages.App();

            newlayout.AddMoreText.Hide();

            var newlayoutnodes = newlayout.body.childNodes.ToArray();

            //newlayout.Sidebar.name = "Sidebar";
            // where is this guy??
            //newlayout.SidebarOverlay.name = "SidebarOverlay";

            var oldcontent = Native.document.body.childNodes.ToArray();

            Native.Document.body.Clear();
            Native.Document.body.appendChild(newlayoutnodes);

            Native.Document.body.setAttribute("style",
                newlayout.Container.getAttribute("style")
            );


            var mycontainer = new IHTMLDiv().AttachTo((IHTMLElement)newlayout.ScrollContainer.parentNode);
            newlayout.ScrollContainer.Orphanize();


            mycontainer.style.position = IStyle.PositionEnum.absolute;
            mycontainer.style.left = "10em";
            mycontainer.style.top = "0px";
            mycontainer.style.right = "0px";
            mycontainer.style.bottom = "0px";

            mycontainer.appendChild(oldcontent);


            //Native.Document.body.Orphanize();
            //newlayout.Container.AttachTo(Native.Document.documentElement);
            //Native.Document.body = (IHTMLBody)(object)newlayout.Container;


            // reparent
            f.GetHTMLTarget().Orphanize().AttachToDocument();

            global::CSSMinimizeFormToSidebar.ApplicationExtension.InitializeSidebarBehaviour(
                newlayout, f, HandleClosed: HandleClosed, HandleDragToLeft: HandleDragToLeft
            );

            return newlayout;
        }
        /// <summary>
        /// This is a javascript application.
        /// </summary>
        /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param>
        public Application(IDefault page)
        {
            IHTMLDiv Control = new IHTMLDiv();


            Control.AttachToDocument();

            Control.appendChild(new IHTMLElement(IHTMLElement.HTMLElementEnum.h1, "This page will ask you to confirm in order to unload the page"));

            var check = new IHTMLInput(HTMLInputTypeEnum.checkbox).AttachToDocument();
            var label = new IHTMLLabel("Bypass check", check).AttachToDocument();



            Native.window.onbeforeunload +=
                delegate (IWindow.Confirmation ev)
                {

                    Timer.DoAsync(
                        delegate
                        {
                            Native.document.body.style.backgroundColor = JSColor.Red;


                            new Timer((t) => Native.document.body.style.backgroundColor = JSColor.White, 500, 0);
                        }
                    );

                    if (check.@checked)
                        return;

                    ev.Text = "This is a secure website, do you want to leave?";
                };

            var anchor = new IHTMLAnchor("http://example.com", "example.com");

            anchor.target = "_self";

            Control.appendChild(anchor);


        }
        // new three broke it?
        // http://www.clicktorelease.com/code/perlin/explosion.html
        // http://www.webgl.com/2013/01/webgl-tutorial-vertex-displacement-with-a-noise-function-aka-fiery-explosion/


        /// <summary>
        /// This is a javascript application.
        /// </summary>
        /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param>
        public Application(IDefault page = null)
        {
            // http://inear.se/fireshader/




            // http://stackoverflow.com/questions/16765120/ashima-perlin-noise-shader-not-working-with-recent-versions-of-three-js

            //var container, renderer,  camera, mesh;
            var start = IDate.Now;
            var fov = 30;


            #region container
            Native.document.body.style.overflow = IStyle.OverflowEnum.hidden;
            var container = new IHTMLDiv();

            container.AttachToDocument();
            container.style.backgroundColor = "#000000";
            container.style.SetLocation(0, 0, Native.window.Width, Native.window.Height);
            #endregion


            var scene = new THREE.Scene();
            var bkgScene = new THREE.Scene();

            var camera = new THREE.PerspectiveCamera(fov, Native.window.aspect, 1, 10000);
            camera.position.z = 100;
            //camera.target = new THREE.Vector3(0, 0, 0);

            scene.add(camera);

            var bkgCamera = new THREE.OrthographicCamera(
                Native.window.Width / -2,
                Native.window.Width / 2,
                Native.window.Height / 2,
                Native.window.Height / -2,
                -10000,
                10000
            );

            bkgScene.add(bkgCamera);

            var bkgShader = new THREE.ShaderMaterial(
                new 
                {
                    uniforms = new 
                    {
                        tDiffuse = new 
                        {
                            type = "t",
                            value = THREE.ImageUtils.loadTexture(
                                new HTML.Images.FromAssets.bkg().src
                            )
                        },

                        resolution = new  { type = "v2", value = new THREE.Vector2(Native.window.Width, Native.window.Height) }
                    },

                    vertexShader = new Shaders.ExplosionVertexShader().ToString(),
                    //        fragmentShader: document.getElementById( 'fs_Gradient' ).textContent,
                    //fragmentShader = new Shaders.GradientFragmentShader().ToString(),
                    fragmentShader = new Shaders.ExplosionFragmentShader().ToString(),

                    depthWrite = false,
                    depthTest = false,
                    transparent = true
                }
            );

            var quad = new THREE.Mesh(new THREE.PlaneGeometry(Native.window.Width, Native.window.Height), bkgShader);
            quad.position.z = -100;
            quad.rotation.x = (float)Math.PI / 2;
            bkgScene.add(quad);


            var material = new THREE.ShaderMaterial(

                new 
                {
                    uniforms = new // material_uniforms
                    {
                        tExplosion = new  //uniforms_item
                        {
                            type = "t",
                            value =  THREE.ImageUtils.loadTexture(
                                new HTML.Images.FromAssets.explosion().src
                            )
                        },
                        time = new { type = "f", value = 0.0 },
                        weight = new { type = "f", value = 8.0 },
                    },

                    vertexShader = new Shaders.ExplosionVertexShader().ToString(),
                    fragmentShader = new Shaders.ExplosionFragmentShader().ToString(),
                    depthWrite = false,
                    depthTest = false,
                    transparent = true
                }
            );


            var mesh = new THREE.Mesh(new THREE.SphereGeometry(20, 200, 200), material);
            scene.add(mesh);

            var renderer = new THREE.WebGLRenderer();
            renderer.setSize(Native.window.Width, Native.window.Height);
            renderer.autoClear = false;

            container.appendChild(renderer.domElement);

          
            var lon = 0.0;
            var phi = 0.0;
            var theta = 0.0;
            var lat = 15.0;
            var isUserInteracting = false;


            var scale = 0.0;

            #region render

            Native.window.onframe += delegate
            {

                ((material_uniforms)material.uniforms).time.value = .00025 * (IDate.Now - start);

                scale += .005;
                scale %= 2;

                lat = Math.Max(-85, Math.Min(85, lat));
                phi = (90 - lat) * Math.PI / 180;
                theta = lon * Math.PI / 180;

                camera.position.x = (float)(100 * Math.Sin(phi) * Math.Cos(theta));
                camera.position.y = (float)(100 * Math.Cos(phi));
                camera.position.z = (float)(100 * Math.Sin(phi) * Math.Sin(theta));

                //mesh.rotation.x += .012;
                //mesh.rotation.y += .01;
                camera.lookAt(scene.position);

                //    //renderer.render( bkgScene, bkgCamera );
                renderer.render(scene, camera);

                //    stats.update();

            };


            #endregion



            #region IsDisposed

            Dispose = delegate
            {
                if (IsDisposed)
                    return;

                IsDisposed = true;


                container.Orphanize();
            };
            #endregion






            #region AtResize
            Action AtResize = delegate
            {
                container.style.SetLocation(0, 0, Native.window.Width, Native.window.Height);


                renderer.setSize(Native.window.Width, Native.window.Height);

                camera.projectionMatrix.makePerspective(fov, Native.window.aspect, 1, 1100);

                //camera.aspect = Native.Window.Width / Native.Window.Height;
                //camera.updateProjectionMatrix();
            };

            Native.window.onresize +=
                delegate
                {
                    AtResize();
                };

            AtResize();
            #endregion



            var ze = new ZeProperties();

            ze.Show();
            ze.treeView1.Nodes.Clear();

            ze.Add(() => renderer);
            //ze.Add(() => controls);
            ze.Add(() => scene);
            ze.Left = 0;



        }
        /// <summary>
        /// Creates a new control
        /// </summary>
        /// <param name="DataElement">The hidden data element</param>
        public LightsOut2(IHTMLElement DataElement)
        {

            // based on http://www.cjcraft.com/Blog/PermaLink,guid,5c35b1f1-dc66-4d85-ac04-22fc97503d4a.aspx

            // what happens in beta2 when the anonymous types are immutable? :)


            var usersettings = new  { x = 5, y = 5, tile = new  { w = 64, h = 64, cold = 0.8 } };

    
            var a = new Array2D<IHTMLDiv>(usersettings.x, usersettings.y);
            var m = a.ToBooleanArray();



            var r = new System.Random();

            m.ForEach(
                (x, y) =>
                {
                    m[x, y] = r.NextDouble() > 0.5;
                }
            );


            var canvas = new IHTMLDiv();

            canvas.className = "canvas";

            var canvas_size = new __Type1 { x = ((a.XLength + 1) * usersettings.tile.w), y = ((a.YLength + 1) * usersettings.tile.h) };

            canvas.style.position = IStyle.PositionEnum.relative;
            canvas.style.border = "2px solid black";
            canvas.style.width = canvas_size.x + "px";
            canvas.style.height = canvas_size.y + "px";

            var canvas_bg = new IHTMLDiv();
            //var canvas_bg_tween = new TweenDataDouble();

            //canvas_bg_tween.Value = 1;
            //canvas_bg_tween.ValueChanged += delegate { canvas_bg.style.Opacity = canvas_bg_tween.Value; };

            new HTML.Images.FromAssets.background().ToBackground(canvas_bg.style);
            //canvas_bg.style.backgroundImage = Assets.Default.Background.StyleSheetURL;
            canvas_bg.style.SetLocation(0, 0, canvas_size.x * 2, canvas_size.y);

            canvas.appendChild(canvas_bg);


            IStyleSheet.Default.AddRule(".info").style
                .Aggregate(s =>
                               {
                                   s.backgroundColor = Color.Black;
                                   s.color = Color.White;
                                   s.padding = "2em";
                                   s.fontFamily = IStyle.FontFamilyEnum.Tahoma;
                                   s.Float = IStyle.FloatEnum.right;
                               })
                ;

            IStyleSheet.Default.AddRule(".canvas").style
                .Aggregate(s => s.overflow = IStyle.OverflowEnum.hidden)
                .Aggregate(s => s.backgroundColor = Color.Black)
                ;

            IStyleSheet.Default.AddRule(".on").style
                .Aggregate(s =>
                    
                        new HTML.Images.FromAssets.vistaLogoOn().ToBackground(s)
                    
                   )
                //.Aggregate(s => s.Opacity = 0.8)
                ;

            IStyleSheet.Default.AddRule(".off").style
                .Aggregate(s => 
                    
                        new HTML.Images.FromAssets.vistaLogoOff().ToBackground(s)
                    
                  )
                //.Aggregate(s => s.Opacity = 0.5)
                ;




            Action<int, int> UpdateColor =
                (x, y) =>
                {
                    var n = a[x, y];

                    if (m[x, y])
                    {
                        n.className = "on";
                    }
                    else
                    {
                        n.className = "off";
                    }

                };

            Action<int, int> ToggleDirect =
                (x, y) =>
                {
                    var n = a[x, y];

                    if (n == null)
                        return;

                    m[x, y] = !m[x, y];
                    UpdateColor(x, y);
                };

            Action<int, int> Toggle =
                (x, y) =>
                {
                    //Console.WriteLine("click at: " + new { x, y } + " = " + m[x, y]);

                    var f = ToggleDirect.WithOffset(x, y);

                    f(-1, 0);
                    f(0, -1);
                    f(0, 0);
                    f(0, 1);
                    f(1, 0);
                };


            var info_stats_clicks = new IHTMLDiv();
            var info_stats_clicks_count = 0;
            var info_stats_off = new IHTMLDiv();
            var info_stats_on = new IHTMLDiv();

            Action info_stats_update =
                () =>
                {
                    info_stats_clicks.innerHTML = info_stats_clicks_count + " clicks made so far";
                    info_stats_on.innerHTML = m.Count(i => i) + " blocks are on";
                    info_stats_off.innerHTML = m.Count(i => !i) + " blocks are off";

                };

            var info_stats = new IHTMLDiv(info_stats_clicks, info_stats_off, info_stats_on);
            info_stats.className = "info";


            a.ForEach(
                (x, y) =>
                {
                    var n = new IHTMLDiv();

                    n.style.left = (x * usersettings.tile.w + usersettings.tile.w / 2) + "px";
                    n.style.top = (y * usersettings.tile.h + usersettings.tile.h / 2) + "px";
                    n.style.width = usersettings.tile.w + "px";
                    n.style.height = usersettings.tile.h + "px";
                    n.style.position = IStyle.PositionEnum.absolute;
                    n.style.overflow = IStyle.OverflowEnum.hidden;

                    //n.style.border = "1px solid black";
                    n.style.cursor = IStyle.CursorEnum.pointer;

                    canvas.appendChild(n);

                    var tween = new TweenDataDouble();


                    tween.ValueChanged += () => n.style.Opacity = tween.Value;
                    tween.Value = usersettings.tile.cold;

                    n.style.Opacity = tween.Value;

                    n.onmouseover += delegate
                    {
                        tween.Value = 1;
                        //canvas_bg_tween.Value = 0.5;
                    };

                    n.onmouseout += delegate
                    {
                        tween.Value = usersettings.tile.cold;
                        //canvas_bg_tween.Value = 1;
                    };

                    n.onclick += delegate
                    {
                        info_stats_clicks_count++;

                        Toggle(x, y);


                        info_stats_update();
                    };


                    a[x, y] = n;

                    UpdateColor(x, y);

                }
            );

            var ani = new Timer(t =>
                               canvas_bg.style.left = -(int)System.Math.Floor((double)((IDate.Now.getTime() / 75) % canvas_size.x)) + "px");




            var info = new IHTMLDiv();

            var info_header_text = "Lights out 2";

            Native.Document.title = info_header_text;

            info.appendChild(new IHTMLElement(IHTMLElement.HTMLElementEnum.h1, info_header_text));

            info.appendChild(new IHTMLAnchor("http://www.cjcraft.com/Blog/PermaLink,guid,5c35b1f1-dc66-4d85-ac04-22fc97503d4a.aspx", "based on SilverlightsOut"));
            info.appendChild(new IHTMLBreak());
            info.appendChild(new IHTMLAnchor("http://www.cjcraft.com/Blog/CommentView,guid,5c35b1f1-dc66-4d85-ac04-22fc97503d4a.aspx", "cjcraft blog post"));

            info.appendChild(new IHTMLElement(IHTMLElement.HTMLElementEnum.p,
                @"Lights out is a one player puzzle that is played on a 5 by 5 grid of squares in which every square has two states: on and off. The game starts off with all squares off, where the goal is to turn on every square. By selecting a square, all the surrounding squares' (up, down, left, right) state is turned toggled. For example, on a 3 by 3 grid of squares with all squares off, if the center one is selected, it will turn 'on' the 4 up, down, left, right squares from it."));

            info.appendChild(new IHTMLDiv("Mozilla based browsers seem to suffer in performance while animating contents under semitransparent elements."));

            info.appendChild(new IHTMLButton("Animate background").Aggregate(btn => btn.onclick += delegate { ani.StartInterval(50); }));
            info.appendChild(new IHTMLButton("Freeze background").Aggregate(btn => btn.onclick += delegate { ani.Stop(); }));
            info.appendChild(info_stats);
            info.appendChild(canvas);

            info_stats_update();

            DataElement.insertNextSibling(info);

        }
        //public const string Alias = "Class1";
        //public const string DefaultData = "Class1Data";

        /// <summary>
        /// Creates a new control
        /// </summary>
        /// <param name="DataElement">The hidden data element</param>
        public GoogleGearsSimple()
        {
            // this ctor creates a new div which has a text and a button element
            // on mouseover over the color text is changed
            // on pressing the button the next message in text element is displayed
            IHTMLDiv Control = new IHTMLDiv();

            Control.AttachToDocument();

            Func<string, string, IHTMLElement> link = (href, text) => new IHTMLDiv(new IHTMLAnchor(href, text));


            Control.appendChild(link("http://gears.google.com/", "Google Gears"));
            Control.appendChild(link("http://code.google.com/apis/gears/samples/hello_world_database.html", "Google Example # 1"));

            Control.appendChild(new IHTMLElement(IHTMLElement.HTMLElementEnum.h3, "This page uses Google Gears to record your entries on the local disk. If you navigate away and revisit this page, all your data will still be here. Try it!"));

            // http://code.google.com/apis/gears/samples/hello_world_database.html

            GoogleGearsFactory.Database db = null;

            try
            {
                db = new GoogleGearsFactory.Database();
            }
            catch (Exception exc)
            {
                var err = new IHTMLCode(exc.Message);

                err.style.color = Color.Red;


                Control.appendChild(err);
            }

            IStyleSheet.Default.AddRule(".odd").style.backgroundColor = Color.FromGray(0xa0);
            IStyleSheet.Default.AddRule(".even").style.backgroundColor = Color.FromGray(0xef);

            if (db != null)
            {
                db.open("demo1");
                db.execute(@"
    create table if not exists Demo
    (Phrase varchar(255), Timestamp int)
            ");

                var textfield = new IHTMLInput(HTMLInputTypeEnum.text, "text1", "");

                var btnadd = new IHTMLButton("Add new entry");
                var btnrefresh = new IHTMLButton("Refresh");
                var btnclear = new IHTMLButton("Clear");

                Control.appendChild(textfield, btnadd, btnclear, btnrefresh,
                    
                    new IHTMLCode(GoogleGearsFactory.Default.getBuildInfo())
                        
                        );



                var list = new IHTMLElement(IHTMLElement.HTMLElementEnum.ol);

                Control.appendChild(list);

                var read = default(Action);

                read = delegate
                {
                    //from i in Demo
                    //select new { Phrase, Timestamp }
                    //order by Timestamp desc

                    list.removeChildren();

                    Func<string, IHTMLElement> AddItem = 
                        text => new IHTMLElement(IHTMLElement.HTMLElementEnum.li, text).Aggregate(v => list.appendChild(v));



                    // this could be rewritten as an expression once they are supported by jsc

                    int counter = 0;

                    var query = from Data in db.AsEnumerable<DemoDataEntity>(
                                                "select * from Demo order by Timestamp desc",
                                                typeof(DemoDataEntity)
                                            )
                                // let ListItem = AddItem(Data.Timestamp + " - " + Data.Phrase)
                                select new __Type2 { ListItem = AddItem(Data.Timestamp + " - " + Data.Phrase), Data  = Data};

                    foreach (var v in query)
                    {
                        counter++;
                        var vx = v;


                        if (counter % 2 == 0)
                            v.ListItem.className = "odd";
                        else
                            v.ListItem.className = "even";

                        #region -
                        var btndel = new IHTMLButton("-");

                        btndel.style.color = Color.Red;

                        btndel.onclick +=
                            delegate
                            {
                                db.execute("delete from Demo where Timestamp = ?", vx.Data.Timestamp);

                                read();
                            };
                        #endregion

                        #region +
                        var btnclone = new IHTMLButton("+");

                        btnclone.style.color = Color.Blue;

                        btnclone.onclick +=
                            delegate
                            {
                                db.Insert("Demo", vx.Data);


                                read();
                            };
                        #endregion

                        v.ListItem.insertBefore(btnclone, v.ListItem.firstChild);
                        v.ListItem.insertBefore(btndel, v.ListItem.firstChild);

                    }


                    #region raw
                    //var rs = db.execute("select * from Demo order by Timestamp desc");

                    //while (rs.isValidRow())
                    //{
                    //    var xt = typeof(DemoDataEntity);
                    //    var xx = (DemoDataEntity)Activator.CreateInstance(xt);

                    //    for (int i = 0; i < rs.fieldCount(); i++)
                    //    {
                    //        xt.GetField(rs.fieldName(i)).SetValue(xx, rs.field(i));
                    //    }

                    //    AddItem(xx.Timestamp + " - " + xx.Phrase);

                    //    rs.next();
                    //}

                    //rs.close();
                    #endregion

                };

                btnclear.onclick +=
                    delegate
                    {
                        db.execute("delete from Demo");

                        read();
                    };

                btnadd.onclick +=
                    delegate
                    {
                        db.Insert("Demo",
                            new DemoDataEntity
                            {
                                Phrase = textfield.value,
                                Timestamp = IDate.Now.getTime()
                            }
                        );

                        //db.execute("insert into Demo (Phrase, Timestamp) values (?, ?)", textfield.value, IDate.Now.getTime());

                        textfield.value = "";

                        read();
                    };

                btnrefresh.onclick +=
                    delegate
                    {
                        read();
                    };

                read();

            }


            // not array
            // is object
            // no prototype
        }
        /// <summary>
        /// Creates a new control
        /// </summary>
        /// <param name="DataElement">The hidden data element</param>
        public SimpleFilmstrip()
        {
            IHTMLDiv Control = new IHTMLDiv();

            Control.style.position = IStyle.PositionEnum.absolute;

            new filmstrip().ToBackground(Control, false);

            //Control.style.background = "url(assets/SimpleFilmstrip/filmstrip.png) no-repeat";
            Control.style.height = "600px";
            Control.style.width = "326px";

            var index = 0;

            var t_icount = default(int);
            var t_interval = default(int);
            var t_iwidth = default(int);
            var t_iheight = default(int);
            var t_feed = default(string);

            var Restart = default(Action);

            var feed = new IHTMLInput(HTMLInputTypeEnum.text,

                new veh_cy().src
                );

            var iwidth = new IHTMLInput(HTMLInputTypeEnum.text, "48");
            var iheight = new IHTMLInput(HTMLInputTypeEnum.text, "48");
            var icount = new IHTMLInput(HTMLInputTypeEnum.text, "32");
            var interval = new IHTMLInput(HTMLInputTypeEnum.text, "50");
            var fps = new IHTMLInput(HTMLInputTypeEnum.text, "24");


            feed.onchange += delegate { Restart(); };
            iwidth.onchange += delegate { Restart(); };
            iheight.onchange += delegate { Restart(); };

            interval.onchange += delegate
            {
                int v = int.Parse(interval.value);

                if (v == 0)
                    return;

                fps.value = "" + (1000 / v);


                Restart();
            };

            icount.onchange += delegate { Restart(); };

            fps.onchange += delegate
            {
                int v = int.Parse(fps.value);

                if (v == 0)
                    return;

                interval.value = "" + (1000 / v);

                Restart();
            };


            var fieldset = new IHTMLElement(IHTMLElement.HTMLElementEnum.fieldset);

            fieldset.style.width = "30em";

            fieldset.appendChild(new IHTMLElement(IHTMLElement.HTMLElementEnum.legend, "Properties"));

            Func<string, IHTMLElement, IHTMLDiv> AsLabel =
                (string text, IHTMLElement control) =>
                {
                    var label = new IHTMLLabel(text, control);

                    control.style.position = IStyle.PositionEnum.absolute;
                    control.style.left = "8em";

                    return new IHTMLDiv(label, control);
                };

            fieldset.appendChild(AsLabel("feed:", feed));
            fieldset.appendChild(AsLabel("width:", iwidth));
            fieldset.appendChild(AsLabel("height:", iheight));
            fieldset.appendChild(AsLabel("count:", icount));
            fieldset.appendChild(AsLabel("interval:", interval));
            fieldset.appendChild(AsLabel("fps:", fps));


            fieldset.style.position = IStyle.PositionEnum.absolute;
            fieldset.style.top = "320px";

            var image = new IHTMLDiv();




            image.style.position = IStyle.PositionEnum.absolute;
            image.style.top = "52px";
            image.style.left = "32px";


            var t = new Timer();

            t.Tick += delegate
            {

                image.style.backgroundPosition = "-" + (index * t_iwidth) + "px 0px";


                index = (index + 1) % t_icount;
            };

            Restart =
                delegate
                {
                    t_icount = int.Parse(icount.value);
                    t_interval = int.Parse(interval.value);
                    t_iwidth = int.Parse(iwidth.value);
                    t_iheight = int.Parse(iheight.value);
                    t_feed = feed.value;

                    image.style.background = "url(" + t_feed + ") no-repeat";

                    image.style.width = t_iwidth + "px";
                    image.style.height = t_iheight + "px";

                    t.StartInterval(t_interval);
                };

            Restart();

            Control.appendChild(image, fieldset);

            Control.AttachToDocument();

        }
        private static IHTMLElement Dump(object xs, IHTMLElement to, object diff)
        {

            var c = new IHTMLDiv();

            c.style.backgroundColor = Color.White;
            c.style.border = "1px solid gray";
            c.style.padding = "1em";
            c.style.fontFamily = IStyle.FontFamilyEnum.Consolas;

            var ttx = new IHTMLDiv(xs.ToString());

            c.appendChild(ttx);

            var dx = Expando.Of(diff);

            foreach (var v in Expando.Of(xs).GetMembers())
            {
                var tt = default(IHTMLDiv);
                var ok = true;

                if (dx != null)
                {
                    if (dx.Contains(v.Name))
                    {
                        if (dx[v.Name] == v.Self)
                            ok = false;
                    }
                }

                if (ok)
                {
                    if (v.Self.IsFunction)
                    {
                        tt = new IHTMLDiv(v.Self.TypeString + " " + v.Name);
                        tt.style.color = Color.Red;

                    }
                    else if (v.Self.IsObject)
                    {
                        tt = new IHTMLDiv(v.Self.TypeString + " " + v.Name + " = " + v.Self.ToString());
                        tt.style.color = Color.Blue;
                    }
                    else
                        tt = new IHTMLDiv(v.Self.TypeString + " " + v.Name + " = " + v.Self.ToString());

                    c.appendChild(tt);
                }
            }

            to.appendChild(c);

            return to;

        }
示例#13
0
        public __CheckBox()
        {
            HTMLTarget = new IHTMLDiv();
            HTMLTarget.style.whiteSpace = ScriptCoreLib.JavaScript.DOM.IStyle.WhiteSpaceEnum.nowrap;

            InternalInputElement = new IHTMLInput(ScriptCoreLib.Shared.HTMLInputTypeEnum.checkbox, "");
            InternalInputElement.style.margin = "0";
            InternalInputElement.style.verticalAlign = "middle";
            InternalInputElement.style.width = "auto";

            label = new IHTMLLabel("", InternalInputElement);
            label.style.verticalAlign = "middle";
            label.style.marginLeft = "0.5em";
            label.style.display = DOM.IStyle.DisplayEnum.inline;

            label.onmousedown +=
                e =>
                {
                    e.preventDefault();
                };

            this.CheckStateChanged +=
                delegate
                {
                    if (this.ThreeState)
                    {
                        // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-input-element.html#dom-input-indeterminate
                        this.InternalInputElement.indeterminate = (this.InternalCheckState == global::System.Windows.Forms.CheckState.Indeterminate);
                    }
                };

            this.InternalInputElement.onchange +=
                e =>
                {
                    // http://shamsmi.blogspot.com/2008/12/tri-state-checkbox-using-javascript.html



                    if (this.ThreeState)
                    {
                        if (this.InternalCheckState == global::System.Windows.Forms.CheckState.Checked)
                        {
                            // http://jsfiddle.net/chriscoyier/mGg85/2/
                            // http://jsfiddle.net/ysangkok/UhQc8/

                            //e.preventDefault();
                            //e.stopPropagation();

                            // next step is to go from checked to unchecked!
                            this.InternalInputElement.@checked = true;
                            this.CheckState = global::System.Windows.Forms.CheckState.Indeterminate;
                            return;
                        }

                    }


                    if (this.InternalCheckState == global::System.Windows.Forms.CheckState.Unchecked)
                    {
                        this.CheckState = global::System.Windows.Forms.CheckState.Checked;
                        return;
                    }

                    this.CheckState = global::System.Windows.Forms.CheckState.Unchecked;

                };
            HTMLTarget.appendChild(InternalInputElement, label);

            this.InternalSetDefaultFont();
        }
        private static void AppendError(IHTMLDiv workspace0, string err_msg)
        {
            var err = new IHTMLElement(IHTMLElement.HTMLElementEnum.pre, err_msg) { className = "error" };


            workspace0.appendChild(err);
        }
示例#15
0
        public __Form()
        {

            Console.WriteLine("event: enter new " + this.GetType().Name + "()");
            //IStyleSheet.all.disabled = true;

            this.InternalTrackInitializeComponents = delegate
            {
                ConstructorStopwatch.Stop();

                // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2014/201402/20140205
                // will this help us? no?
                //IStyleSheet.all.disabled = false;

                //Console.WriteLine("event: new " + new { this.GetType().Name } + " InternalResumeLayout " + new { ConstructorStopwatch.ElapsedMilliseconds });
                Console.WriteLine("event: new " + this.GetType().Name + "() " + new { ConstructorStopwatch.ElapsedMilliseconds });


                //474ms new { Name = FooActivity } InternalResumeLayout { ElapsedMilliseconds = 464 } 


                new XAttribute(
                    "ConstructorStopwatch",
                    new { ConstructorStopwatch.ElapsedMilliseconds }.ToString()
                ).AttachTo(this.HTMLTargetRef);
            };

            //25:584ms event: exit DataGridView .ctor { ElapsedMilliseconds = 525 } view-source:35983
            //48:1043ms event: exit DataGridView .ctor { ElapsedMilliseconds = 445 } view-source:35983
            //95:1509ms event: exit DataGridView .ctor { ElapsedMilliseconds = 420 } view-source:35983
            //96:1713ms at FlowLayoutPanel InternalResumeLayout { ElapsedMilliseconds = 628, Name = flowLayoutPanel1, Controls = 2 } view-source:35955
            //97:1724ms at FlowLayoutPanel InternalResumeLayout { ElapsedMilliseconds = 1674, Name = flowLayoutPanel1, Controls = 9 } view-source:35955
            //97:1724ms at FlowLayoutPanel InternalResumeLayout { ElapsedMilliseconds = 1137, Name = flowLayoutPanel2, Controls = 3 } view-source:35996
            //97:1724ms at FlowLayoutPanel InternalResumeLayout { ElapsedMilliseconds = 1128, Name = flowLayoutPanel3, Controls = 1 } view-source:35996
            //97:1724ms event: new FooActivity() { ElapsedMilliseconds = 1706 } 

            this.StartPosition = FormStartPosition.CenterScreen;

            var TargetElement = new IHTMLDiv
            {

                // do this ahead of time
                // type inheritance?
                className = typeof(Form).Name + " " + this.GetType().Name
            };

            // thanks host, but we do our own resizers
            // http://stackoverflow.com/questions/13224184/css-resize-handles-with-resize-both-property
            // http://www.w3schools.com/cssref/css3_pr_resize.asp
            //TargetElement.style.resize = "none !important";

            TargetElement.style.position = ScriptCoreLib.JavaScript.DOM.IStyle.PositionEnum.absolute;
            TargetElement.style.left = "0px";
            TargetElement.style.top = "0px";

            HTMLTarget = TargetElement;

            // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2013/201312/20131222-form
            outer_css = TargetElement.css;

            #region TargetOuterBorder
            TargetOuterBorder = new IHTMLDiv().AttachTo(TargetElement);
            //HTMLTarget.style.backgroundColor = Shared.Drawing.Color.System.ThreeDFace;
            TargetOuterBorder.style.position = ScriptCoreLib.JavaScript.DOM.IStyle.PositionEnum.absolute;
            TargetOuterBorder.style.left = "0px";
            TargetOuterBorder.style.top = "0px";
            TargetOuterBorder.style.bottom = "0px";
            TargetOuterBorder.style.right = "0px";

            TargetOuterBorder.style.borderWidth = "1px";
            TargetOuterBorder.style.borderStyle = "solid";
            TargetOuterBorder.style.borderBottomColor = "#424142";
            TargetOuterBorder.style.borderRightColor = "#424142";
            TargetOuterBorder.style.borderLeftColor = "#D6D3CE";
            TargetOuterBorder.style.borderTopColor = "#D6D3CE";
            //HTMLTarget.style.SetLocation(64, 64, 100, 100);
            TargetOuterBorder.style.padding = "0";
            #endregion

            #region TargetInnerBorder
            var TargetInnerBorder = new IHTMLDiv().AttachTo(TargetOuterBorder);
            ////HTMLTarget.style.backgroundColor = Shared.Drawing.Color.System.ThreeDFace;
            TargetInnerBorder.style.position = ScriptCoreLib.JavaScript.DOM.IStyle.PositionEnum.absolute;
            TargetInnerBorder.style.left = "0px";
            TargetInnerBorder.style.top = "0px";
            TargetInnerBorder.style.bottom = "0px";
            TargetInnerBorder.style.right = "0px";

            TargetInnerBorder.style.borderWidth = "1px";
            TargetInnerBorder.style.borderStyle = "solid";
            TargetInnerBorder.style.borderLeftColor = "#FFFFFF";
            TargetInnerBorder.style.borderTopColor = "#FFFFFF";
            TargetInnerBorder.style.borderRightColor = "#848284";
            TargetInnerBorder.style.borderBottomColor = "#848284";

            // ?
            //TargetInnerBorder.style.backgroundColor = "#D6D3CE";

            //HTMLTarget.style.SetLocation(64, 64, 100, 100);
            #endregion


            #region TargetResizerPadding
            TargetResizerPadding = new IHTMLDiv().AttachTo(TargetInnerBorder);
            TargetResizerPadding.style.position = ScriptCoreLib.JavaScript.DOM.IStyle.PositionEnum.absolute;
            TargetResizerPadding.style.left = "2px";
            TargetResizerPadding.style.top = "2px";
            TargetResizerPadding.style.bottom = "2px";
            TargetResizerPadding.style.right = "2px";
            #endregion

            #region TargetNoBorder
            TargetNoBorder = new IHTMLDiv().AttachTo(TargetResizerPadding);
            TargetNoBorder.style.position = ScriptCoreLib.JavaScript.DOM.IStyle.PositionEnum.absolute;
            TargetNoBorder.style.left = "0px";
            TargetNoBorder.style.top = "0px";
            TargetNoBorder.style.bottom = "0";
            TargetNoBorder.style.right = "0";
            #endregion


            TargetOuterBorder.style.boxShadow = "black 3px 3px 6px -3px";


            #region caption
            //IHTMLImage icon = "assets/ScriptCoreLib.Windows.Forms/App.ico";

            icon.style.SetLocation(5, 5, 16, 16);

            //caption.style.backgroundColor = JSColor.System.ActiveCaption;
            Caption.style.backgroundColor = JSColor.FromRGB(0x08, 0x24, 0x6B);

            Caption.style.position = ScriptCoreLib.JavaScript.DOM.IStyle.PositionEnum.absolute;
            Caption.style.left = 0 + "px";
            Caption.style.top = 0 + "px";
            Caption.style.right = 0 + "px";
            Caption.style.height = "26px";
            Caption.style.margin = "0px";

            //Caption.style.paddingTop = "6px";
            //Caption.style.paddingLeft = "26px";
            Caption.style.font = new Font("Segoe UI", 9.0F, FontStyle.Regular, GraphicsUnit.Point, 0).ToCssString();

            CaptionShadow = (IHTMLDiv)Caption.cloneNode(false);
            CaptionShadow.style.backgroundColor = JSColor.Black;
            CaptionShadow.style.Opacity = 0;



            CaptionContent = new IHTMLHeader1();
            CaptionContent.style.color = Shared.Drawing.Color.White;

            CaptionContent.style.position = ScriptCoreLib.JavaScript.DOM.IStyle.PositionEnum.absolute;
            CaptionContent.style.left = 0 + "px";
            CaptionContent.style.top = 0 + "px";
            CaptionContent.style.right = 0 + "px";
            CaptionContent.style.height = "26px";
            CaptionContent.style.margin = "0px";

            CaptionContent.style.fontSize = "1em";
            CaptionContent.style.fontWeight = "100";

            CaptionContent.style.backgroundColor = JSColor.None;

            CaptionContent.style.font = DefaultFont.ToCssString();

            (CaptionContent.style as dynamic).textOverflow = "ellipsis";



            //CaptionContent.style.WithDynamic(
            //    style => style.textOverflow = "ellipsis"
            //);

            CaptionContent.style.lineHeight = "26px";
            CaptionContent.style.left = "26px";
            CaptionContent.style.right = "30px";

            CaptionContent.style.overflow = IStyle.OverflowEnum.hidden;



            CaptionForeground = (IHTMLDiv)Caption.cloneNode(false);
            CaptionForeground.style.backgroundColor = ScriptCoreLib.Shared.Drawing.Color.FromRGB(255, 0, 255);
            CaptionForeground.style.Opacity = 0;
            CaptionForeground.className = "caption";
            CaptionForeground.style.right = "26px";

            // http://dojotoolkit.org/pipermail/dojo-checkins/2005-December/002867.html


            //            new IFunction(@"
            //                try { this.style.MozUserSelect = 'none'; } catch (e) { }
            //                try { this.style.KhtmlUserSelect = 'none'; } catch (e) { }
            //                try { this.unselectable = 'on'; } catch (e) { }
            //                "
            //            ).apply(caption_foreground);

            //            caption_foreground.onselectstart +=
            //                (e) =>
            //                {
            //                    e.PreventDefault();
            //                    e.StopPropagation();
            //                };
            #endregion

            // http://developer.apple.com/mac/library/documentation/AppleApplications/Reference/Dashboard_Ref/Dashboard_Ref.pdf
            // for some reason we cannot exclude caption
            // from apple dashboard

            //caption_foreground.style.appleDashboardRegion = "none";

            //container.style.backgroundColor = "#A0A0A0";
            //container.style.appleDashboardRegion = "dashboard-region(control rectangle)";

            #region ContentContainer
            //ContentContainerPadding.title = "ContentContainerPadding";
            ContentContainerPadding.style.position = ScriptCoreLib.JavaScript.DOM.IStyle.PositionEnum.absolute;
            ContentContainerPadding.style.left = 0 + "px";
            ContentContainerPadding.style.top = (26 + innerborder + 0) + "px";
            ContentContainerPadding.style.right = 0 + "px";
            ContentContainerPadding.style.bottom = 0 + "px";

            ContentContainer = new IHTMLDiv().AttachTo(ContentContainerPadding);
            //ContentContainer.title = "ContentContainer";
            ContentContainer.style.position = ScriptCoreLib.JavaScript.DOM.IStyle.PositionEnum.absolute;
            ContentContainer.style.left = 0 + "px";
            ContentContainer.style.top = 0 + "px";
            ContentContainer.style.right = 0 + "px";
            ContentContainer.style.bottom = 0 + "px";
            ContentContainer.style.overflow = IStyle.OverflowEnum.hidden;

            // is this needed?
            //ContentContainer.style.zIndex = 1000;

            var ContentContainerShadow = new IHTMLDiv().AttachTo(ContentContainerPadding);
            //ContentContainerShadow.title = "ContentContainerShadow";
            ContentContainerShadow.style.position = ScriptCoreLib.JavaScript.DOM.IStyle.PositionEnum.absolute;
            ContentContainerShadow.style.left = 0 + "px";
            ContentContainerShadow.style.top = 0 + "px";
            ContentContainerShadow.style.right = 0 + "px";
            ContentContainerShadow.style.bottom = 0 + "px";
            ContentContainerShadow.style.overflow = IStyle.OverflowEnum.hidden;
            ContentContainerShadow.style.backgroundColor = JSColor.Red;
            ContentContainerShadow.style.Opacity = 0.0;
            ContentContainerShadow.style.display = IStyle.DisplayEnum.none;
            ContentContainerShadow.style.zIndex = 1001;
            #endregion

            InternalMouseCapured +=
                delegate
                {
                    // is this enough to capture resizer in a chrome AppWindow?
                    ContentContainerShadow.style.display = IStyle.DisplayEnum.block;
                };

            InternalMouseReleased +=
                delegate
                {
                    ContentContainerShadow.style.display = IStyle.DisplayEnum.none;
                };


            #region ResizeGripElement
            ResizeGripElement = new IHTMLDiv().AttachTo(ContentContainerPadding);
            ResizeGripElement.style.position = ScriptCoreLib.JavaScript.DOM.IStyle.PositionEnum.absolute;
            ResizeGripElement.style.width = "12px";
            ResizeGripElement.style.height = "12px";
            ResizeGripElement.style.bottom = "0px";
            ResizeGripElement.style.right = "0px";
            ResizeGripElement.style.cursor = IStyle.CursorEnum.se_resize;
            new IHTMLImage { src = "assets/ScriptCoreLib.Windows.Forms/FormResizeGrip.png" }.ToBackground(ResizeGripElement);
            ResizeGripElement.style.zIndex = 1002;
            #endregion

            #region ResizeGripDrag
            ResizeGripDrag = new ScriptCoreLib.JavaScript.Controls.DragHelper(ResizeGripElement);

            ResizeGripDrag.Enabled = true;

            #region AtSizeChanged
            Action AtSizeChanged = delegate
            {
                var Size = this.Size;

                ResizeGripDrag.Position = new Shared.Drawing.Point(Size.Width, Size.Height);
            };

            this.SizeChanged +=
                delegate
                {
                    AtSizeChanged();
                };
            AtSizeChanged();
            #endregion

            ResizeGripDrag.DragStart +=
                delegate
                {
                    Capture = true;
                    InternalMouseCapured();
                };
            ResizeGripDrag.DragMove +=
                delegate
                {
                    this.Size = new Size(ResizeGripDrag.Position.X, ResizeGripDrag.Position.Y);
                };

            ResizeGripDrag.DragStop +=
              delegate
              {
                  Capture = false;
                  InternalMouseReleased();

              };
            #endregion



            #region CloseButton
            InternalCloseButton = new IHTMLDiv { name = "CloseButton" };
            InternalCloseButton.style.textAlign = IStyle.TextAlignEnum.center;
            InternalCloseButton.style.fontWeight = "bold";
            //InternalCloseButton.style.cursor = IStyle.CursorEnum.@default;
            InternalCloseButton.style.cursor = IStyle.CursorEnum.pointer;

            InternalCloseButtonContent = new IHTMLDiv { }.AttachTo(InternalCloseButton);

            InternalCloseButtonContent.style.position = ScriptCoreLib.JavaScript.DOM.IStyle.PositionEnum.absolute;
            InternalCloseButtonContent.style.left = "0px";
            InternalCloseButtonContent.style.top = "0px";
            InternalCloseButtonContent.style.bottom = "0";
            InternalCloseButtonContent.style.right = "0";



            InternalCloseButtonContent.title = "Close";
            InternalCloseButtonContent.innerHTML = "&times";



            InternalCloseButton.style.position = ScriptCoreLib.JavaScript.DOM.IStyle.PositionEnum.absolute;

            //CloseButton.style.backgroundColor = JSColor.System.ThreeDFace;
            InternalCloseButton.style.backgroundColor = "#D6D3CE";

            InternalCloseButton.style.height = "18px";
            InternalCloseButton.style.width = "18px";
            InternalCloseButton.style.right = (innerborder + 3) + "px";
            InternalCloseButton.style.top = (innerborder + 2) + "px";

            InternalCloseButton.style.borderWidth = "1px";
            InternalCloseButton.style.borderStyle = "solid";

            InternalCloseButton.style.borderRightColor = "#424142";
            InternalCloseButton.style.borderBottomColor = "#424142";
            InternalCloseButton.style.borderLeftColor = "#FFFFFF";
            InternalCloseButton.style.borderTopColor = "#FFFFFF";



            InternalCloseButtonContent.style.borderWidth = "1px";
            InternalCloseButtonContent.style.borderStyle = "solid";

            InternalCloseButtonContent.style.borderLeftColor = "#D6D3CE";
            InternalCloseButtonContent.style.borderTopColor = "#D6D3CE";
            InternalCloseButtonContent.style.borderRightColor = "#848284";
            InternalCloseButtonContent.style.borderBottomColor = "#848284";

            #region CloseButton onclick

            InternalCloseButton.css.hover[IHTMLElement.HTMLElementEnum.div].style.color = "red";

            //InternalCloseButton.onmouseover +=
            //     delegate
            //     {
            //         InternalCloseButtonContent.style.color = JSColor.Red;
            //     };

            //InternalCloseButton.onmouseout +=
            //    delegate
            //    {
            //        InternalCloseButtonContent.style.color = JSColor.None;
            //    };

            InternalCloseButton.onmousedown +=
                e =>
                {
                    e.stopPropagation();
                    e.preventDefault();
                };

            InternalCloseButton.onclick +=
                delegate
                {


                    InternalClose(reason: CloseReason.UserClosing);
                };
            #endregion

            #endregion

            TargetNoBorder.appendChild(

                ContentContainerPadding,



                 Caption, CaptionShadow, CaptionContent,
                icon, CaptionForeground

                , InternalCloseButton

            );

            CaptionForeground.oncontextmenu +=
                e =>
                {
                    // can we show our own menu?
                    e.preventDefault();
                    e.stopPropagation();
                };

            #region InternalCaptionDrag
            InternalCaptionDrag = new ScriptCoreLib.JavaScript.Controls.DragHelper(CaptionForeground);

            // http://forum.mootools.net/topic.php?id=534
            // disable text selection
            // look at http://forkjavascript.com/

            InternalCaptionDrag.Enabled = true;
            #endregion

            var BeforePosition = new Shared.Drawing.Point(0, 0);

            var FirstMove = false;
            var AnyMove = false;

            var DragStartMaximized = false;
            var DragStartMaximizedY = 0;



            this.MaximizeBox = true;
            this.InternalControlBox = true;

            #region DragStart
            InternalCaptionDrag.DragStartValidate +=
                e =>
                {
                    // if there is no max, then there is no restore. then do not allow to
                    // drag back either
                    e.Value = this.MaximizeBox;
                };

            InternalCaptionDrag.DragStart +=
                delegate
                {
                    TargetNoBorder.style.cursor = IStyle.CursorEnum.move;
                    CaptionForeground.style.cursor = IStyle.CursorEnum.move;
                    Native.Document.body.style.cursor = IStyle.CursorEnum.move;



                    BeforePosition = InternalCaptionDrag.Position;

                    FirstMove = true;
                    DragStartMaximized = this.WindowState == FormWindowState.Maximized;
                    //if (DragStartMaximized)
                    //    DragStartMaximizedY = this.InternalRestoreLocation.Y;

                    // offsetWidth: 1045

                    //Console.WriteLine(new { BeforePosition, DragStartMaximized });

                    Capture = true;
                    InternalMouseCapured();

                };
            #endregion

            #region WindowState
            Action InternalEnterFullscreen =
                delegate
                {
                    Console.WriteLine("InternalEnterFullscreen WindowState <- Maximized");
                    this.WindowState = FormWindowState.Maximized;

                };


            Action InternalExitFullscreen =
                delegate
                {
                    Console.WriteLine("InternalExitFullscreen WindowState <- Normal");

                    this.WindowState = FormWindowState.Normal;

                };
            #endregion


            #region DragMove
            InternalCaptionDrag.DragMove +=
                delegate
                {
                    if (!Capture)
                        return;


                    //Console.WriteLine(new { InternalCaptionDrag.Position, BeforePosition, DragStartMaximized });

                    // { Position = [192, 205.5], BeforePosition = [192, 205.5], DragStartMaximized = true } 

                    if (InternalCaptionDrag.Position.X == BeforePosition.X)
                        if (InternalCaptionDrag.Position.Y == BeforePosition.Y)
                        {
                            //Console.WriteLine("FirstMove without move");
                            return;
                        }

                    // { InternalHostHeight = 0, y = 301 } 
                    //var MinimizeY = InternalHostHeight - 26;
                    var y = InternalCaptionDrag.Position.Y;
                    //Console.WriteLine(new { InternalHostHeight, y });
                    //y = Math.Min(MinimizeY, Math.Max(-4, y));
                    y = Math.Max(-4, y);


                    if (FirstMove)
                    {
                        FirstMove = false;

                        if (this.WindowState == FormWindowState.Maximized)
                        {
                            //Capture = false;

                            //this.InternalRestoreLocation = new Point(InternalCaptionDrag.Position.X, y);


                            // we have a small glitch here
                            Console.WriteLine("InternalCaptionDrag.DragMove FirstMove " + new { this.InternalRestoreLocation });

                            InternalExitFullscreen();

                            //return;
                        }
                    }


                    AnyMove = true;


                    //if (Native.Document.fullscreenElement == TargetNoBorder)
                    this.Location = new Point(InternalCaptionDrag.Position.X, y);

                    //Console.WriteLine(new { Location });

                    if (y < 0)
                    {
                        CaptionShadow.Show();
                    }
                    //else
                    //{

                    //    if (y < MinimizeY)
                    //        CaptionShadow.Hide();
                    //    else
                    //        CaptionShadow.Show();
                    //}
                };
            #endregion

            #region DragStop
            InternalCaptionDrag.DragStop +=
                delegate
                {
                    if (!Capture)
                        return;


                    Capture = false;
                    InternalMouseReleased();

                    if (!AnyMove)
                        return;

                    // tested by
                    // X:\jsc.svn\examples\javascript\MatrixTransformBExample\MatrixTransformBExperiment\Application.cs

                    //var Location = this.Location;

                    //this.Text = new { drag.Position.X, drag.Position.Y }.ToString();

                    TargetNoBorder.style.cursor = IStyle.CursorEnum.@default;
                    CaptionForeground.style.cursor = IStyle.CursorEnum.@default;
                    Native.document.body.style.cursor = IStyle.CursorEnum.@default;


                    //var MinimizeY = InternalHostHeight - 26;
                    var y = InternalCaptionDrag.Position.Y;

                    //if (this.HTMLTarget.parentNode != Native.document.body)
                    //{
                    //    // this window is in a nested element, or even in another window.
                    //    // bail!

                    //    return;
                    //}

                    if (y < 0)
                    {
                        InternalCaptionDrag.Position = BeforePosition;

                        InternalEnterFullscreen();

                        this.InternalRestoreLocation = new Point(BeforePosition.X, BeforePosition.Y);
                    }
                    //else if (y >= MinimizeY)
                    //{
                    //    if (this.WindowState != FormWindowState.Minimized)
                    //    {
                    //        // do we need this?

                    //        var cs = this.ClientSize;
                    //        var ll = this.Location;

                    //        //drag.Position = BeforePosition;
                    //        //this.Location = new Point(BeforePosition.X, BeforePosition.Y);

                    //        this.WindowState = FormWindowState.Minimized;

                    //        //this.InternalRestoreClientSIze = cs;
                    //        this.InternalRestoreLocation = ll;
                    //    }
                    //}
                    else
                    {
                        //Console.WriteLine("to Normal ? " + new { this.WindowState });

                        if (this.WindowState == FormWindowState.Minimized)
                        {
                            var cs = this.ClientSize;
                            var ll = this.Location;

                            this.WindowState = FormWindowState.Normal;

                            //this.ClientSize = cs;
                            this.Location = ll;
                        }
                    }

                };
            #endregion


            #region MiddleClick
            InternalCaptionDrag.MiddleClick +=
                delegate
                {
                    Capture = false;

                    if (!this.MaximizeBox)
                    {
                        // X:\jsc.svn\examples\javascript\forms\FormsWithVisibleTitle\FormsWithVisibleTitle\Application.cs
                        // not supposed to restore
                        return;
                    }

                    if (this.WindowState == FormWindowState.Minimized)
                    {
                        this.WindowState = FormWindowState.Normal;
                        return;
                    }

                    if (this.WindowState == FormWindowState.Maximized)
                    {
                        Console.WriteLine("InternalCaptionDrag.MiddleClick  InternalExitFullscreen");

                        InternalExitFullscreen();
                    }
                    else
                    {
                        Console.WriteLine("InternalCaptionDrag.MiddleClick  InternalEnterFullscreen");
                        InternalEnterFullscreen();
                    }
                };
            #endregion


            #region ondblclick
            CaptionForeground.ondblclick +=
                delegate
                {
                    Capture = false;

                    if (!this.MaximizeBox)
                    {
                        // X:\jsc.svn\examples\javascript\forms\FormsWithVisibleTitle\FormsWithVisibleTitle\Application.cs
                        // not supposed to restore
                        return;
                    }

                    if (this.WindowState == FormWindowState.Minimized)
                    {
                        this.WindowState = FormWindowState.Normal;
                        return;
                    }


                    if (this.WindowState == FormWindowState.Maximized)
                        InternalExitFullscreen();
                    else
                        InternalEnterFullscreen();
                };
            #endregion






            // to be replaiced with #shadow-root content select?
            this.InternalStyler = new FormStyler
            {
                Context = this,

                Caption = Caption,
                CaptionContent = CaptionContent,
                CaptionShadow = CaptionShadow,

                CloseButton = InternalCloseButton,
                CloseButtonContent = InternalCloseButtonContent,

                TargetInnerBorder = TargetInnerBorder,
                TargetOuterBorder = TargetOuterBorder,

                ContentContainerPadding = ContentContainerPadding,

                TargetResizerPadding = TargetResizerPadding
            };


            //HTMLTarget.style.backgroundColor = "#B0B0B0";
            this.BackColor = Color.FromArgb(0xD6, 0xD3, 0xCE);

            this.Size = new Size(400, 400);


            FormStyler.RaiseAtFormCreated(
                this.InternalStyler
            );


            //this.ControlAdded +=
            //    (sender, args) =>
            //    {
            //        if (InternalTrackInitializeComponents)
            //        {

            //            // report what controls are being added and 

            //            Console.WriteLine("at Form ControlAdded " + new
            //            {
            //                ConstructorStopwatch.ElapsedMilliseconds,
            //                Control = args.Control.GetType().Name,
            //                this.GetType().Name
            //            });
            //        }
            //    };

            //312ms at Form InternalResumeLayout { FormConstructorStopwatch = 0.00:00:00, Name = FooActivity } 
            //Console.WriteLine("exit Form .ctor " + new { ConstructorStopwatch.ElapsedMilliseconds, this.GetType().Name });
        }
示例#16
0
        void InitializeContent(IDefault page = null)
        {
            #region make sure we atleast have our invisible DOM
            if (page == null)
                page = new HTML.Pages.Default();
            #endregion

            #region container
            Native.document.body.style.overflow = IStyle.OverflowEnum.hidden;
            var container = new IHTMLDiv();

            container.AttachToDocument();
            container.style.backgroundColor = "#000000";
            container.style.SetLocation(0, 0, Native.window.Width, Native.window.Height);
            #endregion



            #region code port

            double SCREEN_WIDTH = Native.window.Width ;
            double  SCREEN_HEIGHT = Native.window.Height;

            var animDelta = 0;
            var animDeltaDir = -1;
            var lightVal = 0;
            var lightDir = 1;
            var soundVal = 0;
            var oldSoundVal = 0;
            var soundDir = 1;

            #region animate it
            animDeltaDir *= -1;
            #endregion


            var clock = new THREE.Clock();

            var morphs = new List<THREE.MorphAnimMesh>();

            var updateNoise = true;


            var mlib = new Dictionary<string, THREE.ShaderMaterial>();

            var soundtrack = new Five_Armies { loop = true, volume = 0.9 };


            #region HasFocus
            var HasFocus = false;

            Native.window.onblur +=
               delegate
               {
                   HasFocus = false;

                   soundtrack.volume = 0.1;
               };

            Native.window.onfocus +=
                delegate
                {
                    HasFocus = true;
                    soundtrack.volume = 0.9;
                };
            //  Native.Document.onmousemove +=
            //delegate
            //{
            //    if (HasFocus)
            //        return;
            //    soundtrack.play();
            //};

            //  Native.Document.onmouseout +=
            //    delegate
            //    {
            //        if (HasFocus)
            //            return;

            //        soundtrack.pause();
            //    };
            #endregion


            var THREE_RepeatWrapping = 0;
            var THREE_FaceColors = 1;
            var THREE_LinearFilter = 6;
            var THREE_RGBFormat = 17;
            var THREE_LinearMipMapLinearFilter = 8;


            #region SCENE (RENDER TARGET)

            var sceneRenderTarget = new THREE.Scene();

            var cameraOrtho = new THREE.OrthographicCamera(
                (int)SCREEN_WIDTH / -2,
                (int)SCREEN_WIDTH / 2,
                (int)SCREEN_HEIGHT / 2,
                (int)SCREEN_HEIGHT / -2,
                -10000,
                10000
            );

            cameraOrtho.position.z = 100;

            sceneRenderTarget.add(cameraOrtho);
            #endregion

            #region SCENE (FINAL)

            var scene = new THREE.Scene();

            scene.fog = new THREE.Fog(0x050505, 2000, 4000);
            scene.fog.color.setHSV(0.102, 0.9, 0.825);

            var camera = new THREE.PerspectiveCamera(40, (int)Native.window.aspect, 2, 4000);
            camera.position.set(-1200, 800, 1200);

            scene.add(camera);

            var controls = new THREE.TrackballControls(camera);
            controls.target.set(0, 0, 0);

            controls.rotateSpeed = 1.0;
            controls.zoomSpeed = 1.2;
            controls.panSpeed = 0.8;

            controls.noZoom = false;
            controls.noPan = false;

            controls.staticMoving = false;
            controls.dynamicDampingFactor = 0.15;

            controls.keys = new[] { 65, 83, 68 };
            #endregion

            #region LIGHTS

            scene.add(new THREE.AmbientLight(0x111111));

            var spotLight = new THREE.SpotLight(0xffffff, 1.15);
            spotLight.position.set(500, 2000, 0);
            spotLight.castShadow = true;
            scene.add(spotLight);

            var pointLight = new THREE.PointLight(0xff4400, 1.5);
            pointLight.position.set(0, 0, 0);
            scene.add(pointLight);

            #endregion



            #region HEIGHT + NORMAL MAPS

            var normalShader = __THREE.ShaderExtras.normalmap;

            var rx = 256;
            var ry = 256;

            var pars = new THREE.WebGLRenderTargetArguments
            {
                minFilter = THREE_LinearMipMapLinearFilter,
                magFilter = THREE_LinearFilter,
                format = THREE_RGBFormat
            };

            var heightMap = new THREE.WebGLRenderTarget(rx, ry, pars);
            var normalMap = new THREE.WebGLRenderTarget(rx, ry, pars);

            var uniformsNoise = new MyUniformsNoise
            {
                time = new THREE.ShaderExtrasModuleItem_uniforms_item { type = "f", value = 1.0 },
                scale = new THREE.ShaderExtrasModuleItem_uniforms_item { type = "v2", value = new THREE.Vector2(1.5, 1.5) },
                offset = new THREE.ShaderExtrasModuleItem_uniforms_item { type = "v2", value = new THREE.Vector2(0, 0) }
            };

            var uniformsNormal = __THREE.UniformsUtils.clone(normalShader.uniforms);

            uniformsNormal.height.value = 0.05;
            ((THREE.Vector2)uniformsNormal.resolution.value).set(rx, ry);
            uniformsNormal.heightMap.texture = heightMap;

            var vertexShader = new Shaders.NoiseVertexShader().ToString();
            #endregion


            #region before TEXTURES
            var textureCounter = 0;


            #region RENDERER

            var renderer = new THREE.WebGLRenderer();
            renderer.setSize(Native.window.Width, Native.window.Height);
            renderer.setClearColor(scene.fog.color, 1);

            renderer.domElement.style.position = IStyle.PositionEnum.absolute;
            renderer.domElement.style.top = "0px";
            renderer.domElement.style.left = "0px";

            container.appendChild(renderer.domElement);

            //    //

            renderer.gammaInput = true;
            renderer.gammaOutput = true;
            #endregion

            #region applyShader
            Action<THREE.ShaderExtrasModuleItem, object, object> applyShader = (shader, texture, target) =>
            {

                var shaderMaterial = new THREE.ShaderMaterial(
                    new THREE.ShaderMaterialArguments
                    {

                        fragmentShader = shader.fragmentShader,
                        vertexShader = shader.vertexShader,
                        uniforms = __THREE.UniformsUtils.clone(shader.uniforms)

                    }
                );

                shaderMaterial.uniforms.tDiffuse.texture = texture;

                var sceneTmp = new THREE.Scene();

                var meshTmp = new THREE.Mesh(new THREE.PlaneGeometry(Native.window.Width, Native.window.Height), shaderMaterial);
                meshTmp.position.z = -500;
                sceneTmp.add(meshTmp);

                renderer.render(sceneTmp, cameraOrtho, target, true);
            };
            #endregion


            var terrain = default(THREE.Mesh);

            #region loadTextures
            Action loadTextures = () =>
            {

                textureCounter += 1;

                if (textureCounter == 3)
                {

                    terrain.visible = true;

                    //document.getElementById("loading").style.display = "none";

                }

            };

            ////
            #endregion

            #endregion

            #region TEXTURES

            var specularMap = new THREE.WebGLRenderTarget(2048, 2048, pars);


            var diffuseTexture1 = default(THREE.WebGLRenderTarget);

            diffuseTexture1 = __THREE.ImageUtils.loadTexture(
                new global::WebGLDynamicTerrainTemplate.HTML.Images.FromAssets.grasslight_big().src,
                null,
                IFunction.Of(
                    delegate ()
                    {
                        loadTextures();
                        applyShader(__THREE.ShaderExtras.luminosity, diffuseTexture1, specularMap);
                    }
                )
            );

            var diffuseTexture2 = __THREE.ImageUtils.loadTexture(
                   new global::WebGLDynamicTerrainTemplate.HTML.Images.FromAssets.backgrounddetailed6().src,
                   null,
                   IFunction.Of(
                       delegate ()
                       {
                           loadTextures();
                       }
                   )
               );

            var detailTexture = __THREE.ImageUtils.loadTexture(
              new global::WebGLDynamicTerrainTemplate.HTML.Images.FromAssets.grasslight_big_nm().src,
              null,
              IFunction.Of(
                  delegate ()
                  {
                      loadTextures();
                  }
              )
          );

            diffuseTexture1.wrapS = THREE_RepeatWrapping;
            diffuseTexture1.wrapT = THREE_RepeatWrapping;


            diffuseTexture2.wrapS = THREE_RepeatWrapping;
            diffuseTexture2.wrapT = THREE_RepeatWrapping;

            detailTexture.wrapS = THREE_RepeatWrapping;
            detailTexture.wrapT = THREE_RepeatWrapping;

            specularMap.wrapS = THREE_RepeatWrapping;
            specularMap.wrapT = THREE_RepeatWrapping;
            #endregion

            #region TERRAIN SHADER

            var terrainShader = __THREE.ShaderTerrain.terrain;

            var uniformsTerrain = __THREE.UniformsUtils.clone(terrainShader.uniforms);

            uniformsTerrain.tNormal.texture = normalMap;
            uniformsTerrain.uNormalScale.value = 3.5;

            uniformsTerrain.tDisplacement.texture = heightMap;

            uniformsTerrain.tDiffuse1.texture = diffuseTexture1;
            uniformsTerrain.tDiffuse2.texture = diffuseTexture2;
            uniformsTerrain.tSpecular.texture = specularMap;
            uniformsTerrain.tDetail.texture = detailTexture;

            uniformsTerrain.enableDiffuse1.value = true;
            uniformsTerrain.enableDiffuse2.value = true;
            uniformsTerrain.enableSpecular.value = true;

            ((THREE.Color)uniformsTerrain.uDiffuseColor.value).setHex(0xffffff);
            ((THREE.Color)uniformsTerrain.uSpecularColor.value).setHex(0xffffff);
            ((THREE.Color)uniformsTerrain.uAmbientColor.value).setHex(0x111111);

            uniformsTerrain.uShininess.value = 30;
            uniformsTerrain.uDisplacementScale.value = 375;

            ((THREE.Vector2)uniformsTerrain.uRepeatOverlay.value).set(6, 6);


            var _params = new[] {
                new { id= "heightmap", fragmentShader= new Shaders.NoiseFragmentShader().ToString(), vertexShader=  vertexShader, uniforms= (object)uniformsNoise, lights = false },
                new { id="normal", fragmentShader=  normalShader.fragmentShader,  vertexShader=normalShader.vertexShader, uniforms=(object)uniformsNormal, lights = false },
                new { id="terrain", fragmentShader= terrainShader.fragmentShader, vertexShader=terrainShader.vertexShader, uniforms=(object)uniformsTerrain, lights = true }
            };

            for (var i = 0; i < _params.Length; i++)
            {

                var material = new THREE.ShaderMaterial(
                    new THREE.ShaderMaterialArguments
                    {

                        uniforms = (THREE.ShaderExtrasModuleItem_uniforms)_params[i].uniforms,
                        vertexShader = _params[i].vertexShader,
                        fragmentShader = _params[i].fragmentShader,
                        lights = _params[i].lights,
                        fog = true
                    }
                );

                mlib[(string)_params[i].id] = material;

            }


            var plane = new THREE.PlaneGeometry(Native.window.Width, Native.window.Height);

            var quadTarget = new THREE.Mesh(
                plane,
                new THREE.MeshBasicMaterial(
                    new THREE.MeshBasicMaterialArguments { color = 0xff0000 }
                    )
                    );

            quadTarget.position.z = -500;
            sceneRenderTarget.addObject(quadTarget);
            #endregion

            #region TERRAIN MESH

            var geometryTerrain = new THREE.PlaneGeometry(6000, 6000, 256, 256);
            geometryTerrain.computeFaceNormals();
            geometryTerrain.computeVertexNormals();
            geometryTerrain.computeTangents();

            terrain = new THREE.Mesh(geometryTerrain, mlib["terrain"]);
            terrain.rotation.set(-Math.PI / 2.0, 0, 0);
            terrain.position.set(0, -125, 0);
            terrain.visible = false;
            scene.add(terrain);
            #endregion






            #region COMPOSER

            renderer.autoClear = false;



            var renderTargetParameters = new THREE.WebGLRenderTargetArguments
            {
                minFilter = THREE_LinearFilter,
                magFilter = THREE_LinearFilter,
                format = THREE_RGBFormat,
                stencilBufer = false
            };

            var renderTarget = new THREE.WebGLRenderTarget((int)SCREEN_WIDTH, (int)SCREEN_HEIGHT, renderTargetParameters);

            var effectBloom = new THREE.BloomPass(0.6);
            var effectBleach = new THREE.ShaderPass(__THREE.ShaderExtras.bleachbypass);

            var hblur = new THREE.ShaderPass(__THREE.ShaderExtras.horizontalTiltShift);
            var vblur = new THREE.ShaderPass(__THREE.ShaderExtras.verticalTiltShift);

            var bluriness = 6;

            hblur.uniforms.h.value = bluriness / SCREEN_WIDTH;
            vblur.uniforms.v.value = bluriness / SCREEN_HEIGHT;

            hblur.uniforms.r.value = 0.5;
            vblur.uniforms.r.value = 0.5;

            effectBleach.uniforms.opacity.value = 0.65;

            var composer0 = new THREE.EffectComposer(renderer, renderTarget);

            var renderModel = new THREE.RenderPass(scene, camera);

            vblur.renderToScreen = true;

            var composer = new THREE.EffectComposer(renderer, renderTarget);

            composer.addPass(renderModel);

            composer.addPass(effectBloom);
            //composer.addPass( effectBleach );

            composer.addPass(hblur);
            composer.addPass(vblur);
            #endregion

            var r = new Random();

            Func<f> Math_random = () => (f)r.NextDouble();



            #region addMorph

            Action<MyModelGeometry, f, f, f, f, f> addMorph = (geometry, speed, duration, x, y, z) =>
            {

                var material = new THREE.MeshLambertMaterial(
                    new THREE.MeshLambertMaterialArguments
                    {
                        color = 0xffaa55,
                        morphTargets = true,
                        vertexColors = THREE_FaceColors
                    }
                );


                var meshAnim = new THREE.MorphAnimMesh(geometry, material);

                meshAnim.speed = speed;
                meshAnim.duration = duration;
                meshAnim.time = 600.0 * Math_random();

                meshAnim.position.set(x, y, z);
                meshAnim.rotation.y = (f)(Math.PI / 2f);

                meshAnim.castShadow = true;
                meshAnim.receiveShadow = false;

                scene.add(meshAnim);

                morphs.Add(meshAnim);

                renderer.initWebGLObjects(scene);

            };
            #endregion

            #region morphColorsToFaceColors

            Action<MyModelGeometry> morphColorsToFaceColors = (geometry) =>
            {

                if (geometry.morphColors != null)
                    if (geometry.morphColors.Length > 0)
                    {

                        var colorMap = geometry.morphColors[0];

                        for (var i = 0; i < colorMap.colors.Length; i++)
                        {

                            geometry.faces[i].color = colorMap.colors[i];

                        }

                    }

            };
            #endregion

            #region Models
            var loader = new THREE.JSONLoader();

            var startX = -3000;


            loader.load(
                new Models.parrot().Content.src,

                IFunction.OfDelegate(
                    new Action<MyModelGeometry>(
                        geometry =>
                        {
                            morphColorsToFaceColors(geometry);

                            addMorph(geometry, 250, 500, startX - 500, 500, 700);
                            addMorph(geometry, 250, 500, startX - Math_random() * 500, 500, -200);
                            addMorph(geometry, 250, 500, startX - Math_random() * 500, 500, 200);
                            addMorph(geometry, 250, 500, startX - Math_random() * 500, 500, 1000);
                        }
                    )
                )
            );

            loader.load(
                new Models.flamingo().Content.src,
                IFunction.OfDelegate(
                    new Action<MyModelGeometry>(
                        geometry =>
                        {
                            morphColorsToFaceColors(geometry);
                            addMorph(geometry, 500, 1000, startX - Math_random() * 500, 350, 40);
                        }
                    )
                )
            );


            loader.load(
                new Models.stork().Content.src,
                IFunction.OfDelegate(
                        new Action<MyModelGeometry>(
                            geometry =>
                            {
                                morphColorsToFaceColors(geometry);
                                addMorph(geometry, 350, 1000, startX - Math_random() * 500, 350, 340);
                            }
                        )
                    )
            );
            #endregion



            #region PRE-INIT

            renderer.initWebGLObjects(scene);
            #endregion


            #region onkeydown
            Native.document.body.onkeydown +=
                 (e) =>
                 {

                     if (e.KeyCode == 78) lightDir *= -1;
                     if (e.KeyCode == 77) animDeltaDir *= -1;
                     if (e.KeyCode == 66) soundDir *= -1;

                 };
            #endregion



            Action __loaded = null;

            #region event Action loaded;

            Native.window.parent.With(
                parent =>
                {
                    __loaded = delegate
                    {
                        __loaded = null;
                        parent.postMessage("WebGLDynamicTerrainTemplate.loaded");
                    };
                }
            );
            #endregion


            #region render
            Action render = () =>
            {

                var delta = clock.getDelta();

                soundVal = __THREE.Math.clamp(soundVal + delta * soundDir, 0, 1);

                if (soundVal != oldSoundVal)
                {

                    if (soundtrack != null)
                    {

                        soundtrack.volume = soundVal;
                        oldSoundVal = soundVal;

                    }

                }

                //Native.Document.title = "textureCounter " + textureCounter;


                if (terrain.visible)
                {

                    controls.update();

                    var Date_now = new IDate().getTime();
                    var time = Date_now * 0.001;

                    var fLow = 0.4;
                    var fHigh = 0.825;

                    lightVal = __THREE.Math.clamp(lightVal + 0.5 * delta * lightDir, fLow, fHigh);

                    var valNorm = (lightVal - fLow) / (fHigh - fLow);

                    var sat = __THREE.Math.mapLinear(valNorm, 0, 1, 0.95, 0.25);
                    scene.fog.color.setHSV(0.1, sat, lightVal);

                    renderer.setClearColor(scene.fog.color, 1);

                    spotLight.intensity = __THREE.Math.mapLinear(valNorm, 0, 1, 0.1, 1.15);
                    pointLight.intensity = __THREE.Math.mapLinear(valNorm, 0, 1, 0.9, 1.5);

                    uniformsTerrain.uNormalScale.value = __THREE.Math.mapLinear(valNorm, 0, 1, 0.6, 3.5);

                    if (updateNoise)
                    {

                        animDelta = __THREE.Math.clamp(animDelta + 0.00075 * animDeltaDir, 0, 0.05);
                        uniformsNoise.time.value = ((f)uniformsNoise.time.value) + delta * animDelta;

                        var uniformsNoise_offset_value = (THREE.Vector3)uniformsNoise.offset.value;
                        uniformsNoise_offset_value.x += delta * 0.05f;

                        var uniformsTerrain_uOffset_value = (THREE.Vector3)uniformsTerrain.uOffset.value;
                        uniformsTerrain_uOffset_value.x = 4.0f * uniformsNoise_offset_value.x;

                        quadTarget.material = mlib["heightmap"];
                        renderer.render(sceneRenderTarget, cameraOrtho, heightMap, true);

                        quadTarget.material = mlib["normal"];
                        renderer.render(sceneRenderTarget, cameraOrtho, normalMap, true);

                        //updateNoise = false;

                    }


                    for (var i = 0; i < morphs.Count; i++)
                    {

                        var morph = morphs[i];

                        morph.updateAnimation(1000 * delta);

                        morph.position.x += morph.speed * delta;

                        if (morph.position.x > 2000)
                        {

                            morph.position.x = -1500 - Math_random() * 500;

                        }


                    }

                    //renderer.render( scene, camera );
                    composer.render(0.1);


                    if (__loaded != null)
                        __loaded();
                }
                else
                {
                }

            };
            #endregion





            Native.window.onframe +=
                delegate
                {
                    if (IsDisposed)
                        return;


                    render();


                };




            #endregion



            #region IsDisposed

            Dispose = delegate
            {
                if (IsDisposed)
                    return;

                IsDisposed = true;

                //page.song.pause();
                soundtrack.pause();

                container.Orphanize();
            };
            #endregion






            #region AtResize
            Action AtResize = delegate
            {
                container.style.SetLocation(0, 0, Native.window.Width, Native.window.Height);

                renderer.setSize(Native.window.Width, Native.window.Height);

                camera.aspect = Native.window.Width / Native.window.Height;
                camera.updateProjectionMatrix();
            };

            Native.window.onresize +=
                delegate
                {
                    AtResize();
                };

            AtResize();
            #endregion


            Native.document.body.onmousedown +=
                e =>
                {
                    if (e.MouseButton == IEvent.MouseButtonEnum.Middle)
                    {
                        Native.document.body.requestFullscreen();
                    }
                };

            #region requestFullscreen
            Native.document.body.ondblclick +=
                delegate
                {
                    if (IsDisposed)
                        return;

                    // http://tutorialzine.com/2012/02/enhance-your-website-fullscreen-api/

                    Native.document.body.requestFullscreen();

                    //AtResize();
                };
            #endregion


        }
		private static void CreateRotor(double _angle, IHTMLElement _container)
		{

			var shadow = new IHTMLDiv();
			shadow.style.position = IStyle.PositionEnum.absolute;
			shadow.style.left = "0px";
			shadow.style.top = "0px";
			shadow.style.width = "600px";
			shadow.style.height = "400px";
			shadow.style.backgroundColor = "black";
			shadow.style.Opacity = 0.3;
			shadow.AttachTo(_container);

			var borders = new IHTMLDiv();
			borders.style.position = IStyle.PositionEnum.absolute;
			borders.style.left = "0px";
			borders.style.top = "0px";
			//borders.style.width = "400px";
			//borders.style.height = "300px";
			borders.style.border = "4px solid black";
			borders.style.Opacity = 0.1;
			borders.AttachTo(_container);

			var a = new IHTMLDiv();

			// we can specify rotation origin within red area!

			a.style.backgroundColor = "red";

			a.style.marginTop = "-200px";
			a.style.marginLeft = "-300px";
			a.style.paddingLeft = "300px";
			a.style.paddingTop = "200px";

			var c = new IHTMLDiv();

			var z = new IHTMLButton("hi");


			z.AttachTo(c);
			c.AttachTo(a);

			//a.style.width = "300px";
			//a.style.height = "200px";

			c.style.width = "300px";
			c.style.height = "200px";
			//c.style.position = IStyle.PositionEnum.relative;
			//c.style.SetLocation(0, 0);
			//c.style.clip = "rect(0px,60px,200px,0px)";

			c.appendChild("hello world");
			c.appendChild(new IHTMLButton("click me"));

			var xx = new IHTMLButton("xx");

			xx.style.SetLocation(32, 32);

			c.appendChild(xx);
			c.appendChild("hello world");

			new IHTMLDiv
			{
				innerText =
					@"As it seems we can use apng files but 
we cannot have absolute children. This means we will be able to support
non container objects."
			}.AttachTo(c);


			c.style.SetBackground("assets/MatrixTransformExample/bg.png", true);

			var t = new IHTMLDiv();

			c.appendChild(t);

			//a.style.width = "400px";
			//a.style.height = "300px";


			
			var angle = _angle;
			ApplyRotation2(a, angle, 1, 200, 0);

			new Timer(
				delegate
				{
					t.innerHTML = "" + angle;
					angle -= 2;
					ApplyRotation2(a, angle, 1, 200, 0);

					borders.style.SetSize(a.offsetWidth, a.offsetHeight);

					borders.style.SetLocation((a.clientWidth - a.offsetWidth) / 2, (a.clientHeight - a.offsetHeight) / 2);
					a.style.SetLocation((a.clientWidth - a.offsetWidth) / 2, (a.clientHeight - a.offsetHeight) / 2);

				}
				, 0, 250
			);


			a.AttachTo(_container);
		}
        //public const string Alias = "Class1";
        //public const string DefaultData = "Class1Data";


        /// <summary>
        /// Creates a new control
        /// </summary>
        /// <param name="DataElement">The hidden data element</param>
        public SimpleRollover()
        {
            // wallpapers at http://labnol.blogspot.com/2006/11/download-windows-vista-wallpapers.html

            // * broken at the moment
            #region AnimateCharacterColors
            System.Func<string, INode> AnimateCharacterColors =
                (text) =>
                {
                    var s = new IHTMLSpan();

                    var l = new global::System.Collections.Generic.List<IHTMLSpan>();

                    foreach (char c in text)
                    {
                        var y = new string(c, 1);
                        var x = new IHTMLSpan(y);

                        if (y == " ")
                        {
                            s.appendChild(" ");
                        }
                        else
                        {
                            l.Add(x);


                            s.appendChild(x);
                        }


                    }



                    new Timer(
                        t =>
                        {
                            var len = l.Count + 40;

                            if (t.Counter % len < l.Count)
                            {
                                if (t.Counter % (len * 2) < l.Count)
                                {
                                    l[t.Counter % len].style.visibility = IStyle.VisibilityEnum.hidden;
                                }
                                else
                                {
                                    l[t.Counter % len].style.visibility = IStyle.VisibilityEnum.visible;
                                }
                            }



                        }, 6000, 200);


                    return s;
                };
            #endregion
            // */

            var u = new IHTMLDiv();

            //u.style.backgroundColor = Color.Green;
            u.style.position = IStyle.PositionEnum.absolute;
            u.style.left = "0";
            u.style.top = "0";
            u.style.height = "100%";
            u.style.width = "100%";
            u.style.overflow = IStyle.OverflowEnum.auto;

            var styles = new XStyles
            {
                dark = new IStyleSheet(),
                light = new IStyleSheet(),
                switchbutton = new IHTMLAnchor("", "day/night"),
                counter = 0
            };



            styles.switchbutton.onclick +=
                ev =>
                {
                    ev.PreventDefault();

                    styles.counter++;


                    if (styles.counter % 2 == 1)
                    {
                        styles.dark.disabled = false;
                        styles.light.disabled = true;
                    }
                    else
                    {
                        styles.dark.disabled = true;
                        styles.light.disabled = false;
                    }
                };


            var ad = new IHTMLDiv(
                            new IHTMLSpan(
                                 AnimateCharacterColors(
                                "this application was written in c# and then translated to javascript by jsc to run in your browser"
                                 )
                            ),
                            new IHTMLAnchor("http://zproxy.wordpress.com", "visit blog"),
                            new IHTMLAnchor("http://jsc.sf.net", "get more examples"),
                            styles.switchbutton
                         )
                         {
                             className = "ad1"
                         };

            u.appendChild(ad);

            var sheet = new IStyleSheet();

            sheet.AddRule(".ad1",
                r =>
                {
                    r.style.marginTop = "1em";
                    r.style.color = Color.White;
                    r.style.fontFamily = IStyle.FontFamilyEnum.Verdana;
                }
            );


            sheet.AddRule(".ad1 > *",
                r =>
                {
                    r.style.padding = "1em";

                    r.style.marginTop = "1em";
                }
            );

            sheet.AddRule(".ad1 > span",
                r =>
                {
                    r.style.Float = IStyle.FloatEnum.right;
                }
            );

            sheet.AddRule(".ad1 > a",
                r =>
                {
                    r.style.Float = IStyle.FloatEnum.left;
                    r.style.color = Color.White;

                    r.style.textDecoration = "none";
                }
            );

            sheet.AddRule(".ad1 a:hover",
                r =>
                {
                    r.style.color = Color.Yellow;
                }
            );



            sheet.AddRule("html",
                r =>
                {

                    r.style.overflow = IStyle.OverflowEnum.hidden;
                }
            );

            sheet.AddRule("body",
                r =>
                {
                    r.style.overflow = IStyle.OverflowEnum.hidden;

                    r.style.padding = "0";
                    r.style.margin = "0";

                    //r.style.backgroundImage = "url(assets/vista.jpg)";

                }
            );


            styles.dark.AddRule("body").style.backgroundColor = JSColor.Black;
            styles.dark.AddRule("body").style.backgroundPosition = "center top";

            styles.light.AddRule("body").style.backgroundColor = JSColor.Black;
            styles.light.AddRule("body").style.backgroundPosition = "center top";


            new global::SimpleRollover.HTML.Images.FromAssets.vistax().ToBackground(
                styles.dark.AddRule("body").style, false
            );

            new global::SimpleRollover.HTML.Images.FromAssets.vista().ToBackground(
                styles.dark.AddRule(".effect1").style
            );

            styles.dark.AddRule(".moon1").style.backgroundColor = Color.Yellow;

            new global::SimpleRollover.HTML.Images.FromAssets.vista().ToBackground(
                styles.light.AddRule("body").style, false
            );

            new global::SimpleRollover.HTML.Images.FromAssets.vistax().ToBackground(
                 styles.light.AddRule(".effect1").style
            );
            styles.light.AddRule(".moon1").style.backgroundColor = Color.Red;


            sheet.AddRule(".special1",
                r =>
                {
                    r.style.background = "none";
                    r.style.border = "0";
                    r.style.width = "100%";
                    r.style.marginTop = "4em";


                }
            );

            sheet.AddRule(".content1",
                r =>
                {
                    r.style.backgroundColor = Color.White;

                    r.style.padding = "1em";
                    r.style.marginLeft = "4em";
                    r.style.marginRight = "4em";
                    r.style.Opacity = 0.5;
                    r.style.border = "1px solid gray";
                }
            );

            sheet.AddRule(".special1 img", "border: 0", 0);
            sheet.AddRule(".special1:hover", "background: url(" + new global::SimpleRollover.HTML.Images.FromAssets.Untitled_3().src + ") repeat-x", 1);

            sheet.AddRule(".special1 .hot").style.display = IStyle.DisplayEnum.none;
            sheet.AddRule(".special1:hover .hot").style.display = IStyle.DisplayEnum.inline;

            sheet.AddRule(".special1 .cold", "display: inline;", 1);
            sheet.AddRule(".special1:hover .cold", "display: none;", 1);


            var states = new XState[] { }.AsEnumerable();

            //    new XState { 
            //        Show = default(System.Action), 
            //        Hide = default(System.Action), 
            //        Selected = false } 
            //}.Where(p => false);


            Action<IHTMLImage, IHTMLImage, string> Spawn =
                async (icold, ihot, i2) =>
                {
                    var cold = await icold;
                    var hot = await ihot;

                    //((IHTMLImage)i[0]).InvokeOnComplete(cold =>
                    //((IHTMLImage)i[1]).InvokeOnComplete(hot =>
                    //     {
                    cold.className = "cold";
                    hot.className = "hot";


                    var btn = new IHTMLButton()
                        {
                            className = "special1"
                        };

                    btn.appendChild(cold, hot);

                    var content = new IHTMLElement(IHTMLElement.HTMLElementEnum.pre);

                    content.innerHTML = "...";
                    content.className = "content1";

                    var tween = new TweenDataDouble();
                    var tween_max = 16;

                    tween.ValueChanged +=
                        delegate
                        {
                            content.style.Opacity = tween.Value / tween_max;
                            content.style.height = tween.Value + "em";

                            content.style.overflow = IStyle.OverflowEnum.hidden;

                        };

                    tween.Done += delegate
                    {
                        if (tween.Value > 0)
                            content.style.overflow = IStyle.OverflowEnum.auto;
                    };

                    tween.Value = 0;

                    var state = new XState
                       {
                           Show = (System.Action)(() =>
                                               {
                                                   tween.Value = tween_max;
                                               }
                           ),
                           Hide = (System.Action)(() => tween.Value = 0),
                           Selected = false
                       };

                    //try
                    //{
                    //    new IXMLHttpRequest(HTTPMethodEnum.GET, i[2],
                    //       request => content.innerHTML = request.responseText
                    //    );
                    //}
                    //catch
                    //{
                    content.innerText = i2;
                    //}

                    states = states.Concat(new[] { state });

                    btn.onclick +=
                        delegate
                        {
                            foreach (var v in states)
                            {
                                if (v == state)
                                {

                                    v.Selected = !v.Selected;

                                    if (v.Selected)
                                    {
                                        v.Show();
                                    }
                                    else
                                    {
                                        v.Hide();
                                    }

                                }
                                else
                                {
                                    v.Selected = false;
                                    v.Hide();
                                }
                            }
                        };

                    u.appendChild(btn, content);




                };


            SpawnCursor();


            u.AttachToDocument();

            Spawn(
                new global::SimpleRollover.HTML.Images.FromAssets.Untitled_1_03(),
                new global::SimpleRollover.HTML.Images.FromAssets.Untitled_2_03(),
                "This application was written in C#."
            );

            Spawn(
                new global::SimpleRollover.HTML.Images.FromAssets.Untitled_1_07(),
                new global::SimpleRollover.HTML.Images.FromAssets.Untitled_2_07(),

                 "This application was cross compiled into JavaScript."
            );


        }
示例#19
0
        /// <summary>
        /// This is a javascript application.
        /// </summary>
        /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param>
        public Application(IDefaultPage page)
        {
            @"Hello world".ToDocumentTitle();
            // Send data from JavaScript to the server tier
            service.WebMethod2(
                @"A string from JavaScript.",
                value => value.ToDocumentTitle()
            );



            var x = new IHTMLDiv();

            var size = new
            {
                w = Native.Window.Width,
                h = Native.Window.Height
            };

            x.style.SetLocation(0, 0, size.w, size.h);

            x.style.backgroundColor = Color.Blue;
            x.style.color = Color.Yellow;
            x.style.overflow = ScriptCoreLib.JavaScript.DOM.IStyle.OverflowEnum.hidden;

            x.AttachToDocument();

            Action<string> Append =
                e =>
                {
                    x.appendChild(new IHTMLDiv(e));

                    if (x.childNodes.Length > 20) x.removeChild(x.firstChild);

                };

            Append("size: " + size);

            Native.Document.onkeydown +=
                ev => Append("keydown: " + ev.KeyCode);


            Native.Document.onkeyup +=
                ev => Append("keyup: " + ev.KeyCode);

            Native.Document.onkeypress +=
                ev => Append("keypress: " + ev.KeyCode);


            Native.Document.onclick +=
                ev => Append("click: " + ev.OffsetPosition);

            Native.Document.body.ontouchstart +=
            ev =>
            {
                ev.PreventDefault();

                Append("ontouchstart: " + ev.touches.length);
            };



            Native.Document.body.ontouchmove +=
            ev =>
            {
                ev.PreventDefault();

                Append("ontouchmove: " + ev.touches.length + new { 
                    ev.touches[0].clientX, ev.touches[0].clientY });
            };

            Native.Document.body.ontouchend +=
                ev =>
                {
                    ev.PreventDefault();

                    Append("ontouchend: " + 
                        new { 
                            touches = ev.touches.length, 
                            changedTouches = ev.changedTouches.length ,
                            targetTouches = ev.targetTouches.length 
                        }
                    );
                };



        }