示例#1
0
        /// <summary>
        /// fades an element and provides async callback
        /// </summary>
        /// <param name="target"></param>
        /// <param name="waittime"></param>
        /// <param name="fadetime"></param>
        /// <param name="done"></param>
        static public void Fade(IHTMLElement target, int waittime, int fadetime, System.Action done)
        {
            // if IE
            target.style.height = target.clientHeight + "px";

            new Timer(
                delegate
                {
                    Timer a = null;

                    a = new Timer(
                        delegate
                        {

                            target.style.Opacity = 1 - (a.Counter / a.TimeToLive);

                            if (a.Counter == a.TimeToLive)
                            {
                                if (done != null)
                                    done();

                            }

                        }
                        );


                    a.StartInterval(fadetime / 25, 25);
                }
            ).StartTimeout(waittime);
        }
示例#2
0
        void Worker_Tick(Timer e)
        {
            try
            {
                EntryItem i = List[0];

                List.RemoveAt(0);

                double z = IDate.Now.getTime();

                i.Handler();

                if (IDate.Now.getTime() - z > Timeout)
                {
                    System.Console.WriteLine("workpool timeout exceeded");

                    

                    Helper.Invoke(Abort, this);

                    List.Clear();
                }
            }
            catch (global::System.Exception ex)
            {
                if (Error != null)
                    Error(ex);
            }

            Touch();
        }
示例#3
0
        static public void FadeOut(IHTMLElement target, int waittime, int fadetime)
        {
            target.style.Opacity = 1;

            new Timer(
                delegate
                {
                    Timer a = null;

                    a = new Timer(
                        delegate
                        {

                            target.style.Opacity = 1 - (a.Counter / a.TimeToLive);

                            if (a.Counter == a.TimeToLive)
                            {
                                target.Hide();

                            }

                        }
                    );


                    a.StartInterval(fadetime / 25, 25);
                }
            ).StartTimeout(waittime);
        }
示例#4
0
		static public void FadeIn(this IHTMLElement target, int waittime, int fadetime, Action done)
		{
			// if IE
			target.style.height = target.clientHeight + "px";

			target.style.Opacity = 0;

			waittime.AtDelay(
				delegate
				{
					Timer a = null;

					a = new Timer(
						delegate
						{

							target.style.Opacity = (a.Counter / a.TimeToLive);

							if (a.Counter == a.TimeToLive)
							{
								target.style.Opacity = 1;

								if (done != null)
									done();

							}

						}
						);


					a.StartInterval(fadetime / 25, 25);
				}
			);
		}
        void t_Tick(Timer e)
        {
            if (_async)
                return;

            _async = true;


            try
            {
                r = new IXMLHttpRequest();
                r.open(HTTPMethodEnum.HEAD, Url);
                r.send();
            }
            catch
            {
                Native.window.alert(" send error ");
            }

            r.InvokeOnComplete(
                delegate(IXMLHttpRequest rr)
                {
                    

                    if (RequestComplete != null)
                        RequestComplete(this);

                    if (rr.status == IXMLHttpRequest.HTTPStatusCodes.OK)
                    {
                        string z = rr.ETag;

                        bool b = (z != ETag) && (ETag != null) && (z != null);

                        ETag = z;

                        if (b)
                        {
                            if (ETagChanged != null)
                                ETagChanged(this);

                            this.Enabled = false;
                            return;
                        }


                    }
                    else
                    {
                        this.Enabled = false;
                        return;
                    }


                    _async = false;
                

            }
            );
        }
示例#6
0
        void timer_Tick(Timer e)
        {
            if (value > step)
            {
                Console.WriteLine("tick");

                value -= step;

                //Base.style.backgroundColor = Color.Red;

                Base.style.Opacity = 1 - (value / 0xFF);

                if (value <= step)
                {
                    Console.WriteLine("// we are done");


                    
                    timer.Stop();

                    //this.Base.style.backgroundColor = Color.Red;

                    WorkPool p = Fader.FlashAndFadeOut(this.Base, 15);


                    p += delegate
                    {
                        new SubSquare(
                        Rectangle.Of(Location.Left, Location.Top, Location.Width / 2, Location.Height / 2)
                        , _bg
                          );

                        new SubSquare(
                            Rectangle.Of(Location.Left + Location.Width / 2, Location.Top, Location.Width / 2, Location.Height / 2)
                            , _bg
                        );

                        new SubSquare(
                            Rectangle.Of(Location.Left + Location.Width / 2, Location.Top + Location.Height / 2, Location.Width / 2, Location.Height / 2)
                            , _bg
                        );

                        new SubSquare(
                            Rectangle.Of(Location.Left, Location.Top + Location.Height / 2, Location.Width / 2, Location.Height / 2)
                            , _bg
                        );

                        this.Base.Orphanize();
                    };
                }
            }
            else
                timer.Stop();
        }
示例#7
0
        public __Timer(IContainer e)
        {
            //Console.WriteLine("__Timer.ctor IContainer");


            Target = new Timer();
            Target.Tick += t =>
                {
                    //Console.WriteLine("Target.Tick");

                    if (this.Tick != null)
                        this.Tick(this, null);
                };

            _Interval = 100;
        }
			private void InternalAnimate()
			{
				var c = Frames.AsCyclicEnumerator();
				var x = Image;

				var t = new Timer(
					delegate
					{
						c.MoveNext();
						x.parentNode.replaceChild(c.Current, x);
						//x.parentNode.insertBefore(c.Current, x);
						//x.parentNode.removeChild(x);
						x = c.Current;
					}, 1, Interval
				);
			}
        public static void Trigger(this Func<bool> condition, Action done, int interval)
        {
            Timer t = null;

            t = new Timer(
                delegate
                {
                    if (!condition())
                    {
                        t.Stop();

                        done();
                    }
                }
            );

            t.StartInterval(interval);
        }
示例#10
0
		static public void FadeOut(this IHTMLElement target, int waittime, int fadetime, Action done)
		{
			waittime.AtDelay(
				delegate
				{
					if (null == target)
					{
						done();
						return;
					}

					Timer a = null;

					a = new Timer(
						delegate
						{

							var Opacity = 1.0 - (a.Counter / a.TimeToLive);

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

							target.style.Opacity = Opacity;

							if (a.Counter == a.TimeToLive)
							{
								target.style.Opacity = 0;

								if (done != null)
									done();

							}

						}
						);


					a.StartInterval(fadetime / 25, 25);
				}
			);
		}
示例#11
0
        void SpawnAnimation(IHTMLImage img, int x, int y, int w, int h, int from, int to, Timer t)
        {
            var div = new IHTMLDiv();
            var animate = true;

            div.style.SetSize(w, h);
            div.style.backgroundRepeat = "no-repeat";
            div.style.backgroundImage = "url(" + img.src + ")";

            div.SetCenteredLocation(x, y);
            Native.Document.body.appendChild(div);

            div.onmouseover += delegate { animate = false; };
            div.onmouseout += delegate { animate = true; };

            var frame = from;

            t.Tick += delegate
            {
                if (!animate)
                    return;

                frame++;

                if (frame > to)
                    frame = from;

                div.style.backgroundPosition = -(frame * w) + "px 0px";
            };
        }
        /// <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();

        }
示例#13
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)
        {
            var SpiderModelContent = new SpiderModel.ApplicationContent();


            page.program_13_turn_left.onclick += delegate { SpiderModelContent.po = 13; };
            page.program_14_turn_right.onclick += delegate { SpiderModelContent.po = 14; };
            page.program_15_go_backwards.onclick += delegate { SpiderModelContent.po = 15; };
            page.program_16_go_forwards.onclick += delegate { SpiderModelContent.po = 16; };
            page.program_53_mayday.onclick += delegate { SpiderModelContent.po = 53; };
            page.program_43_high_five_calibration_stand.onclick += delegate { SpiderModelContent.po = 43; };
            page.stop.onclick += delegate { SpiderModelContent.po = 0; ; };

            new Timer(
                tttt =>
                {
                    var pp = SpiderModelContent.pp;

                    if (tttt.Counter % 2 == 0)
                        pp = 0;

                    if (pp == 13)
                        page.program_13_turn_left.style.color = JSColor.Blue;
                    else
                        page.program_13_turn_left.style.color = JSColor.None;

                    if (pp == 14)
                        page.program_14_turn_right.style.color = JSColor.Blue;
                    else
                        page.program_14_turn_right.style.color = JSColor.None;

                    if (pp== 15)
                        page.program_15_go_backwards.style.color = JSColor.Blue;
                    else
                        page.program_15_go_backwards.style.color = JSColor.None;


                    if (pp == 16)
                        page.program_16_go_forwards.style.color = JSColor.Blue;
                    else
                        page.program_16_go_forwards.style.color = JSColor.None;
                },
                300,
                150
            );

            #region program_60
            page.program_60.onclick += delegate
            {
                #region po
                Action<int> po =
                    v =>
                    {
                        page.program_60.innerText = "program_60: " + v;
                        SpiderModelContent.po = v;
                    };
                #endregion



                #region po_to_po
                Action<int, int> po_to_po =
                    (from, to) =>
                    {
                        if (SpiderModelContent.po != from)
                            return;

                        po(to);
                    };
                #endregion



                #region po_to_po_at
                Action<int, int, int> po_to_po_at =
                    (from, to, xdelay) =>
                    {
                        new Timer(delegate { po_to_po(from, to); }, xdelay * 1000, 0);
                    };
                #endregion

                // turn left until 3
                po(13);

                // wait 3 sec and go backwards until 6
                po_to_po_at(13, 15, 3);

                // wait 6 sec and turn right
                po_to_po_at(15, 14, 3 + 6);

                // wait 6 sec and go forwards until 6
                po_to_po_at(14, 16, 3 + 6 + 6);

                // wait 3 sec and stop
                po_to_po_at(16, 0, 3 + 6 + 6 + 6);
            };
            #endregion

            #region program_61
            page.program_61.onclick += delegate
            {
                #region po
                Action<int> po =
                    v =>
                    {
                        page.program_61.innerText = "program_61: " + v;
                        SpiderModelContent.po = v;
                    };
                #endregion



                #region po_to_po
                Action<int, int> po_to_po =
                    (from, to) =>
                    {
                        if (SpiderModelContent.po != from)
                            return;

                        po(to);
                    };
                #endregion



                #region po_to_po_at
                Action<int, int, int> po_to_po_at =
                    (from, to, xdelay) =>
                    {
                        new Timer(delegate { po_to_po(from, to); }, xdelay * 1000, 0);
                    };
                #endregion

                // turn left until 3
                po(14);

                // wait 3 sec and go backwards until 6
                po_to_po_at(14, 15, 3);

                // wait 6 sec and turn right
                po_to_po_at(15, 13, 3 + 6);

                // wait 6 sec and go forwards until 6
                po_to_po_at(13, 16, 3 + 6 + 6);

                // wait 3 sec and stop
                po_to_po_at(16, 0, 3 + 6 + 6 + 6);
            };
            #endregion

            @"Hello world".ToDocumentTitle();

            #region sidebars
            var LeftLR = new IHTMLDiv();

            LeftLR.style.position = IStyle.PositionEnum.absolute;
            LeftLR.style.left = "0";
            LeftLR.style.top = "0";
            LeftLR.style.bottom = "0";
            LeftLR.style.width = "4em";
            LeftLR.style.Opacity = 0.5;
            LeftLR.AttachToDocument();

            var LeftIR = new IHTMLDiv();

            LeftIR.style.position = IStyle.PositionEnum.absolute;
            LeftIR.style.left = "0";
            LeftIR.style.top = "0";
            LeftIR.style.height = "1em";
            LeftIR.style.width = "4em";
            LeftIR.style.Opacity = 0.8;
            LeftIR.AttachToDocument();
            LeftIR.style.backgroundColor = JSColor.FromRGB(0xB0, 0, 0);



            var RightLR = new IHTMLDiv();

            RightLR.style.position = IStyle.PositionEnum.absolute;
            RightLR.style.right = "0";
            RightLR.style.top = "0";
            RightLR.style.bottom = "0";
            RightLR.style.Opacity = 0.5;
            RightLR.style.width = "4em";
            RightLR.AttachToDocument();


            var RightIR = new IHTMLDiv();

            RightIR.style.position = IStyle.PositionEnum.absolute;
            RightIR.style.right = "0";
            RightIR.style.top = "0";
            RightIR.style.height = "1em";
            RightIR.style.width = "4em";
            RightIR.style.Opacity = 0.8;
            RightIR.AttachToDocument();
            RightIR.style.backgroundColor = JSColor.FromRGB(0xB0, 0, 0);



            LeftLR.style.backgroundColor = JSColor.FromRGB(0x80, 0, 0);
            RightLR.style.backgroundColor = JSColor.FromRGB(0x80, 0, 0);
            #endregion

            page.PageContainer.AttachToDocument();
            page.PageContainer.style.color = JSColor.White;
            page.PageContainer.style.textShadow = "#000 0px 0px 3px";
            page.ElShadow.style.textShadow = "#000 0px 0px 3px";

            #region AtResize
            Action AtResize = delegate
            {
                page.PageContainer.style.SetLocation(0, 0, Native.Window.Width, Native.Window.Height);


            };

            AtResize();

            Native.Window.onresize += delegate { AtResize(); };
            #endregion

            var delay = new Timer(
                delegate
                {
                    Native.Document.body.style.cursor = IStyle.CursorEnum.wait;
                }
            );

            var COM46_Line_value = "";

            Func<double, double> sin = Math.Sin;

            #region deviceorientation
            var gamma = 0.0;
            var beta = 0.0;
            var alpha = 0.0;

            Window.deviceorientation +=
                e =>
                {
                    gamma = e.gamma;
                    beta = e.beta;
                    alpha = e.alpha;

                    if (beta < 20) SpiderModelContent.po = 16;
                    if (beta > 60) SpiderModelContent.po = 15;
                    if (gamma > 30) SpiderModelContent.po = 14;
                    if (gamma < -30) SpiderModelContent.po = 13;
                };
            #endregion


            #region COM46_Line_value_loop
            Action COM46_Line_value_loop = null;

            COM46_Line_value_loop = delegate
            {
                var t = SpiderModelContent.t;

                page.Content2.innerText = COM46_Line_value;

                page.Content.innerText = ""
                    //+ "\n: \t" + 
                    + "\nt: \t" + System.Convert.ToInt32((double)SpiderModelContent.t)
                    + "\np: \t" + SpiderModelContent.p
                    + "\npo: \t" + SpiderModelContent.po
                   + "\ncamera_z: \t" + System.Convert.ToInt32((double)SpiderModelContent.camera_z)
                    //+ "\nalpha: \t" + alpha
                    //+ "\nbeta: \t" + beta
                    //+ "\ngamma: \t" + gamma
                    + "\n"
                    + "\nRED leg1down_vertical_deg: \t" + System.Convert.ToInt32((double)SpiderModelContent.leg1down_vertical_deg)
                    + "\nGREEN leg2down_vertical_deg: \t" + System.Convert.ToInt32((double)SpiderModelContent.leg2down_vertical_deg)
                    + "\nBLUE leg3down_vertical_deg: \t" + System.Convert.ToInt32((double)SpiderModelContent.leg3down_vertical_deg)
                    + "\nWHITE leg4down_vertical_deg: \t" + System.Convert.ToInt32((double)SpiderModelContent.leg4down_vertical_deg)
                    + "\n"
                    + "\nRED leg1up_sideway_deg: \t" + System.Convert.ToInt32((double)SpiderModelContent.leg1up_sideway_deg)
                    + "\nGREEN leg2up_sideway_deg: \t" + System.Convert.ToInt32((double)SpiderModelContent.leg2up_sideway_deg)
                    + "\nBLUE leg3up_sideway_deg: \t" + System.Convert.ToInt32((double)SpiderModelContent.leg3up_sideway_deg)
                    + "\nWHITE leg4up_sideway_deg: \t" + System.Convert.ToInt32((double)SpiderModelContent.leg4up_sideway_deg);

                Native.Window.requestAnimationFrame += COM46_Line_value_loop;
            };

            Native.Window.requestAnimationFrame += COM46_Line_value_loop;
            #endregion


            #region Connect
            page.Connect.onclick +=
            delegate
            {
                SpiderModelContent.t_fix = 0;
                "Connect".ToDocumentTitle();
                SpiderModelContent.po = 0; ;
                service.AtFocus();
            };
            #endregion

            #region Disconnect
            page.Disconnect.onclick +=
                delegate
                {
                    "Disconnect".ToDocumentTitle();
                    SpiderModelContent.po = 0; ;
                    service.AtBlur();
                };
            #endregion


            Action poll = null;

            poll = delegate
                {
                    delay.StartTimeout(400);

                    // Send data from JavaScript to the server tier
                    service.WebMethod2(
                        "" + SpiderModelContent.po,
                        COM46_Line =>
                        {
                            Native.Document.body.style.cursor = IStyle.CursorEnum.@default;
                            delay.Stop();

                            COM46_Line_value = COM46_Line.Replace("\t", "\n");

                            // jsc: why string.split with each not working??

                            var a = COM46_Line.Split(';');

                            byte RightLR_value = 0;
                            byte LeftLR_value = 0;
                            var t = 0f;

                            #region parse RightLR, LeftLS, LeftIR, RightIR
                            for (int i = 0; i < a.Length; i++)
                            {
                                var u = a[i];

                                u.TakeUntilOrEmpty(":").Trim().With(
                                    key =>
                                    {
                                        var _value = u.SkipUntilOrEmpty(":").Trim();

                                        // 1024 is dark


                                        #region RightLR
                                        if (key == "RS")
                                        {

                                            var value_int32 = int.Parse(_value);
                                            var value_1024 = (1024 - Math.Min(int.Parse(_value), 1024));

                                            // jsc: please do the masking when casting to byte yyourself, thanks :)
                                            RightLR_value = (byte)((255 * value_1024 / 1024) & 0xff);
                                            RightLR_value = (byte)Math.Min(255, RightLR_value * 2);

                                            if (RightLR_value == 255)
                                                RightLR.style.backgroundColor = JSColor.Cyan;
                                            else
                                                RightLR.style.backgroundColor = JSColor.FromGray(RightLR_value);

                                        }
                                        #endregion

                                        #region LeftLS
                                        if (key == "LS")
                                        {

                                            var value_int32 = int.Parse(_value);
                                            var value_1024 = (1024 - Math.Min(int.Parse(_value), 1024));

                                            // jsc: please do the masking when casting to byte yyourself, thanks :)
                                            LeftLR_value = (byte)((255 * value_1024 / 1024) & 0xff);
                                            LeftLR_value = (byte)Math.Min(255, LeftLR_value * 2);

                                            //LeftLR.innerText = "" + ivalue;

                                            if (LeftLR_value == 255)
                                                LeftLR.style.backgroundColor = JSColor.Cyan;
                                            else
                                                LeftLR.style.backgroundColor = JSColor.FromGray(LeftLR_value);

                                        }
                                        #endregion

                                        #region LeftIR
                                        if (key == "LI")
                                        {

                                            var value_int32 = int.Parse(_value);

                                            if (value_int32 > 400)
                                                LeftIR.style.backgroundColor = JSColor.Red;
                                            else
                                                if (value_int32 > 200)
                                                    LeftIR.style.backgroundColor = JSColor.Yellow;
                                                else
                                                    LeftIR.style.backgroundColor = JSColor.Green;

                                            LeftIR.style.height = value_int32 + "px";

                                            SpiderModelContent.tween_red_obstacle_L_y((1 - value_int32 / 600) * 24);
                                        }
                                        #endregion

                                        #region RightIR
                                        if (key == "RI")
                                        {

                                            var value_int32 = int.Parse(_value);

                                            if (value_int32 > 400)
                                                RightIR.style.backgroundColor = JSColor.Red;
                                            else
                                                if (value_int32 > 200)
                                                    RightIR.style.backgroundColor = JSColor.Yellow;
                                                else
                                                    RightIR.style.backgroundColor = JSColor.Green;



                                            RightIR.style.height = value_int32 + "px";
                                            SpiderModelContent.tween_red_obstacle_R_y((1 - value_int32 / 600) * 24);

                                        }
                                        #endregion

                                        if (key == "t")
                                        {
                                            t = (float)double.Parse(_value);
                                        }

                                        if (key == "pp")
                                        {
                                            SpiderModelContent.p = int.Parse(_value);
                                        }
                                    }
                                );
                            }
                            #endregion

                            if (t != 0)
                                if (SpiderModelContent.t_local != 0)
                                    if (SpiderModelContent.t_fix == 0)
                                        SpiderModelContent.t_fix = t - SpiderModelContent.t_local;



                            // dark 70 .. 255 bright

                            SpiderModelContent.tween_white_arrow_y(
                                50 * (1 - ((Math.Max(LeftLR_value, RightLR_value) - 70) / (255 - 70)))
                            );

                            SpiderModelContent.tween_white_arrow_x(
                                (LeftLR_value - 60) * -20f / (255 - 60)
                            + (RightLR_value - 60) * 20f / (255 - 60)
                            );


                            #region next
                            new Timer(
                               delegate
                               {
                                   Native.Window.requestAnimationFrame += poll;
                               }
                           ).StartTimeout(UpdateSpeed);
                            #endregion

                        }
                    );

                    page.FastUpdates.onclick += delegate
                    {
                        UpdateSpeed = 50;
                    };

                    page.SlowUpdates.onclick += delegate
                    {
                        UpdateSpeed = 500;
                    };
                };

            Native.Window.requestAnimationFrame += poll;

        }
示例#14
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(IApp page)
        {
            DiagnosticsConsole.ApplicationContent.BindKeyboardToDiagnosticsConsole();

            FormStyler.AtFormCreated =
                  s =>
                  {

                      FormStyler.LikeVisualStudioMetro(s);

                      s.TargetOuterBorder.style.borderColor = ScriptCoreLib.JavaScript.Runtime.JSColor.FromRGB(0, 127, 0);
                      s.Caption.style.backgroundColor = ScriptCoreLib.JavaScript.Runtime.JSColor.FromRGB(0, 127, 0);
                      s.TargetOuterBorder.style.boxShadow = "rgba(0, 127, 0, 0.3) 0px 0px 6px 3px";
                  };

            //FormStyler.AtFormCreated = FormStyler.LikeWindows3;

            var SidebarIdleWidth = 32;

            var f = new Form { Text = "Sidebar" };

            GrayScaleRule.InitializeGrayScaleFor("CLRForm");
            f.GetHTMLTarget().className = "CLRForm";


            #region WhileDragging


            Action WhileDragging = null;

            WhileDragging = delegate
            {
                if (f.Left == 0)
                {
                    f.GetHTMLTarget().className = "CLRForm_nohover";
                    f.Text = "Sidebar (docked)";
                }
                else if (f.Capture)
                {
                    f.GetHTMLTarget().className = "";
                    f.Text = "Sidebar (dragging)";
                }
                else
                {
                    f.GetHTMLTarget().className = "CLRForm";
                    f.Text = "Sidebar";

                }
                Native.window.requestAnimationFrame += WhileDragging;
            };
            Native.window.requestAnimationFrame += WhileDragging;
            #endregion


            var c = new Sidebar { Dock = DockStyle.Fill }.AttachTo(f);

            f.Show();

            Action<int> SetLeftSidebarWidth =
                 w =>
                 {
                     page.SidebarContainer.style.width = w + "px";
                     page.DocumentContent.style.left = w + "px";
                 };

            Action<int> SetRightSidebarWidth =
               w =>
               {
                   page.RightSidebarContainer.style.width = w + "px";
                   page.DocumentContent.style.right = w + "px";
               };

            #region LocationChanged
            var LocationChangedDisabled = false;
            f.LocationChanged +=
                delegate
                {
                    if (LocationChangedDisabled)
                        return;

                    if (f.Left == 0)
                        return;

                    if (f.Right == Native.window.Width)
                        return;

                    SetLeftSidebarWidth(SidebarIdleWidth);
                    SetRightSidebarWidth(SidebarIdleWidth);

                    if (f.Left < SidebarIdleWidth && c.checkBox1.Checked)
                        page.SidebarContainer.style.backgroundColor = JSColor.Blue;
                    else
                        page.SidebarContainer.style.backgroundColor = JSColor.Gray;

                    if (f.Right > Native.window.Width - SidebarIdleWidth && c.checkBox2.Checked)
                        page.RightSidebarContainer.style.backgroundColor = JSColor.Blue;
                    else
                        page.RightSidebarContainer.style.backgroundColor = JSColor.Gray;
                };
            #endregion



            #region Capture
            var tt = new ScriptCoreLib.JavaScript.Runtime.Timer();

            Action AtCapture = null;

            tt.Tick +=
                delegate
                {
                    if (LocationChangedDisabled)
                        return;

                    if (f.Left == 0)
                        return;

                    if (f.Right == Native.window.Width)
                        return;

                    if (f.Capture)
                    {
                        if (AtCapture != null)
                            AtCapture();

                        return;
                    }


                    if (f.Left < SidebarIdleWidth)
                    {
                        if (c.checkBox1.Checked)
                        {
                            var fs = f.Size;

                            SetLeftSidebarWidth(f.ClientSize.Width);
                            f.MoveTo(0, 0);
                            f.SizeTo(f.ClientSize.Width, page.SidebarContainer.clientHeight);
                            f.MinimumSize = new System.Drawing.Size(SidebarIdleWidth, Native.window.Height);
                            f.MaximumSize = new System.Drawing.Size(Native.window.Width - page.RightSidebarContainer.clientWidth, Native.window.Height);


                            var done = false;
                            Action<IEvent> onresize =
                                delegate
                                {
                                    if (done)
                                        return;
                                    f.SizeTo(f.ClientSize.Width, page.SidebarContainer.clientHeight);
                                    f.MinimumSize = new System.Drawing.Size(SidebarIdleWidth, Native.window.Height);
                                    f.MaximumSize = new System.Drawing.Size(Native.window.Width - page.RightSidebarContainer.clientWidth, Native.window.Height);


                                };

                            Native.window.onresize += onresize;

                            AtCapture = delegate
                            {
                                done = true;

                                AtCapture = null;
                                f.MinimumSize = new System.Drawing.Size(100, 100);
                                f.SizeTo(fs.Width, fs.Height);
                            };
                        }
                    }
                    else if (f.Right > (Native.window.Width - SidebarIdleWidth))
                    {
                        if (c.checkBox2.Checked)
                        {

                            var fs = f.Size;

                            SetRightSidebarWidth(f.ClientSize.Width);
                            f.MoveTo(page.RightSidebarContainer.offsetLeft, 0);
                            f.SizeTo(f.ClientSize.Width, page.RightSidebarContainer.clientHeight);
                            f.MinimumSize = new System.Drawing.Size(SidebarIdleWidth, Native.window.Height);
                            f.MaximumSize = new System.Drawing.Size(Native.window.Width, Native.window.Height);

                            var done = false;
                            Action<IEvent> onresize =
                                delegate
                                {
                                    if (done)
                                        return;

                                    f.MoveTo(page.RightSidebarContainer.offsetLeft, 0);
                                    f.SizeTo(f.ClientSize.Width, page.RightSidebarContainer.clientHeight);
                                    f.MinimumSize = new System.Drawing.Size(SidebarIdleWidth, Native.window.Height);
                                    f.MaximumSize = new System.Drawing.Size(Native.window.Width, Native.window.Height);
                                };

                            Native.window.onresize += onresize;


                            AtCapture = delegate
                            {
                                done = true;
                                AtCapture = null;
                                f.MinimumSize = new System.Drawing.Size(100, 100);
                                f.SizeTo(fs.Width, fs.Height);
                            };
                        }
                    }
                };
            tt.StartInterval(100);
            #endregion

            SetLeftSidebarWidth(SidebarIdleWidth);
            SetRightSidebarWidth(SidebarIdleWidth);

            #region SizeChanged
            var PrevRight = 0;

            f.SizeChanged +=
                delegate
                {
                    if (LocationChangedDisabled)
                        return;

                    if (f.Left == 0)
                    {
                        SetLeftSidebarWidth(f.Width);
                    }
                    else
                    {
                        //if (f.Left == page.RightSidebarContainer.offsetLeft)
                        //{
                        //    LocationChangedDisabled = true;
                        //    f.Left = Native.Window.Width - f.Width;
                        //    SetRightSidebarWidth(f.Width);
                        //    LocationChangedDisabled = false;
                        //}
                    }

                    PrevRight = f.Right;
                };
            #endregion

            #region AtButton1
            Action AtButton1 =
                delegate
                {
                    c.button1.Enabled = false;
                    c.button2.Enabled = true;

                    var cl = f.Location;
                    var cs = f.ClientSize;


                    var cc = f.GetHTMLTarget();

                    var IsLeft = f.Left < (Native.window.Width - f.Width) / 2;

                    if (IsLeft)
                    {
                        f.MoveTo(0, 0);
                    }
                    else
                    {
                        f.MoveTo(page.RightSidebarContainer.offsetLeft, 0);
                    }

                    f.FormBorderStyle = FormBorderStyle.None;

                    Native.window.requestAnimationFrame +=
                        delegate
                        {
                            f.Height = Native.window.Height;
                        };

                    c.button2.Click +=
                          delegate
                          {
                              if (cc == null)
                                  return;

                              c.button1.Enabled = true;
                              c.button2.Enabled = false;

                              cc.AttachToDocument();


                              cc = null;

                              f.ClientSize = cs;
                              f.Location = cl;

                              //if (c.checkBox1.Checked)
                              f.FormBorderStyle = FormBorderStyle.Sizable;

                              SetLeftSidebarWidth(SidebarIdleWidth);
                          };

                    cc.AttachTo(page.SidebarContainer);
                };
            #endregion

            #region button1
            c.button1.Click +=
                delegate
                {
                    AtButton1();
                };
            #endregion

            c.button2.Enabled = false;

            c.button3.Click +=
                delegate
                {
                    c.checkBox1.Enabled = false;
                    c.checkBox2.Enabled = false;
                    c.button3.Enabled = false;

                    //f.PopupInsteadOfClosing(
                    //    HandleFormClosing: true
                    //);
                };

            f.FormClosing +=
                (ss, ee) =>
                {
                    if (c.button3.Enabled)
                    {
                        // not yet popup mode
                        ee.Cancel = true;
                        if (c.button1.Enabled)
                            AtButton1();

                    }

                };

            //f.FormClosed +=
            //    delegate
            //    {
            //        Native.Document.body.Clear();

            //        Native.Window.close();
            //    };


            @"Hello world".ToDocumentTitle();
            // Send data from JavaScript to the server tier
            //service.WebMethod2(
            //    @"A string from JavaScript.",
            //    value => value.ToDocumentTitle()
            //);


            //#region snippet http://my.jsc-solutions.net/#TestPackageAsApplication

            //new IHTMLAnchor { "drag me to my.jsc-solutions.net" }.AttachToDocument().With(
            //    dragme =>
            //    {
            //        dragme.style.position = IStyle.PositionEnum.@fixed;
            //        dragme.style.left = "1em";
            //        dragme.style.bottom = "1em";

            //        dragme.AllowToDragAsApplicationPackage();
            //    }
            //);

            //#endregion

        }
        public ApplicationWebServiceWithReplay()
        {
            var sync = new Timer(
                delegate
                {
                    // in every 500ms we get to do stuff.

                    if (CurrentPending == null)
                    {
                        // there is nothing pending just yet.
                        // do we have work?

                        if (actions.Count > 0)
                        {
                            var next = actions.Peek();

                            // alright, we know what to do
                            // start our timeout

                            var timeout = new Stopwatch();

                            timeout.Start();

                            CurrentPending = timeout;

                            Console.WriteLine("start task " + new { actions.Count });


                            // .net does not need this?
                            if (!ServicePending.IsRunning)
                                ServicePending.Start();


                            if (AtPendingActions != null)
                                AtPendingActions(actions.Count);

                            next(
                                delegate
                                {
                                    if (CurrentPending == timeout)
                                    {
                                        // we have been expecting you..

                                        Console.WriteLine("task complete " + new { timeout.ElapsedMilliseconds, actions.Count });

                                        CurrentPending = null;
                                        actions.Dequeue();

                                        if (actions.Count == 0)
                                        {
                                            ServicePending = new Stopwatch();
                                            //ServicePending.Reset();
                                        }

                                        if (AtPendingActions != null)
                                            AtPendingActions(actions.Count);

                                    }
                                }
                            );
                        }

                    }
                    else
                    {
                        // there is something pending

                        // lag 4000 and we will need to retry
                        if (CurrentPending.ElapsedMilliseconds > 4000)
                        {
                            Console.WriteLine("task abort  " + new { actions.Count });
                            CurrentPending = null;



                        }

                        if (AtPendingActions != null)
                            AtPendingActions(actions.Count);
                    }


                }
            );

            sync.StartInterval(500);
        }
示例#16
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(IApp page)
        {
            DiagnosticsConsole.ApplicationContent.BindKeyboardToDiagnosticsConsole();

            FormStyler.AtFormCreated =
                s =>
            {
                FormStyler.LikeVisualStudioMetro(s);

                s.TargetOuterBorder.style.borderColor = ScriptCoreLib.JavaScript.Runtime.JSColor.FromRGB(0, 127, 0);
                s.Caption.style.backgroundColor       = ScriptCoreLib.JavaScript.Runtime.JSColor.FromRGB(0, 127, 0);
                s.TargetOuterBorder.style.boxShadow   = "rgba(0, 127, 0, 0.3) 0px 0px 6px 3px";
            };

            //FormStyler.AtFormCreated = FormStyler.LikeWindows3;

            var SidebarIdleWidth = 32;

            var f = new Form {
                Text = "Sidebar"
            };

            GrayScaleRule.InitializeGrayScaleFor("CLRForm");
            f.GetHTMLTarget().className = "CLRForm";


            #region WhileDragging


            Action WhileDragging = null;

            WhileDragging = delegate
            {
                if (f.Left == 0)
                {
                    f.GetHTMLTarget().className = "CLRForm_nohover";
                    f.Text = "Sidebar (docked)";
                }
                else if (f.Capture)
                {
                    f.GetHTMLTarget().className = "";
                    f.Text = "Sidebar (dragging)";
                }
                else
                {
                    f.GetHTMLTarget().className = "CLRForm";
                    f.Text = "Sidebar";
                }
                Native.window.requestAnimationFrame += WhileDragging;
            };
            Native.window.requestAnimationFrame += WhileDragging;
            #endregion


            var c = new Sidebar {
                Dock = DockStyle.Fill
            }.AttachTo(f);

            f.Show();

            Action <int> SetLeftSidebarWidth  =
                w =>
            {
                page.SidebarContainer.style.width = w + "px";
                page.DocumentContent.style.left   = w + "px";
            };

            Action <int> SetRightSidebarWidth =
                w =>
            {
                page.RightSidebarContainer.style.width = w + "px";
                page.DocumentContent.style.right       = w + "px";
            };

            #region LocationChanged
            var LocationChangedDisabled       = false;
            f.LocationChanged +=
                delegate
            {
                if (LocationChangedDisabled)
                {
                    return;
                }

                if (f.Left == 0)
                {
                    return;
                }

                if (f.Right == Native.window.Width)
                {
                    return;
                }

                SetLeftSidebarWidth(SidebarIdleWidth);
                SetRightSidebarWidth(SidebarIdleWidth);

                if (f.Left < SidebarIdleWidth && c.checkBox1.Checked)
                {
                    page.SidebarContainer.style.backgroundColor = JSColor.Blue;
                }
                else
                {
                    page.SidebarContainer.style.backgroundColor = JSColor.Gray;
                }

                if (f.Right > Native.window.Width - SidebarIdleWidth && c.checkBox2.Checked)
                {
                    page.RightSidebarContainer.style.backgroundColor = JSColor.Blue;
                }
                else
                {
                    page.RightSidebarContainer.style.backgroundColor = JSColor.Gray;
                }
            };
            #endregion



            #region Capture
            var tt = new ScriptCoreLib.JavaScript.Runtime.Timer();

            Action AtCapture = null;

            tt.Tick +=
                delegate
            {
                if (LocationChangedDisabled)
                {
                    return;
                }

                if (f.Left == 0)
                {
                    return;
                }

                if (f.Right == Native.window.Width)
                {
                    return;
                }

                if (f.Capture)
                {
                    if (AtCapture != null)
                    {
                        AtCapture();
                    }

                    return;
                }


                if (f.Left < SidebarIdleWidth)
                {
                    if (c.checkBox1.Checked)
                    {
                        var fs = f.Size;

                        SetLeftSidebarWidth(f.ClientSize.Width);
                        f.MoveTo(0, 0);
                        f.SizeTo(f.ClientSize.Width, page.SidebarContainer.clientHeight);
                        f.MinimumSize = new System.Drawing.Size(SidebarIdleWidth, Native.window.Height);
                        f.MaximumSize = new System.Drawing.Size(Native.window.Width - page.RightSidebarContainer.clientWidth, Native.window.Height);


                        var             done     = false;
                        Action <IEvent> onresize =
                            delegate
                        {
                            if (done)
                            {
                                return;
                            }
                            f.SizeTo(f.ClientSize.Width, page.SidebarContainer.clientHeight);
                            f.MinimumSize = new System.Drawing.Size(SidebarIdleWidth, Native.window.Height);
                            f.MaximumSize = new System.Drawing.Size(Native.window.Width - page.RightSidebarContainer.clientWidth, Native.window.Height);
                        };

                        Native.window.onresize += onresize;

                        AtCapture = delegate
                        {
                            done = true;

                            AtCapture     = null;
                            f.MinimumSize = new System.Drawing.Size(100, 100);
                            f.SizeTo(fs.Width, fs.Height);
                        };
                    }
                }
                else if (f.Right > (Native.window.Width - SidebarIdleWidth))
                {
                    if (c.checkBox2.Checked)
                    {
                        var fs = f.Size;

                        SetRightSidebarWidth(f.ClientSize.Width);
                        f.MoveTo(page.RightSidebarContainer.offsetLeft, 0);
                        f.SizeTo(f.ClientSize.Width, page.RightSidebarContainer.clientHeight);
                        f.MinimumSize = new System.Drawing.Size(SidebarIdleWidth, Native.window.Height);
                        f.MaximumSize = new System.Drawing.Size(Native.window.Width, Native.window.Height);

                        var             done     = false;
                        Action <IEvent> onresize =
                            delegate
                        {
                            if (done)
                            {
                                return;
                            }

                            f.MoveTo(page.RightSidebarContainer.offsetLeft, 0);
                            f.SizeTo(f.ClientSize.Width, page.RightSidebarContainer.clientHeight);
                            f.MinimumSize = new System.Drawing.Size(SidebarIdleWidth, Native.window.Height);
                            f.MaximumSize = new System.Drawing.Size(Native.window.Width, Native.window.Height);
                        };

                        Native.window.onresize += onresize;


                        AtCapture = delegate
                        {
                            done          = true;
                            AtCapture     = null;
                            f.MinimumSize = new System.Drawing.Size(100, 100);
                            f.SizeTo(fs.Width, fs.Height);
                        };
                    }
                }
            };
            tt.StartInterval(100);
            #endregion

            SetLeftSidebarWidth(SidebarIdleWidth);
            SetRightSidebarWidth(SidebarIdleWidth);

            #region SizeChanged
            var PrevRight = 0;

            f.SizeChanged +=
                delegate
            {
                if (LocationChangedDisabled)
                {
                    return;
                }

                if (f.Left == 0)
                {
                    SetLeftSidebarWidth(f.Width);
                }
                else
                {
                    //if (f.Left == page.RightSidebarContainer.offsetLeft)
                    //{
                    //    LocationChangedDisabled = true;
                    //    f.Left = Native.Window.Width - f.Width;
                    //    SetRightSidebarWidth(f.Width);
                    //    LocationChangedDisabled = false;
                    //}
                }

                PrevRight = f.Right;
            };
            #endregion

            #region AtButton1
            Action AtButton1 =
                delegate
            {
                c.button1.Enabled = false;
                c.button2.Enabled = true;

                var cl = f.Location;
                var cs = f.ClientSize;


                var cc = f.GetHTMLTarget();

                var IsLeft = f.Left < (Native.window.Width - f.Width) / 2;

                if (IsLeft)
                {
                    f.MoveTo(0, 0);
                }
                else
                {
                    f.MoveTo(page.RightSidebarContainer.offsetLeft, 0);
                }

                f.FormBorderStyle = FormBorderStyle.None;

                Native.window.requestAnimationFrame +=
                    delegate
                {
                    f.Height = Native.window.Height;
                };

                c.button2.Click +=
                    delegate
                {
                    if (cc == null)
                    {
                        return;
                    }

                    c.button1.Enabled = true;
                    c.button2.Enabled = false;

                    cc.AttachToDocument();


                    cc = null;

                    f.ClientSize = cs;
                    f.Location   = cl;

                    //if (c.checkBox1.Checked)
                    f.FormBorderStyle = FormBorderStyle.Sizable;

                    SetLeftSidebarWidth(SidebarIdleWidth);
                };

                cc.AttachTo(page.SidebarContainer);
            };
            #endregion

            #region button1
            c.button1.Click +=
                delegate
            {
                AtButton1();
            };
            #endregion

            c.button2.Enabled = false;

            c.button3.Click +=
                delegate
            {
                c.checkBox1.Enabled = false;
                c.checkBox2.Enabled = false;
                c.button3.Enabled   = false;

                //f.PopupInsteadOfClosing(
                //    HandleFormClosing: true
                //);
            };

            f.FormClosing +=
                (ss, ee) =>
            {
                if (c.button3.Enabled)
                {
                    // not yet popup mode
                    ee.Cancel = true;
                    if (c.button1.Enabled)
                    {
                        AtButton1();
                    }
                }
            };

            //f.FormClosed +=
            //    delegate
            //    {
            //        Native.Document.body.Clear();

            //        Native.Window.close();
            //    };


            @"Hello world".ToDocumentTitle();
            // Send data from JavaScript to the server tier
            //service.WebMethod2(
            //    @"A string from JavaScript.",
            //    value => value.ToDocumentTitle()
            //);


            //#region snippet http://my.jsc-solutions.net/#TestPackageAsApplication

            //new IHTMLAnchor { "drag me to my.jsc-solutions.net" }.AttachToDocument().With(
            //    dragme =>
            //    {
            //        dragme.style.position = IStyle.PositionEnum.@fixed;
            //        dragme.style.left = "1em";
            //        dragme.style.bottom = "1em";

            //        dragme.AllowToDragAsApplicationPackage();
            //    }
            //);

            //#endregion
        }
示例#17
0
			private static void Tick(IHTMLApplet a, Action value, Timer t)
			{
				// http://www.rgagnon.com/javadetails/java-0176.html

				// in IE: isActive returns an error if the applet IS loaded, 
				// false if not loaded
				// in NS: isActive returns true if loaded, an error if not loaded, 

				var ie = (bool)new IFunction(
					"/*@cc_on return true; @*/ return false;"
				).apply(null);

				var r = false;

				try
				{
					r = a.isActive();
				}
				catch
				{
					r = ie;
				}

				if (r)
				{
					t.Stop();

					if (value != null)
						value();

					// note: this actually works! :)
					//Native.Window.alert("onload!");
				}
			}
示例#18
0
            void t_Tick(Timer e)
            {
                if (bAnimate)
                {
                    x--;


                    if (x < xto)
                        bAnimate = false;
                    else
                        this.MoveShip();

                }
            }
示例#19
0
        private void Setup(System.Action done)
        {
            t = new Timer();

            var text = new IHTMLInput(HTMLInputTypeEnum.text);

            text.className = "TalkToOthers";

            text.AttachToDocument();

            text.onkeypress += delegate(IEvent x)
            {
                if (x.IsReturn)
                {
                    this.CurrentSession.IServer_TalkToOthers(text.value);
                    this.DisplayNotification(text.value, Color.Blue);

                    text.value = "";
                }
            };

            text.style.zIndex = 1000;

            //Native.Document.body.DisableContextMenu();

            //CreateRotatingTank(96 + 48 * 7, 96 + 48 * 1, t, "tree_1", 383, 392);
            //CreateRotatingTank(96 + 48 * 1, 96 + 48 * 2, t, "tank_1", 308, 339);

            int u = 7;
            System.Action idone = null;

            System.Action<System.Action> adone = delegate(System.Action x)
            {
                if (x != null)
                    idone += x;
                u--;

                if (u == 0)
                {
                    if (idone != null)
                    {
                        idone();
                        idone = null;
                    }

                    //done();

                    //t.StartInterval(100);
                }
            };

            done();
            t.StartInterval(100);

            UnitCache.Of("harvester_1", 71, 71 + 31, 48, 48,
                delegate(UnitCache c)
                {
                    adone(delegate
                    {
                        for (int i = 1; i < 10; i++)
                        {
                            Unit.Of(c, 32 * 7, 24 * i, t, 5);
                        }
                    });
                }
            );


            building_1 = UnitCache.Of("building_1", 365, 365 + 17, 72, 72,
                delegate(UnitCache c)
                {

                    adone(delegate
                    {
                        for (int i = 1; i < 5; i++)
                        {
                            var xu = Unit.Of(c, 32 * 14, 72 * i, t, 2);

                            System.Action To3 = null;
                            System.Action To4 = null;
                            System.Action To1r = null;
                            System.Action To1 = null;

                            To3 = delegate
                            {

                                xu.Cache = building_3;
                                xu.WhenDone = To4;

                            };


                            To1r = delegate
                            {
                                xu.ReverseAnimation = true;
                                xu.Cache = building_1;
                                xu.WhenDone = To1;

                            };

                            To1 = delegate
                           {
                               xu.ReverseAnimation = false;
                               xu.Cache = building_1;
                               xu.WhenDone = To3;

                           };


                            To4 = delegate
                               {
                                   xu.Cache = building_4;
                                   xu.WhenDone = To1r;

                               };

                            xu.WhenDone = To3;
                        }
                    });
                }
            );

            UnitCache.Of("building_2", 1252, 1252 + 15, 48, 48,
                delegate(UnitCache c)
                {
                    adone(delegate
                    {
                        for (int i = 1; i < 10; i++)
                        {
                            Unit.Of(c, 32 * 17, 48 * i, t, 6);

                        }
                    });
                }
            );

            building_4 = UnitCache.Of("building_4", 405, 405 + 17, 72, 72, uc => adone(null));

            building_3 = UnitCache.Of("building_3", 393, 393 + 11, 72, 72, uc => adone(null));

            UnitCache.Of("tank_2", 308, 308 + 31, 24, 24,
               delegate(UnitCache c)
               {
                   adone(delegate
                   {
                       for (int i = 1; i < 10; i++)
                       {
                           Unit.Of(c, 32 * 3, 24 * i, t, 3);
                       }
                   });
               }
            );

            explosion_1 = UnitCache.Of("explosion_1", 990, 1015, 78, 121,
               delegate(UnitCache c)
               {
                   adone(delegate
                   {


                       Native.Document.body.onclick +=
                           delegate(IEvent ev)
                           {
                               int cx = ev.CursorX;
                               int cy = ev.CursorY;

                               UserCreateExplosion(cx, cy);
                           };
                   });
               }
            );

            new IHTMLImage("fx/building/power.png").InvokeOnComplete(
                delegate(IHTMLImage img)
                {
                    for (int i = 0; i < 3; i++)
                    {
                        SpawnAnimation(img, 50 + 48 * i, 200, 48, 72, 0, 23, t);

                    }


                }
            );


            new IHTMLImage("fx/building/cy.png").InvokeOnComplete(
                delegate(IHTMLImage img)
                {
                    for (int i = 0; i < 3; i++)
                    {
                        SpawnAnimation(img, 50 + 72 * i, 300, 72, 72, 0, 34, t);

                    }


                }
            );

            new IHTMLImage("fx/building/barrack.png").InvokeOnComplete(
                    delegate(IHTMLImage img)
                    {
                        for (int i = 0; i < 3; i++)
                        {
                            SpawnAnimation(img, 280 + 48 * i, 300, 48, 72, 0, 46, t);

                        }


                    }
                );


            new IHTMLImage("fx/vehicle/veh_cy.png").InvokeOnComplete(
                delegate(IHTMLImage img)
                {
                    for (int i = 0; i < 3; i++)
                    {
                        SpawnAnimation(img, 50 + 48 * i, 400, 48, 48, 0, 31, t);
                    }

                }
            );

            //.InvokeOnComplete(
            //    delegate(IHTMLImage img)
            //    {
            //        this.Explosion = img;

            //        for (int i = 0; i < 3; i++)
            //        {
            //            SpawnAnimation(img, 250 + 48 * i, 200, 78, 121, 0, 25, t);
            //        }

            //    }
            //);
        }
示例#20
0
		static public void FadeIn(this IHTMLElement target, int waittime, int fadetime, Action done)
		{
			// if IE
			var c = target.clientHeight;

			if (c < 20)
				c = 20;

			target.style.height = c + "px";

			target.style.Opacity = 0;
			target.style.display = ScriptCoreLib.JavaScript.DOM.IStyle.DisplayEnum.empty;

			waittime.AtDelay(
				delegate
				{
					Timer a = null;

					a = new Timer(
						delegate
						{

							target.style.Opacity = (a.Counter / a.TimeToLive);

							if (a.Counter == a.TimeToLive)
							{
								target.style.Opacity = 1;

								if (done != null)
									done();

							}

						}
						);


					a.StartInterval(fadetime / 25, 25);
				}
			);
		}
示例#21
0
        public Tycoon4(Action<Tycoon4> yield)
        {


            Native.Document.body.style.overflow = IStyle.OverflowEnum.hidden;
            Native.Document.body.style.color = Color.White;
            Native.Document.body.style.backgroundColor = Color.Black;

            //var info_text =
            //    ((ApplicationDescriptionAttribute)typeof(Tycoon4).GetCustomAttributes(typeof(ApplicationDescriptionAttribute), false).Single()).Description;

            var infoc = new IHTMLDiv();
            new fullbox().AttachTo(infoc);
            var info = new IHTMLCode().AttachTo(infoc);



            infoc.style.SetLocation(4, 4, Native.window.Width - 8, 0);
            infoc.style.height = "auto";
            info.style.Float = IStyle.FloatEnum.right;


            var paused = false;

            var ZeroPoint = new Point<double>();

            // http://en.wikipedia.org/wiki/Isometric_projection
            // http://en.wikipedia.org/wiki/Dimetric_projection
            // http://en.wikipedia.org/wiki/Axonometric_projection
            // http://en.wikipedia.org/wiki/First_angle_projection
            // http://en.wikipedia.org/wiki/3/4_perspective

            var RotationA = 45.ToRadians();
            var RotationB = 0.5;
            var Zoom = 1;
            var Dot = 4;

            var MapSize = new Rectangle
            {
                Left = -12,
                Width = 24,
                Top = -12,
                Height = 24
            };

            var MapMargins = new Point
            (
                4,
                4
            );

            var bg_size = new
            {
                w = (64 * Zoom).ToInt32(),
                h = (32 * Zoom).ToInt32()
            };

            Func<Point<double>> GetCenter = () => new Point<double>
            {
                X = bg_size.w * (MapSize.Width + MapMargins.X) / 2 /*Native.Window.Width / 2*/,
                Y = bg_size.h * (MapSize.Height + MapMargins.Y) / 2 /*Native.Window.Height / 2*/
            };

            var arena = new ArenaControl();

            arena.Control.AttachToDocument();

            arena.Layers.Canvas.style.backgroundColor = Color.FromRGB(0, 0, 0);

            //arena.SetCanvasViewCenter();


            arena.SetCanvasSize(new Point(
                ((MapSize.Width + +MapMargins.X) * bg_size.w).ToInt32(),
                ((MapSize.Height + +MapMargins.Y) * bg_size.h).ToInt32()
                ));

            var PauseFog = new IHTMLDiv().AttachTo(arena.Layers.Info);

            PauseFog.style.backgroundColor = Color.Black;
            PauseFog.style.Opacity = 1;

            PauseFogTween = new TweenDataDouble(
                delegate
                {
                }
            ) { Value = 1 };

            PauseFogTween.ValueChanged +=
                    () => PauseFog.style.Opacity = PauseFogTween.Value;

            #region onresize
            Action onresize =
                delegate
                {
                    infoc.style.SetLocation(4, 4, Native.window.Width - 8, 0);
                    infoc.style.height = "auto";

                    var rect = Rectangle.Of(0, 0, Native.window.Width, Native.window.Height);

                    arena.SetLocation(rect);
                    PauseFog.style.SetLocation(rect);
                };

            Native.window.onresize +=
                ev =>
                {
                    onresize();
                };

            onresize();
            #endregion

            infoc.AttachTo(arena.Layers.Info);

            #region TileResources
            var TileResources = new
                {
                    Grass = new { Source = new _0_192x95().src, Height = 32 },
                    //Rocks = new { Source = new _1().src, Height = 32 },
                    TileSelector = new { Source = new _3().src, Height = 32 },
                    RoughLand = new { Source = new _2x192x95().src, Height = 32 },
                    Dirt = new { Source = new _4_192x95().src, Height = 32 },
                    //DirtDirtGrass = new { Source = new _5().src, Height = 32 },
                    //DirtGrassGrass = new { Source = new _6().src, Height = 32 },

                    Track1 = new { Source = new r2_192x95().src, Height = 32 },

                    Road2 = new { Source = new r1_192x95().src, Height = 32 },
                    Road2_Track1 = new { Source = new r3_192x95().src, Height = 32 },
                    Road1 = new { Source = new r4_192x95().src, Height = 32 },
                    Road1_Road2 = new { Source = new r5_192x95().src, Height = 32 },

                    Tree = new { Source = new t1_192x192().src, Height = 64 },
                    Tree2 = new { Source = new t2_192x192().src, Height = 128 },

                    House1a = new { Source = new h1a_192x384().src, Height = 128 },
                    House1b = new { Source = new h1b_192x384().src, Height = 128 },
                    House1x = new { Source = new h1x_192x384().src, Height = 128 },

                    //House2 = new { Source = new h2().src, Height = 96 },
                    //House3 = new { Source = new h3().src, Height = 50 },
                    //House4 = new { Source = new h4().src, Height = 53 },
                    //House5a = new { Source = new h5a().src, Height = 33 },
                    //House5b = new { Source = new h5b().src, Height = 40 },
                    //House5c = new { Source = new h5c().src, Height = 40 },
                    //House5 = new { Source = new h5().src, Height = 40 },

                    //House11a = new { Source = new h11a().src, Height = 89 },
                    //House11b = new { Source = new h11b().src, Height = 89 },
                    //House11c = new { Source = new h11c().src, Height = 89 },
                    //House11x = new { Source = new h11x().src, Height = 89 }
                };

            var TileResourcesList = new[]
                {
                    TileResources.Grass,
                    //TileResources.Rocks,
                    TileResources.TileSelector,
                    TileResources.RoughLand ,
                    TileResources.Dirt ,
                    //TileResources.DirtDirtGrass ,
                    //TileResources.DirtGrassGrass,
                    TileResources.Track1 ,
                    TileResources.Road2 ,
                    TileResources.Road2_Track1 ,
                    TileResources.Road1 ,
                    TileResources.Road1_Road2,

                    TileResources.Tree ,
                    TileResources.Tree2 ,

                    TileResources.House1a,
                    TileResources.House1b,
                    TileResources.House1x,

                    //TileResources.House2,
                    //TileResources.House3 ,
                    //TileResources.House4 ,
                    //TileResources.House5a ,
                    //TileResources.House5b ,
                    //TileResources.House5c ,
                    //TileResources.House5 ,
                    //TileResources.House11a ,
                    //TileResources.House11b ,
                    //TileResources.House11c ,
                    //TileResources.House11x ,
                };
            #endregion

            var MyFrames_Soldier = new DudeAnimationInfo
                {
                    Frames_Stand = Frames.WolfSoldier,
                    Frames_Walk = Frames.WolfSoldier_Walk
                };

            var MyFrames_Imp = new DudeAnimationInfo
                {
                    Frames_Stand = Frames.DoomImp,
                    Frames_Walk = Frames.DoomImp_Walk
                };


            var MyFrames_TwinClone = new DudeAnimationInfo
                {
                    Frames_Stand = DoomImp,
                    Frames_Walk = DoomImp_Walk
                };



            #region Preloading
            Action AllImagesLoaded = delegate { };

            var ImagesThatAreCurrentlyLoading = new List<IHTMLImage>();
            var ImagesThatAreCurrentlyLoadingCounter = 0;

            //Action<IHTMLImage> LoadingSingleImageDone = img =>
            //{
            //    ImagesThatAreCurrentlyLoading.Remove(img);

            //    Console.WriteLine("loaded: " + img.src);

            //    if (ImagesThatAreCurrentlyLoading.Count == 0)
            //        AllImagesLoaded();
            //    else
            //        info.innerText = "Loading images... (" + ImagesThatAreCurrentlyLoading.Count + ")";
            //};


            info.innerText = "Loading images...";

            #region StartLoadingSingleImage
            Action<IHTMLImage> StartLoadingSingleImage = Image =>
                {
                    ImagesThatAreCurrentlyLoading.Add(Image);

                    Image.InvokeOnComplete(img => { ImagesThatAreCurrentlyLoadingCounter++; }, 30);
                    //LoadingSingleImageDone(Image);
                };
            #endregion

            #region StartLoadingDudeAnimationInfo
            Action<DudeAnimationInfo> StartLoadingDudeAnimationInfo =
                a =>
                {
                    a.Frames_Stand.ForEach(i => StartLoadingSingleImage(i.Image));
                    a.Frames_Walk.ForEach(j => j.ForEach(i => StartLoadingSingleImage(i.Image)));
                };
            #endregion

            var Argh = new Argh();
            var CloneAffirmative = new EN_000002();
            var Affirmative = new Affirmative();
            var click = new click();
            var Hammertime = new SAMPLES234 { volume = 0.1 };
            var Sawtime = new SAMPLES216 { volume = 0.1 };
            var StoneHammerTime = new SAMPLES233 { volume = 0.1 };


            #endregion

            #region AllImagesLoaded
            AllImagesLoaded +=
                delegate
                {
                    Console.WriteLine("AllImagesLoaded");

                    info.innerText = "Loading images... done!";

                    #region Translate
                    Func<double, double, Point<double>> Translate =
                        (_x, _y) =>
                        {
                            var _r = ZeroPoint.GetRotation(_x, _y) + RotationA;
                            var _d = ZeroPoint.GetDistance(_x, _y) * bg_size.h * 2d.Sqrt();

                            _x = Math.Cos(_r) * _d;
                            _y = Math.Sin(_r) * _d * RotationB;

                            return new Point<double> { X = _x, Y = _y };
                        };
                    #endregion

                    #region Translator
                    var Translator = new CoordTranslatorBase
                    {
                        ConvertMapToCanvas = map_coords =>
                        {
                            var canvas_coords = Translate(map_coords.X, map_coords.Y);
                            var c = GetCenter();

                            canvas_coords.X += c.X;
                            canvas_coords.Y += c.Y;

                            return canvas_coords;

                        },
                        ConvertCanvasToMap = canvas =>
                        {
                            var c = GetCenter();

                            var offset = new Point<double> { X = canvas.X - c.X, Y = (canvas.Y - c.Y) / RotationB };

                            var d = ZeroPoint.GetDistance(offset) / (bg_size.h * 2d.Sqrt());
                            var r = ZeroPoint.GetRotation(offset) - RotationA;

                            var realoffset = new Point<double>
                            {
                                X = Math.Cos(r) * d,
                                Y = Math.Sin(r) * d
                            };

                            return realoffset;
                        }
                    };
                    #endregion





                    #region ApplyPosition
                    Action<double, double, IHTMLDiv> ApplyPosition =
                        (_x, _y, _div) =>
                        {
                            try
                            {
                                var _pos = GetCenter();

                                var p = Translate(_x, _y);



                                var _dot = (Zoom * Dot).ToInt32();

                                _div.style.SetLocation(
                                    (_pos.X + p.X).ToInt32() - _dot / 2,
                                    (_pos.Y + p.Y).ToInt32() - _dot / 2,
                                    _dot,
                                    _dot
                                );

                                _div.AttachToDocument();

                                _div.onmouseover +=
                                    delegate
                                    {
                                        Native.Document.title = new { _x, _y }.ToString();

                                    };

                            }
                            catch (Exception ex)
                            {
                                ex.ToConsole();
                            }
                        };
                    #endregion


                    #region CreateDiv
                    Func<double, double, IHTMLDiv> CreateDiv =
                        (_x, _y) =>
                        {

                            var _div = new IHTMLDiv();

                            _div.style.backgroundColor = Color.Red;

                            ApplyPosition(_x, _y, _div);

                            return _div;
                        };
                    #endregion


                    var TileColor = Color.Gray;
                    var TileColor2 = Color.White;
                    var TileColorHouse1 = Color.FromRGB(41, 0, 0);
                    //var TileColorHouse2 = Color.FromRGB(42, 0, 0);
                    //var TileColorHouse3 = Color.FromRGB(43, 0, 0);
                    //var TileColorHouse11 = Color.FromRGB(44, 0, 0);

                    var TileColorTree1 = Color.FromRGB(51, 0, 0);
                    var TileColorTree2 = Color.FromRGB(52, 0, 0);
                    var TileColorTree3 = Color.FromRGB(53, 0, 0);


                    var TileColorRoad1 = Color.FromRGB(61, 0, 0);
                    var TileColorRoad2 = Color.FromRGB(62, 0, 0);
                    var TileColorRoad3 = Color.FromRGB(63, 0, 0);

                    var TileColorTrack1 = Color.FromRGB(70, 0, 0);
                    var TileColorRoadTrack1 = Color.FromRGB(71, 0, 0);


                    var data = new[] {
                        new { x = -0.5, y = -0.5, color = Color.Red },
                        new { x = 0.5, y = -0.5, color = Color.Green },
                        new { x = 0.5, y = 0.5, color = Color.Blue },
                        new { x = -0.5, y = 0.5, color = Color.Yellow },
                    };

                    #region IsDefined
                    Func<double, double, bool> IsDefined =
                        (x, y) => data.Any(
                            i =>
                            {
                                if (i.x != x) return false;
                                if (i.y != y) return false;

                                return true;
                            }
                    );
                    #endregion


                    data = data.Concat(
                        from x in Enumerable.Range(MapSize.Left, MapSize.Width + 1)
                        from y in Enumerable.Range(MapSize.Top, MapSize.Height + 1)
                        select new { x = (double)x, y = (double)y, color = TileColor }
                           ).ToArray();


                    #region CreateNewItemsRandomly
                    Action<int, Color> CreateNewItemsRandomly =
                        (x, c) =>
                            x.Times(
                                     delegate
                                     {
                                         var loc = data.Where(i => i.color == TileColor).Random();

                                         data = data.ConcatSingle(
                                                new { x = loc.x, y = loc.y, color = c }
                                         ).ToArray();
                                     }
                             );
                    #endregion


                    #region ApplyTileToCanvas
                    Action<double, double, IHTMLImage, double> ApplyTileToCanvas =
                        (x, y, bg, height) =>
                        {
                            height *= Zoom;

                            var c = GetCenter();

                            var p = Translate(x, y);

                            c.X += p.X.ToInt32(bg_size.w / 2);
                            c.Y += p.Y.ToInt32(bg_size.h / 2);

                            var _x = (c.X - bg_size.w / 2);
                            var _y = (c.Y - bg_size.h / 2 - (height - bg_size.h));



                            bg.style.SetLocation(
                                _x.ToInt32(),
                                _y.ToInt32(),
                                bg_size.w, height.ToInt32()
                            );


                            if (height > bg_size.h)
                            {
                                bg.style.zIndex = (_y + height - bg_size.h / 2).ToInt32();
                            }
                            else
                            {
                                bg.style.zIndex = (_y).ToInt32();
                            }
                        };
                    #endregion

                    // http://wiki.openttd.org/index.php/Enhanced_GFX_replacement

                    var KnownTileElements = new List<TileElement>();
                    var KnownDirtTileElements = new List<TileElement>();

                    #region SpawnItems
                    Action<Color, Func<string>, double> SpawnItems =
                        (c, src, h) =>
                        {
                            var tiles_query =
                                 from point in data
                                 where point.color == c
                                 let img = new IHTMLImage(src())
                                 let update = (Action)(() => ApplyTileToCanvas(point.x, point.y, img, h))
                                 let img2 = img.Aggregate(
                                    i =>
                                    {
                                        update();
                                    }).AttachTo(arena.Layers.Canvas)
                                 select
                                    new TileElement
                                    {
                                        Position = new Point<double> { X = point.x, Y = point.y },
                                        Image = img,
                                        Source = src()
                                        //, update 
                                    };

                            var aa0 = tiles_query.ToArray();
                            var aa1 = aa0;
                            var aa2 = aa1;
                            KnownTileElements.AddRange(aa2);//.ForEach(i => i.update());
                        };
                    #endregion


                    CreateNewItemsRandomly(12, TileColorHouse1);
                    //CreateNewItemsRandomly(4, TileColorHouse2);
                    //CreateNewItemsRandomly(5, TileColorHouse3);
                    //CreateNewItemsRandomly(5, TileColorHouse11);
                    CreateNewItemsRandomly(20, TileColorTree1);
                    CreateNewItemsRandomly(10, TileColorTree2);
                    CreateNewItemsRandomly(5, TileColorTree3);

                    CreateNewItemsRandomly(2, TileColorRoad1);
                    CreateNewItemsRandomly(1, TileColorRoad2);

                    CreateNewItemsRandomly(1, TileColorTrack1);

                    // expand the random roads through the map
                    #region expand



                    data.Where(i => i.color == TileColorRoad1).ToArray().ForEach(
                        road =>
                        {
                            data = data.Concat(
                                    from y in Enumerable.Range(MapSize.Top, MapSize.Height + 1)
                                    select new { x = road.x, y = (double)y, color = TileColorRoad1 }
                            ).ToArray();
                        }
                    );

                    data.Where(i => i.color == TileColorRoad2).ToArray().ForEach(
                        road =>
                        {
                            data = data.Concat(
                                    from x in Enumerable.Range(MapSize.Left, MapSize.Width + 1)
                                    select new { x = (double)x, y = road.y, color = TileColorRoad2 }
                            ).ToArray();
                        }
                    );

                    data.Where(i => i.color == TileColorTrack1).ToArray().ForEach(
                       road =>
                       {
                           data = data.Concat(
                                   from x in Enumerable.Range(MapSize.Left, MapSize.Width + 1)
                                   select new { x = (double)x, y = road.y, color = TileColorTrack1 }
                           ).ToArray();
                       }
                   );

                    #endregion

                    // remove buildings on the roads
                    #region clean road1
                    {
                        var AllRoads = data.Where(i => i.color == TileColorRoad1).ToArray();

                        data = data.Where(
                            v =>
                            {
                                if (v.color == TileColor)
                                    return true;

                                if (v.color == TileColorRoad1)
                                    return true;

                                if (v.color == TileColorRoad2)
                                    return true;

                                if (v.color == TileColorTrack1)
                                    return true;

                                return !AllRoads.Any(i => i.x == v.x && i.y == i.y);
                            }
                        ).ToArray();
                    }

                    {

                        var query = from a in data
                                    where a.color == TileColorRoad1
                                    let b = data.FirstOrDefault(i =>
                                        {
                                            var SameColor = i.color == TileColorRoad2;
                                            var SameLocation = i.x == a.x && i.y == a.y;

                                            return SameColor && SameLocation;
                                        })
                                    where b != null
                                    let c = new { a.x, a.y, color = TileColorRoad3 }
                                    select new { a, b, c };

                        foreach (var v in query)
                        {

                            var data0 = data.Where(i =>
                                    {
                                        if (i == v.a) return false;
                                        if (i == v.b) return false;

                                        return true;
                                    });

                            data = data0.ConcatSingle(v.c)
                                .ToArray();


                        }
                    }

                    {

                        var query = from a in data
                                    where a.color == TileColorRoad1
                                    let b = data.FirstOrDefault(i =>
                                    {
                                        var SameColor = i.color == TileColorTrack1;
                                        var SameLocation = i.x == a.x && i.y == a.y;

                                        return SameColor && SameLocation;
                                    })
                                    where b != null
                                    let c = new { a.x, a.y, color = TileColorRoadTrack1 }
                                    select new { a, b, c };

                        foreach (var v in query)
                        {

                            var data0 = data.Where(i =>
                            {
                                if (i == v.a) return false;
                                if (i == v.b) return false;

                                return true;
                            });

                            data = data0.ConcatSingle(v.c)
                                .ToArray();


                        }
                    }


                    {
                        var AllRoads = data.Where(i => i.color == TileColorRoad2).ToArray();

                        data = data.Where(
                            v =>
                            {
                                if (v.color == TileColor)
                                    return true;

                                if (v.color == TileColorRoad1)
                                    return true;

                                if (v.color == TileColorRoad2)
                                    return true;

                                return !AllRoads.Any(i => i.x == v.x && i.y == v.y);
                            }
                        ).ToArray();
                    }
                    #endregion



                    info.innerText = "Loading items...";

                    Timer.DoAsync(
                        delegate
                        {
                            SpawnItems(TileColor,
                                () =>
                                {
                                    //if (0.05.ByChance()) return new _1().src;
                                    if (0.33.ByChance()) return new _2x192x95().src;

                                    return new _0_192x95().src;
                                }, 32);

                            SpawnItems(TileColorRoad1, () => new r1_192x95().src, 32);
                            SpawnItems(TileColorRoad2, () => new r4_192x95().src, 32);
                            SpawnItems(TileColorRoad3, () => new r5_192x95().src, 32);

                            SpawnItems(TileColorTrack1, () => new r2_192x95().src, 32);
                            SpawnItems(TileColorRoadTrack1, () => new r3_192x95().src, 32);

                            SpawnItems(TileColorHouse1, () => new h1x_192x384().src, 128);
                            //SpawnItems(TileColorHouse11, () => new h11x().src, 89);
                            //SpawnItems(TileColorHouse2, () => new h2().src, 96);
                            //SpawnItems(TileColorHouse3, () => new h3().src, 50);

                            SpawnItems(TileColorTree1, () => new t1_192x192().src, 65);
                            SpawnItems(TileColorTree2, () => new t2_192x192().src, 128);
                            SpawnItems(TileColorTree3, () => new t3_192x192().src, 128);





                            Func<bool> IsDoneRotatingA = () => RotationA.ToDegrees() == 45;


                            #region SpawnLookingDude
                            Func<FrameInfo[], int, int, Dude2> SpawnLookingDude =
                                       (f, x, y) =>
                                       {
                                           var r = new Dude2
                                           {
                                               Frames = f,
                                           };

                                           r.AnimationInfo.Frames_Stand = f;

                                           r.Zoom.DynamicZoomFunc = a => 1;
                                           r.Zoom.StaticZoom = 1;

                                           r.SetSize(48, 72);
                                           r.TeleportTo(x, y);


                                           r.Control.AttachTo(arena.Layers.Canvas);

                                           r.Direction = Math.PI.Random() * 2;

                                           return r;
                                       };
                            #endregion








                            var Dudes = new List<Dude2>();
                            var RoadVehicles = new List<Dude2>();


                            #region GetRandomCanvasPosition
                            Func<Point> GetRandomCanvasPosition =
                                () =>
                                {
                                    var x = (MapSize.Width - 1).Random() + MapSize.Left + 1;
                                    var y = (MapSize.Height - 1).Random() + MapSize.Top + 1;


                                    var target = Translate(
                                        x, y
                                    );

                                    var c = GetCenter();

                                    var p = new Point(
                                        (target.X + c.X).ToInt32(),
                                        (target.Y + c.Y).ToInt32()
                                    );

                                    return p;
                                }
                            ;
                            #endregion


                            #region CreateDude
                            Func<DudeAnimationInfo, IdleBehaviour, double, Dude2> CreateDude =
                                (ani, idle, dudezoom) =>
                                {
                                    var w2c = GetRandomCanvasPosition();
                                    var w2 = SpawnLookingDude(ani.Frames_Stand, w2c.X.ToInt32(), w2c.Y.ToInt32());
                                    w2.Zoom.StaticZoom = dudezoom;
                                    w2.AnimationInfo.Frames_Walk = ani.Frames_Walk;
                                    w2.TargetLocationDistanceMultiplier = 1;

                                    Action<Action> GoSomeWhere =
                                        done =>
                                        {
                                            w2.DoneWalkingOnce += done;
                                            w2.WalkTo(GetRandomCanvasPosition().ToDouble());
                                        };

                                    #region WaitSomeAndGoSomeWhere
                                    Action WaitSomeAndGoSomeWhere = null;

                                    WaitSomeAndGoSomeWhere =
                                        () => 5000.Random().AtTimeout(
                                            t =>
                                            {
                                                if (paused)
                                                {
                                                    WaitSomeAndGoSomeWhere();
                                                    return;
                                                }

                                                var CurrentlyWalking = Dudes.Count(i => i.IsWalking);

                                                if (w2.IsWalking)
                                                {
                                                    WaitSomeAndGoSomeWhere();
                                                    return;
                                                }

                                                // if we've been selected, then wait for orders
                                                if (w2.IsSelected)
                                                {
                                                    WaitSomeAndGoSomeWhere();
                                                    return;
                                                }

                                                if (w2.IsHot)
                                                {
                                                    WaitSomeAndGoSomeWhere();
                                                    return;
                                                }

                                                // dont make them all walk at the same time
                                                if (CurrentlyWalking > 3)
                                                {
                                                    w2.Direction = (Math.PI * 2).Random();

                                                    WaitSomeAndGoSomeWhere();
                                                    return;
                                                }


                                                if (idle == IdleBehaviour.Scout)
                                                    GoSomeWhere(WaitSomeAndGoSomeWhere);
                                                else
                                                    WaitSomeAndGoSomeWhere();
                                            }
                                        );

                                    // make only imps wander on their own
                                    if (idle != IdleBehaviour.None)
                                        WaitSomeAndGoSomeWhere();
                                    #endregion

                                    return w2;
                                };
                            #endregion



                            info.innerHTML = "Creating dudes...";

                            1.Times(() => Dudes.Add(CreateDude(MyFrames_Soldier, IdleBehaviour.Look, 0.5)));
                            4.Times(() => Dudes.Add(CreateDude(MyFrames_Soldier, IdleBehaviour.Scout, 0.5)));

                            1.Times(() => Dudes.Add(CreateDude(MyFrames_Imp, IdleBehaviour.Look, 0.5)));
                            4.Times(() => Dudes.Add(CreateDude(MyFrames_Imp, IdleBehaviour.Scout, 0.5)));

                            1.Times(() => Dudes.Add(CreateDude(MyFrames_TwinClone, IdleBehaviour.Look, 0.5)));
                            4.Times(() => Dudes.Add(CreateDude(MyFrames_TwinClone, IdleBehaviour.Scout, 0.5)));








                            Func<Point, Point<double>> GetNearestMapPosition =
             p => Translator.ConvertCanvasToMap(p.ToDouble()).Round().BoundTo(MapSize);

                            #region GetNearestMapRect
                            Func<Rectangle, Rectangle> GetNearestMapRect =
                                rect =>
                                {
                                    var from = GetNearestMapPosition(new Point(rect.Left, rect.Top));
                                    var to = GetNearestMapPosition(new Point(rect.Right, rect.Bottom));

                                    return new Rectangle
                                    {
                                        Left = from.X.ToInt32(),
                                        Top = from.Y.ToInt32(),
                                        Right = to.X.ToInt32(),
                                        Bottom = to.Y.ToInt32()
                                    };
                                };
                            #endregion

                            #region GetTileElementsAt
                            Func<Point<double>, IEnumerable<TileElement>> GetTileElementsAt =
                                map_coords =>
                                    from i in KnownTileElements
                                    where i != null
                                    where i.Position.X == map_coords.X && i.Position.Y == map_coords.Y
                                    select i;
                            #endregion



                            #region AddTileElement
                            Func<Point<double>, string, int, TileElement> AddTileElement =
                                (map_coords, source, height) =>
                                {
                                    var n = new TileElement
                                    {
                                        Position = map_coords,
                                        Image = new IHTMLImage(source),
                                        Source = source,
                                        Height = height
                                    };


                                    KnownTileElements.Add(n);
                                    ApplyTileToCanvas(map_coords.X, map_coords.Y, n.Image, height);
                                    n.Image.AttachTo(arena.Layers.Canvas);



                                    return n;
                                };
                            #endregion

                            #region RemoveAllTilesAt
                            Action<Point<double>> RemoveAllTilesAt =
                                map_coords =>
                                {
                                    foreach (var t in GetTileElementsAt(map_coords).ToArray())
                                    {
                                        t.Image.Orphanize();

                                        t.RemoveFrom(KnownTileElements);
                                        t.RemoveFrom(KnownDirtTileElements);



                                    }
                                };
                            #endregion


                            #region ReplaceTileWithDirt
                            Func<Point<double>, TileElement> ReplaceTileWithDirt =
                                map_coords =>
                                {
                                    RemoveAllTilesAt(map_coords);

                                    var r = AddTileElement(map_coords, TileResources.Dirt.Source, TileResources.Dirt.Height);

                                    r.AddTo(KnownDirtTileElements);

                                    return r;

                                };
                            #endregion

                            #region ReplaceTileWithNewBuilding
                            Func<Point<double>, TileElement> ReplaceTileWithNewBuilding =
                                map_coords =>
                                {
                                    var n = ReplaceTileWithDirt(map_coords);

                                    n.DirtAge = -200 - (3 + 5.Random());

                                    return n;
                                };
                            #endregion


                            #region interesting predicates
                            var IsGrass =
                                new[]
                                 {
                                     TileResources.Grass.Source,
                                     TileResources.Dirt.Source,
                                     //TileResources.DirtDirtGrass.Source,
                                     //TileResources.DirtGrassGrass.Source,
                                     //TileResources.Rocks.Source,
                                     TileResources.RoughLand.Source,
                                 }.ToEqualsAny();
                            var IsGrassStrict = TileResources.Grass.Source.ToEquals();
                            var IsRoad1 = TileResources.Road1.Source.ToEquals();
                            var IsRoad2 = TileResources.Road2.Source.ToEquals();
                            var IsTrack1 = TileResources.Track1.Source.ToEquals();
                            var IsTree = TileResources.Tree.Source.ToEquals();
                            var IsTileSelector = TileResources.TileSelector.Source.ToEquals();
                            #endregion



                            // create a draggable toolbar
                            #region creating the toolbar

                            var toolbar_color = Color.FromRGB(0x40, 0x40, 0x40);

                            var infotoolbar = ToolbarDialog.CreateToolbar(
                                new Point(64, 64),
                                new Point(200, 64), toolbar_color
                                );

                            var infotoolbar_content = new IHTMLDiv().AttachTo(infotoolbar.Control);

                            infotoolbar_content.style.SetLocation(2, 8, infotoolbar.Size.X - 6, infotoolbar.Size.Y - 12);
                            infotoolbar_content.SetDialogColor(infotoolbar.Color, false);
                            infotoolbar_content.onmousedown += Native.DisabledEventHandler;

                            Action<IStyle> SetInfoAnchorStyle =
                                style =>
                                {
                                    style.display = IStyle.DisplayEnum.block;
                                    style.textDecoration = "none";
                                    style.color = Color.White;
                                    style.textAlign = IStyle.TextAlignEnum.center;
                                };

                            new IHTMLAnchor("http://zproxy.wordpress.com", "zproxy.wordpress.com").AttachTo(infotoolbar_content).style.Aggregate(SetInfoAnchorStyle);
                            new IHTMLAnchor("http://jsc.sf.net", "jsc.sf.net").AttachTo(infotoolbar_content).style.Aggregate(SetInfoAnchorStyle);


                            var toolbar_size = new Point(96, 32);
                            var toolbar_pos = new Point(8, Native.window.Height - toolbar_size.Y - 8);

                            Console.WriteLine("toolbar!");
                            var toolbar = ToolbarDialog.CreateToolbar(toolbar_pos, toolbar_size, toolbar_color);

                            Native.window.onresize +=
                                delegate
                                {
                                    infotoolbar.ApplyPosition();
                                    toolbar.ApplyPosition();
                                };

                            infotoolbar.Control.Hide();
                            infotoolbar.Control.AttachToDocument();
                            toolbar.Control.AttachToDocument();

                            toolbar_btn_pause = new ToolbarButton(
                               toolbar, new btn_pause().src
                               )
                           {
                               Title = "Pause"
                           };

                            var aww = new aww();
                            var gong = new gong();

                            toolbar_btn_pause.Clicked +=
                                btn =>
                                {
                                    paused = btn.IsActivated;


                                    Dudes.ForEach(i => i.Paused = paused);
                                };

                            #region toolbar_btn_demolish
                            var toolbar_btn_demolish = new ToolbarButton(
                                toolbar, new btn_demolish().src
                            )
                            {
                                Title = "Demolish"
                            };



                            var ShowingTileSelector = default(Func<bool>);


                            #endregion


                            var toolbar_btn_track1 = new ToolbarButton(
                               toolbar, new btn_track1().src
                            ) { Title = "Build rail tracks" };

                            // var toolbar_btn_road2 = new ToolbarButton(
                            //   toolbar, new btn_road2().src
                            //) { Title = "Build road" };

                            // var toolbar_btn_road1 = new ToolbarButton(
                            //  toolbar, new btn_road1().src
                            // ) { Title = "Build road" };

                            var toolbar_btn_road1_road2 = new ToolbarButton(
                             toolbar, new btn_road1_road2().src
                            ) { Title = "Build road" };


                            /*
                            var toolbar_btn_sign = new ToolbarButton(
                               toolbar, "assets/ThreeDStuff/btn_sign.png"
                            );
                            */

                            var toolbar_btn_trees = new ToolbarButton(
                               toolbar, new btn_trees().src
                            ) { Title = "Build trees" };

                            var toolbar_btn_trees2 = new ToolbarButton(
                              toolbar, new btn_trees().src
                           ) { Title = "Build trees" };



                            var TileSelectorModes = new Dictionary<ToolbarButton, TileSelectorMode>
                            {
                                {toolbar_btn_demolish, TileSelectorMode.Rectangle},
                                {toolbar_btn_track1, TileSelectorMode.Horizontal},
                                //{toolbar_btn_road2, TileSelectorMode.Vertical},
                                //{toolbar_btn_road1, TileSelectorMode.Horizontal},
                                {toolbar_btn_road1_road2, TileSelectorMode.HorizontalOrVertical},
                                {toolbar_btn_trees, TileSelectorMode.Rectangle},
                                {toolbar_btn_trees2, TileSelectorMode.Rectangle},
                            };

                            var __before_error = "__before_error";

                            var __Keys = TileSelectorModes.Keys;
                            var __KeysArray = __Keys.ToArray();

                            var __after_error = "__after_error";


                            var toolbar_btngroup = new ToolbarButtonGroup
                            {
                                Buttons = __KeysArray
                            };




                            var toolbar_btn_city = new ToolbarButton(
                                toolbar, new btn_city().src
                            ) { Title = "Build city" };

                            var toolbar_btn_landinfo = new ToolbarButton(
                                toolbar, new btn_landinfo().src
                            ) { Title = "Show info" };

                            toolbar_btn_landinfo.Clicked +=
                                btn =>
                                {
                                    infotoolbar.Control.Show(btn.IsActivated);
                                };

                            ShowingTileSelector =
                                () => toolbar_btngroup.IsActivated;

                            var MultipleTileSelector = new List<TileElement>();


                            #region MultipleTileSelector_Clear
                            Action MultipleTileSelector_Clear =
                                delegate
                                {
                                    // framework bug: while iterating and the collection changes an exception sould be thrown
                                    foreach (var v in MultipleTileSelector.ToArray())
                                    {
                                        if (v.Image != null)
                                        {
                                            v.Image.Orphanize();
                                            v.Image = null;
                                        }

                                        v.RemoveFrom(KnownTileElements);
                                    }


                                    MultipleTileSelector.Clear();
                                };
                            #endregion

                            #region MultipleTileSelector_Add
                            Action<Point<double>> MultipleTileSelector_Add =
                                 p =>
                                 {
                                     AddTileElement(
                                         p,
                                         TileResources.TileSelector.Source,
                                         TileResources.TileSelector.Height
                                     ).AddTo(MultipleTileSelector);
                                 };
                            #endregion


                            // show tile selection
                            #region arena.MouseMove
                            arena.MouseMove +=
                               p =>
                               {
                                   if (paused)
                                       return;

                                   if (ShowingTileSelector())
                                   {
                                       if (arena.InSelectionMode)
                                           return;

                                       // get map coords from canvas coords
                                       var map_coords = GetNearestMapPosition(p);

                                       if (MultipleTileSelector.Count == 1)
                                       {
                                           var n = MultipleTileSelector.SingleOrDefault();

                                           ApplyTileToCanvas(map_coords.X, map_coords.Y, n.Image, n.Height);
                                       }
                                       else
                                       {
                                           MultipleTileSelector_Clear();
                                           MultipleTileSelector_Add(map_coords);
                                       }

                                       // must be on top of new dirt
                                       //SingleTileSelector.style.zIndex++;
                                   }
                               };
                            #endregion

                            #region GetActivatedTileSelectorMode
                            Func<TileSelectorMode> GetActivatedTileSelectorMode =
                                delegate
                                {
                                    if (toolbar_btngroup.ActivatedButton == null)
                                        return TileSelectorMode.Unknown;

                                    if (!TileSelectorModes.ContainsKey(toolbar_btngroup.ActivatedButton))
                                        return TileSelectorMode.Unknown;

                                    return TileSelectorModes[toolbar_btngroup.ActivatedButton];
                                };
                            #endregion


                            #region arena.SelectionPointsPreview - just apply the current TileSelectorMode
                            arena.SelectionPointsPreview +=
                                (from, to) =>
                                {
                                    if (paused)
                                        return;

                                    if (!ShowingTileSelector())
                                        return;

                                    //SingleTileSelector.Hide();

                                    var map_coords = new
                                        {
                                            from = GetNearestMapPosition(from),
                                            to = GetNearestMapPosition(to)
                                        };

                                    #region CurrentMode

                                    var CurrentMode = GetActivatedTileSelectorMode();

                                    if (CurrentMode == TileSelectorMode.Unknown)
                                        return;

                                    if (CurrentMode == TileSelectorMode.HorizontalOrVertical)
                                    {
                                        if ((map_coords.from.X - map_coords.to.X).Abs() > (map_coords.from.Y - map_coords.to.Y).Abs())
                                            CurrentMode = TileSelectorMode.Horizontal;
                                        else
                                            CurrentMode = TileSelectorMode.Vertical;
                                    }

                                    #endregion


                                    if (CurrentMode == TileSelectorMode.Horizontal)
                                    {
                                        MultipleTileSelector_Clear();

                                        foreach (var x in map_coords.from.X.ToInt32().RangeTo(map_coords.to.X.ToInt32()))
                                            MultipleTileSelector_Add(new Point<double> { X = x, Y = map_coords.from.Y });
                                    }


                                    if (CurrentMode == TileSelectorMode.Vertical)
                                    {
                                        MultipleTileSelector_Clear();

                                        foreach (var y in map_coords.from.Y.ToInt32().RangeTo(map_coords.to.Y.ToInt32()))
                                            MultipleTileSelector_Add(new Point<double> { X = map_coords.from.X, Y = y });
                                    }



                                    if (CurrentMode == TileSelectorMode.Rectangle)
                                    {
                                        MultipleTileSelector_Clear();

                                        foreach (var x in map_coords.from.X.ToInt32().RangeTo(map_coords.to.X.ToInt32()))
                                            foreach (var y in map_coords.from.Y.ToInt32().RangeTo(map_coords.to.Y.ToInt32()))
                                            {
                                                MultipleTileSelector_Add(new Point<double> { X = x, Y = y });
                                            }
                                    }
                                };
                            #endregion



                            #region UseCurrentToolAt
                            Action<Point<double>, TileSelectorMode> UseCurrentToolAt =
                                (map_coords, CurrentMode) =>
                                {
                                    //"UseCurrentToolAt".ToConsole();



                                    var Subject = GetTileElementsAt(map_coords).ToArray();
                                    var StatsQuery = Subject.Select(i => i.Source);


                                    if (toolbar_btn_demolish)
                                    {
                                        ReplaceTileWithDirt(map_coords);
                                    }

                                    #region toolbar_btn_trees
                                    if (toolbar_btn_trees)
                                    {
                                        Func<string, bool> IsOther = s =>
                                            !(IsGrass(s) || IsTileSelector(s));

                                        var Stats = new
                                        {
                                            GrassStrict = StatsQuery.Any(IsGrassStrict),
                                            Other = StatsQuery.Any(IsOther)
                                        };

                                        if (!Stats.Other)
                                        {
                                            if (!Stats.GrassStrict)
                                            {
                                                RemoveAllTilesAt(map_coords);
                                                AddTileElement(map_coords, TileResources.Grass.Source, TileResources.Grass.Height);
                                            }

                                            AddTileElement(map_coords, TileResources.Tree.Source, TileResources.Tree.Height);


                                        }
                                    }

                                    #endregion

                                    #region toolbar_btn_trees2
                                    if (toolbar_btn_trees2)
                                    {
                                        Func<string, bool> IsOther = s =>
                                            !(IsGrass(s) || IsTileSelector(s));

                                        var Stats = new
                                        {
                                            GrassStrict = StatsQuery.Any(IsGrassStrict),
                                            Other = StatsQuery.Any(IsOther)
                                        };

                                        if (!Stats.Other)
                                        {
                                            if (!Stats.GrassStrict)
                                            {
                                                RemoveAllTilesAt(map_coords);
                                                AddTileElement(map_coords, TileResources.Grass.Source, TileResources.Grass.Height);
                                            }

                                            AddTileElement(map_coords, TileResources.Tree2.Source, TileResources.Tree2.Height);


                                        }
                                    }

                                    #endregion

                                    #region toolbar_btn_track1
                                    if (toolbar_btn_track1)
                                    {
                                        #region Stats

                                        Func<string, bool> IsOther = s =>
                                            !(IsRoad2(s) || IsGrass(s) || IsTree(s) || IsTileSelector(s));

                                        var Stats = new
                                        {
                                            Grass = StatsQuery.Any(IsGrass),
                                            Road2 = StatsQuery.Any(IsRoad2),
                                            Other = StatsQuery.Any(IsOther)
                                        };
                                        #endregion

                                        if (!Stats.Other)
                                        {
                                            RemoveAllTilesAt(map_coords);

                                            if (!Stats.Road2)
                                                AddTileElement(map_coords, TileResources.Track1.Source, TileResources.Track1.Height);
                                            else
                                                AddTileElement(map_coords, TileResources.Road2_Track1.Source, TileResources.Road2_Track1.Height);
                                        }
                                        else
                                        {
                                            // should show that red error dialog now :)
                                            "Cannot build tracks!".ToConsole();
                                            foreach (var v in Subject)
                                            {
                                                v.Source.ToConsole();
                                            }
                                        }

                                    }

                                    #endregion

                                    bool ActiveIsRoad1 = false;
                                    bool ActiveIsRoad2 = false;

                                    if (toolbar_btn_road1_road2)
                                    {
                                        ActiveIsRoad1 = CurrentMode == TileSelectorMode.Horizontal;
                                        ActiveIsRoad2 = CurrentMode == TileSelectorMode.Vertical;
                                    }



                                    #region toolbar_btn_road1
                                    if (ActiveIsRoad1)
                                    {


                                        #region Stats

                                        Func<string, bool> IsOther = s =>
                                            !(IsRoad2(s) || IsTrack1(s) || IsGrass(s) || IsTree(s) || IsTileSelector(s));

                                        var Stats = new
                                        {
                                            Grass = StatsQuery.Any(IsGrass),
                                            Road2 = StatsQuery.Any(IsRoad2),
                                            Track1 = StatsQuery.Any(IsTrack1),
                                            Other = StatsQuery.Any(IsOther)
                                        };
                                        #endregion

                                        if (!Stats.Other)
                                        {
                                            RemoveAllTilesAt(map_coords);

                                            if (!Stats.Road2)
                                                AddTileElement(map_coords,
                                                    TileResources.Road1.Source,
                                                    TileResources.Road1.Height);
                                            else
                                                AddTileElement(map_coords, TileResources.Road1_Road2.Source, TileResources.Road1_Road2.Height);
                                        }
                                        else
                                        {
                                            // should show that red error dialog now :)
                                            "Cannot build tracks!".ToConsole();

                                        }

                                    }

                                    #endregion


                                    #region toolbar_btn_road2
                                    if (ActiveIsRoad2)
                                    {


                                        #region Stats

                                        Func<string, bool> IsOther = s =>
                                            !(IsRoad1(s) || IsTrack1(s) || IsGrass(s) || IsTree(s) || IsTileSelector(s));




                                        var Stats = new
                                        {
                                            Grass = StatsQuery.Any(IsGrass),
                                            Road1 = StatsQuery.Any(IsRoad1),
                                            Track1 = StatsQuery.Any(IsTrack1),
                                            Other = StatsQuery.Any(IsOther)
                                        };
                                        #endregion

                                        if (!Stats.Other)
                                        {
                                            RemoveAllTilesAt(map_coords);

                                            if (Stats.Road1)
                                                AddTileElement(map_coords, TileResources.Road1_Road2.Source, TileResources.Road1_Road2.Height);
                                            else if (!Stats.Track1)
                                                AddTileElement(map_coords, TileResources.Road2.Source, TileResources.Road2.Height);
                                            else
                                                AddTileElement(map_coords, TileResources.Road2_Track1.Source, TileResources.Road2_Track1.Height);
                                        }
                                        else
                                        {
                                            // should show that red error dialog now :)
                                            "Cannot build tracks!".ToConsole();

                                        }

                                    }

                                    #endregion
                                };
                            #endregion

                            #region arena.ApplyPointsSelection - using current tool
                            arena.ApplyPointsSelection +=
                                 (from, to, ev) =>
                                 {
                                     if (!ShowingTileSelector())
                                         return;

                                     if (paused)
                                         return;

                                     var map_coords = new
                                     {
                                         from = GetNearestMapPosition(from),
                                         to = GetNearestMapPosition(to)
                                     };



                                     #region CurrentMode

                                     var CurrentMode = GetActivatedTileSelectorMode();

                                     if (CurrentMode == TileSelectorMode.Unknown)
                                         return;

                                     if (CurrentMode == TileSelectorMode.HorizontalOrVertical)
                                     {
                                         if ((map_coords.from.X - map_coords.to.X).Abs() > (map_coords.from.Y - map_coords.to.Y).Abs())
                                             CurrentMode = TileSelectorMode.Horizontal;
                                         else
                                             CurrentMode = TileSelectorMode.Vertical;
                                     }

                                     #endregion

                                     Console.WriteLine("mode: " + CurrentMode);

                                     if (CurrentMode == TileSelectorMode.Vertical)
                                     {
                                         MultipleTileSelector_Clear();

                                         foreach (var y in map_coords.from.Y.ToInt32().RangeTo(map_coords.to.Y.ToInt32()))
                                         {
                                             UseCurrentToolAt(new Point<double> { X = map_coords.from.X, Y = y }, CurrentMode);

                                         }
                                     }

                                     if (CurrentMode == TileSelectorMode.Horizontal)
                                     {
                                         MultipleTileSelector_Clear();

                                         foreach (var x in map_coords.from.X.ToInt32().RangeTo(map_coords.to.X.ToInt32()))
                                             UseCurrentToolAt(new Point<double> { X = x, Y = map_coords.from.Y }, CurrentMode);
                                     }

                                     if (CurrentMode == TileSelectorMode.Rectangle)
                                     {
                                         MultipleTileSelector_Clear();

                                         foreach (var x in map_coords.from.X.ToInt32().RangeTo(map_coords.to.X.ToInt32()))
                                             foreach (var y in map_coords.from.Y.ToInt32().RangeTo(map_coords.to.Y.ToInt32()))
                                             {
                                                 UseCurrentToolAt(new Point<double> { X = x, Y = y }, CurrentMode);
                                             }
                                     }


                                     MultipleTileSelector_Clear();
                                     MultipleTileSelector_Add(map_coords.to);

                                     click.play();
                                     click = new click(); ;
                                 };
                            #endregion

                            #region arena.SelectionClick - just use the current tool
                            arena.SelectionClick +=
                             (p, ev) =>
                             {
                                 if (paused)
                                     return;

                                 if (!ShowingTileSelector())
                                     return;



                                 var map_coords = GetNearestMapPosition(p);

                                 #region CurrentMode
                                 var CurrentMode = GetActivatedTileSelectorMode();

                                 if (CurrentMode == TileSelectorMode.Unknown)
                                     return;

                                 if (CurrentMode == TileSelectorMode.HorizontalOrVertical)
                                 {
                                     var map_coords0 = Translator.ConvertCanvasToMap(p.ToDouble()).Wrap(1).Abs();

                                     if (map_coords0.X > map_coords0.Y)
                                         CurrentMode = TileSelectorMode.Horizontal;
                                     else
                                         CurrentMode = TileSelectorMode.Vertical;
                                 }
                                 #endregion


                                 UseCurrentToolAt(map_coords, CurrentMode);


                                 MultipleTileSelector_Clear();
                                 MultipleTileSelector_Add(map_coords);

                                 click.play();
                                 click = new click(); ;
                             };
                            #endregion




                            #region toolbar_btngroup.Clicked - a tool has been selected
                            toolbar_btngroup.Clicked +=
                                btn =>
                                {
                                    arena.ShowSelectionRectangle = !ShowingTileSelector();

                                    if (!ShowingTileSelector())
                                        MultipleTileSelector_Clear();
                                };
                            #endregion



                            #endregion


                            #region arena.SelectionClick - move dudes
                            arena.SelectionClick +=
                                (p, ev) =>
                                {
                                    if (paused)
                                        return;

                                    if (ShowingTileSelector())
                                        return;

                                    var selection = Dudes.Where(i => i.IsSelected).ToArray();


                                    //KnownCanvasPosition = p;

                                    var target = Translator.ConvertCanvasToMap(p.ToDouble()).BoundTo(MapSize);

                                    if (selection.Length == 0)
                                    {
                                        // single select?

                                        return;
                                    }

                                    selection.WithEach(
                                        v =>
                                        {
                                            if (v.AnimationInfo.Frames_Stand[0].Source == Frames.WolfSoldier[0].Source)
                                            {
                                                CloneAffirmative.play();
                                                CloneAffirmative = new EN_000002();
                                            }
                                            else if (v.AnimationInfo.Frames_Stand[0].Source == MyFrames_TwinClone.Frames_Stand[0].Source)
                                            {
                                                CloneAffirmative.play();
                                                CloneAffirmative = new EN_000002();
                                            }
                                            else
                                            {
                                                Argh.play();
                                                Argh = new Argh();
                                            }

                                        }
                                    );

                                    if (selection.Length == 1)
                                    {

                                        var canvas = Translator.ConvertMapToCanvas(target);

                                        //canvas.X += GetCenter().X;
                                        //canvas.Y += GetCenter().Y;

                                        //new
                                        //{
                                        //    target = new { target.X, target.Y },
                                        //    canvas = new { canvas.X, canvas.Y }
                                        //}.ToConsole(); ;

                                        selection.ForEach(i => i.WalkTo(
                                            canvas
                                            ));
                                    }
                                    else
                                    {
                                        #region Circle

                                        var center = GetCenter();


                                        #region GetRotatedTargetPoint
                                        Func<double, double, Point<double>> GetRotatedTargetPoint =
                                            (direction, distance) =>
                                                new Point<double>
                                                {
                                                    X = target.X + (Math.Cos(direction) * distance),
                                                    Y = target.Y + (Math.Sin(direction) * distance),
                                                };
                                        #endregion

                                        Func<Point<double>, Point> OffsetToCenter =
                                            mcanvas =>
                                                new Point
                                                (
                                                    (mcanvas.X + center.X).ToInt32(),
                                                    (mcanvas.Y + center.Y).ToInt32()
                                                );

                                        var dest =
                                            from index in selection.Length.ToRange()
                                            let direction = (((double)index / (selection.Length)) * (Math.PI * 2)).ToConsole()
                                            let distance = 0.5
                                            let mtarget = GetRotatedTargetPoint(direction, distance)
                                            let mcanvas = Translate(mtarget.X, mtarget.Y)

                                            select new
                                            {
                                                index,
                                                canvas = OffsetToCenter(mcanvas)
                                            };

                                        foreach (var v in dest)
                                        {
                                            selection[v.index].WalkTo(v.canvas.ToDouble());
                                        }

                                        #endregion

                                    }
                                };
                            #endregion

                            #region arena.ApplySelection
                            arena.ApplySelection +=
                                (r, ev) =>
                                {
                                    if (paused)
                                        return;

                                    if (ShowingTileSelector())
                                        return;

                                    Console.WriteLine("ApplySelection " + new { ev.shiftKey });

                                    foreach (var v in Dudes)
                                    {
                                        // chrome always reports shiftKey?

                                        //if (ev.shiftKey)
                                        //    v.IsSelected |= r.Contains(v.CurrentLocation.ToInt32());
                                        //else
                                        v.IsSelected = r.Contains(v.CurrentLocation.ToInt32());
                                    }
                                };
                            #endregion


                            #region toolbar_btn_city.Clicked
                            var toolbar_btn_city_StopTimer = default(Action);

                            toolbar_btn_city.Clicked +=
                                delegate
                                {
                                    if (toolbar_btn_city_StopTimer != null)
                                    {
                                        Console.WriteLine("stopping city building");
                                        toolbar_btn_city_StopTimer();
                                        toolbar_btn_city_StopTimer = null;

                                        return;
                                    }

                                    #region TryBuildHere
                                    Func<Point<double>, bool> TryBuildHere =
                                        n =>
                                        {
                                            if (IsDefined(n.X, n.Y))
                                                if (GetTileElementsAt(n).All(i => IsGrassStrict(i.Source)))
                                                {
                                                    new IHTMLAudio[]
                                                                {
                                                                   Hammertime,
                                                                   Sawtime,
                                                                   StoneHammerTime
                                                                }.Random().With(
                                                       snd =>
                                                       {
                                                           snd.play();

                                                           Hammertime = new SAMPLES234 { volume = 0.1 };
                                                           Sawtime = new SAMPLES216 { volume = 0.1 };
                                                           StoneHammerTime = new SAMPLES233 { volume = 0.1 };
                                                       }
                                                   );

                                                    ReplaceTileWithNewBuilding(n);


                                                    return true;
                                                }

                                            return false;
                                        };
                                    #endregion


                                    var Query = from i in KnownTileElements
                                                let Road2 = IsRoad2(i.Source)
                                                let Road1 = IsRoad1(i.Source)
                                                where Road2 || Road1
                                                select new { i, Road1, Road2 };


                                    Console.WriteLine("starting city building");
                                    toolbar_btn_city_StopTimer = new Timer(
                                        t =>
                                        {
                                            if (paused)
                                                return;

                                            var v = Query.Random();
                                            Console.WriteLine("try building city at road {0}", new { v.i.Position.X, v.i.Position.Y });



                                            if (v.Road2)
                                            {
                                                if (0.5.ByChance())
                                                    TryBuildHere(v.i.Position.Round().WithOffset(-1, 0));
                                                else
                                                    TryBuildHere(v.i.Position.Round().WithOffset(1, 0));
                                            }
                                            else
                                                if (v.Road1)
                                                {
                                                    if (0.5.ByChance())
                                                        TryBuildHere(v.i.Position.Round().WithOffset(0, -1));
                                                    else
                                                        TryBuildHere(v.i.Position.Round().WithOffset(0, 1));
                                                }

                                        },
                                        3000, 20000

                                    ).Stop;

                                    //toolbar_btn_city.RaiseClicked
                                };
                            #endregion

                            toolbar_btn_city.RaiseClicked();

                            #region grass growth
                            1500.AtInterval(
                                t =>
                                {
                                    if (paused)
                                        return;

                                    //"got dirt?".ToConsole();

                                    #region KnownDirtTileElements
                                    foreach (var v in KnownDirtTileElements.ToArray())
                                    {
                                        new { v.DirtAge, v.Position.X, v.Position.Y }.ToConsole();

                                        if (v.DirtAge > 5)
                                        {
                                            v.RemoveFrom(KnownDirtTileElements);


                                        }

                                        #region House1a building animation
                                        if (v.Source == TileResources.House1a.Source)
                                            if (v.DirtAge > 3)
                                            {
                                                new IHTMLAudio[]
                                                                {
                                                                   Hammertime,
                                                                   Sawtime,
                                                                   StoneHammerTime
                                                                }.Random().With(
                                                    snd =>
                                                    {
                                                        snd.play();

                                                        Hammertime = new SAMPLES234 { volume = 0.1 };
                                                        Sawtime = new SAMPLES216 { volume = 0.1 };
                                                        StoneHammerTime = new SAMPLES233 { volume = 0.1 };
                                                    }
                                                );

                                                RemoveAllTilesAt(v.Position);
                                                AddTileElement(v.Position,
                                                    TileResources.House1b.Source,
                                                    TileResources.House1b.Height
                                                    )
                                                    .AddTo(KnownDirtTileElements);
                                            }

                                        if (v.Source == TileResources.House1b.Source)
                                            if (v.DirtAge > 3)
                                            {
                                                new IHTMLAudio[]
                                                                {
                                                                   Hammertime,
                                                                   Sawtime,
                                                                   StoneHammerTime
                                                                }.Random().With(
                                                    snd =>
                                                    {
                                                        snd.play();

                                                        Hammertime = new SAMPLES234 { volume = 0.1 };
                                                        Sawtime = new SAMPLES216 { volume = 0.1 };
                                                        StoneHammerTime = new SAMPLES233 { volume = 0.1 };
                                                    }
                                                );

                                                RemoveAllTilesAt(v.Position);
                                                AddTileElement(v.Position,
                                                    TileResources.House1x.Source,
                                                    TileResources.House1x.Height
                                                    )
                                                    .AddTo(KnownDirtTileElements);
                                            }

                                        #endregion


                                        #region make that dirt grow into grass over time
                                        if (v.Source == TileResources.Dirt.Source)
                                        {
                                            if (v.DirtAge == -200)
                                            {
                                                RemoveAllTilesAt(v.Position);


                                                var NewHouse = new[]
                                            {
                                                TileResources.House1a,
                                                //TileResources.House2,
                                                //TileResources.House3,
                                                //TileResources.House4,
                                                //TileResources.House5a,
                                                //TileResources.House5a

                                            }.Random();

                                                AddTileElement(v.Position,
                                                    NewHouse.Source,
                                                    NewHouse.Height
                                                    )
                                                    .AddTo(KnownDirtTileElements);
                                            }

                                            if (v.DirtAge > 3)
                                            {
                                                RemoveAllTilesAt(v.Position);

                                                v.RemoveFrom(KnownDirtTileElements);

                                                AddTileElement(v.Position, TileResources.Grass.Source, TileResources.Grass.Height)
                                                    .AddTo(KnownDirtTileElements);
                                            }
                                        }


                                        #endregion

                                        v.DirtAge++;
                                    }
                                    #endregion

                                }
                            );
                            #endregion


                            // wont work correctly on IE
                            //Native.Window.onblur +=
                            //    delegate
                            //    {
                            //        if (!toolbar_btn_pause.IsActivated)
                            //            toolbar_btn_pause.RaiseClicked();
                            //    };

                            Console.WriteLine("ready!");

                            info.innerHTML = "LBA Redux";

                            if (!paused)
                                PauseFogTween.Value = 0;


                            toolbar.Buttons.WithEach(
                              btn =>
                              {
                                  btn.Clicked +=
                                      delegate
                                      {
                                          click.play();
                                          click = new click(); ;
                                      };
                              }
                              );

                            arena.Layers.User.oncontextmenu +=
                                e =>
                                {
                                    e.preventDefault();

                                };

                            yield(this);
                        });

                };
            #endregion


            StartLoadingDudeAnimationInfo(MyFrames_Soldier);
            StartLoadingDudeAnimationInfo(MyFrames_Imp);
            StartLoadingDudeAnimationInfo(MyFrames_TwinClone);

            TileResourcesList.ForEach(i => StartLoadingSingleImage(i.Source));



            new Timer(
                t =>
                {
                    info.innerHTML = ImagesThatAreCurrentlyLoadingCounter + " of " + ImagesThatAreCurrentlyLoading.Count;

                    if (ImagesThatAreCurrentlyLoading.Count == ImagesThatAreCurrentlyLoadingCounter)
                    {
                        t.Stop();
                        AllImagesLoaded();
                    }
                }
            ).StartInterval(1);
        }
        public ClientToServerBase()
        {
            PollTimer = new Timer();
            PollTimer.StartInterval(500);
            PollTimer.Tick +=
                delegate
                {
                    if (PollCount > MaxConcurrentPolls)
                    {
                        Console.WriteLine(MaxConcurrentPolls + " polls already in progress....");
                        return;
                    }

                    var data = MarkPending();

                    // Console.WriteLine("polling.... sending: " + data.Length);

                    var t = new ClientTansport<Message[]>("");


                    // t.IsVerbose = true;

                    t.BeforeSend += delegate
                    {
                        t.Data = data;
                        t.Descriptor.Description = this.ClientName;

                        PollCount++;
                    };

                    t.Complete += delegate
                    {
                        PollCount--;

                        if (t.Request.IsNoContent)
                        {
                            return;
                        }

                        if (t.Request.IsOffline)
                        {

                            Console.WriteLine("server seems to be offline");

                            this.PollTimer.Stop();

                            return;
                        }

                        if (t.Request.IsOK)
                        {
                            foreach (Message v in t.Data)
                            {
                                if (v.ToServerMessageId > 0)
                                {
                                    RemoveToServerPending(v);
                                }
                                else if (v.ToClientMessageId > 0)
                                {
                                    AsyncInvoke(v);
                                }
                            }

                            t.Data = null;
                        }
                        else
                        {
                            Console.WriteLine("unknown status: " + t.Request.status);
                        }


                    };

                    t.Send();
                };
        }
示例#23
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(IApp page)
        {
            var random = new Random();
            device_id = random.Next();

            #region con
            var con = new ConsoleForm();

            con.InitializeConsoleFormWriter();
            con.StartPosition = FormStartPosition.Manual;
            con.Show();

            // make it slim
            con.Height = 100;

            // TopMost
            con.GetHTMLTarget().style.zIndex = 20002;
            con.Opacity = 0.9;




            Action Toggle =
                delegate
                {
                    if (con.WindowState == FormWindowState.Minimized)
                    {
                        con.WindowState = FormWindowState.Normal;

                    }
                    else
                    {
                        con.WindowState = FormWindowState.Minimized;


                    }

                    // put the console far right bottom
                    con.MoveTo(
                        Native.window.Width - con.Width,
                        Native.window.Height - con.Height
                    );

                };

            Action<int> AtKeyCode =
               KeyCode =>
               {
                   Console.WriteLine(
                       new { KeyCode }

                   );



                   // US
                   if (KeyCode == 222)
                   {
                       Toggle();
                   }
                   // EE
                   if (KeyCode == 192)
                   {
                       Toggle();
                   }
               };


#if onorientationchange
            Native.window.onorientationchange +=
                e =>
                {
                    Toggle();
                };
#endif

            Native.document.onkeyup +=
                e =>
                {
                    AtKeyCode(e.KeyCode);

                };

            Toggle();
            #endregion

            Console.WriteLine("console ready for " + new { id = device_id });

            var x = 0;
            var y = 0;

            #region Virtual Screen
            FormStyler.AtFormCreated = LikeDesktop;
            var fs = new Form { };

            //fs.FormBorderStyle = FormBorderStyle.None;

            fs.BackColor = Color.FromArgb(0, 148, 155);
            fs.Width = Native.screen.width / 4;
            fs.Height = Native.screen.height / 4;
            fs.Show();
            fs.Opacity = 0.5;

            FormStyler.AtFormCreated = LikeVirtualScreen;
            var fvs = new Form { Text = "Virtual Screen" };
            fvs.BackColor = Color.Transparent;
            FormStyler.AtFormCreated = FormStyler.LikeWindowsClassic;
            fvs.Width = Native.screen.width / 4;
            fvs.Height = Native.screen.height / 4;
            fvs.Show();
            fvs.Owner = fs;

            var fw = new Form { };

            fw.Width = Native.window.Width / 4;
            fw.Height = Native.window.Height / 4;
            fw.Show();
            fw.Owner = fvs;
            fw.Opacity = 0.8;

            KeepOwnedFormsLinkedToOwnerLocation(fs);
            KeepOwnedFormsLinkedToOwnerLocation(fvs);
            KeepOwnedFormsLinkedToOwnerLocation(fw);
            #endregion


            // doesnt work yet?
            //fw.SizeGripStyle = SizeGripStyle.Hide;

            var svg = new ISVGSVGElement().AttachTo(page.content);
            svg.style.SetLocation(0, 0);

            var vsvg = new ISVGSVGElement().AttachTo(fvs.GetHTMLTarget());
            vsvg.style.SetLocation(0, 0);

            #region VirtualScreenUpdate
            Action VirtualScreenUpdate = delegate
            {
                if (fs.Capture)
                    return;

                // dragging it?
                if (fvs.Capture)
                    return;

                var max_right = fvs.OwnedForms.Max(k => k.Right);
                var min_left = fvs.OwnedForms.Min(k => k.Left);

                var max_bottom = fvs.OwnedForms.Max(k => k.Bottom);
                var min_top = fvs.OwnedForms.Min(k => k.Top);

                DisableKeepOwnedFormsLinkedToOwnerLocation = true;

                fvs.Left = min_left;
                fvs.Top = min_top;
                fvs.Width = max_right - min_left;
                fvs.Height = max_bottom - min_top;

                page.content.style.SetLocation(
                    (min_left - fw.Left) * 4,
                    (min_top - fw.Top) * 4,
                    (max_right - min_left) * 4,
                    (max_bottom - min_top) * 4
                );



                DisableKeepOwnedFormsLinkedToOwnerLocation = false;

            };
            #endregion


            fw.LocationChanged +=
                delegate
                {
                    VirtualScreenUpdate();
                };

            #region AtResize
            Action AtResize = delegate
            {
                // screen can change, but only once, when window is moved to the other monitor?
                fs.Text = "Screen " + new { Native.screen.width, Native.screen.height };
                fs.Width = Native.screen.width / 4;
                fs.Height = Native.screen.height / 4;

                fw.Text = " " + new { Native.window.Width, Native.window.Height
#if onorientationchange                    
                    , Native.window.orientation 
#endif
                };
                fw.Width = Native.window.Width / 4;
                fw.Height = Native.window.Height / 4;

                VirtualScreenUpdate();
            };



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

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

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

            new ScriptCoreLib.JavaScript.Runtime.Timer(
                delegate
                {
                    AtResize();
                }
            ).StartInterval(1000 / 2);
            #endregion


            // what is attaching what?
            // what about await
            var svgcursor1ghost = new cursor1().AttachTo(page.content).ToSVG();

            var svgcursor1 = new cursor1().AttachTo(page.content).ToSVG();

            svgcursor1.fill += svgcursor1ghost.fill;

            var vcursor = new cursor1().AttachTo(fvs.GetHTMLTarget()).ToSVG();

            var Shadows = new List<Form>();

            Func<Form, Form> CreateShadow =
                _fw =>
                {
                    FormStyler.AtFormCreated = LikeVirtualWindow;
                    var fwshadow = new Form();
                    Shadows.Add(fwshadow);

                    fwshadow.BackColor = Color.Transparent;
                    FormStyler.AtFormCreated = FormStyler.LikeWindowsClassic;
                    fwshadow.Width = Native.screen.width / 4;
                    fwshadow.Height = Native.screen.height / 4;
                    fwshadow.Show();


                    Action fwshadow_update = delegate
                    {

                        fwshadow.MoveTo(_fw.Left, _fw.Top);
                        fwshadow.SizeTo(_fw.Width, _fw.Height);
                    };

                    _fw.LocationChanged +=
                        delegate
                        {
                            fwshadow_update();
                        };

                    _fw.SizeChanged +=
                        delegate
                        {
                            fwshadow_update();

                        };

                    fwshadow_update();

                    _fw.BringToFront();

                    return fwshadow;
                };

            Shadows.Add(CreateShadow(fw));

            bool canexit = false;
            bool canenter = true;

            Action at_exit_MultiMouseMode = delegate
            {
                //Console.WriteLine("at_exit_MultiMouseMode");
            };

            Action at_enter_MultiMouseMode = delegate
            {

                //Console.WriteLine("at_enter_MultiMouseMode");
            };

            Action<IEvent.MouseButtonEnum> at_mousedown = button =>
            {

                //Console.WriteLine("at_enter_mousedown: " + button);
            };


            Action at_mouseup = delegate
            {

                //Console.WriteLine("at_enter_mouseup");
            };




            var path = new ISVGPathElement().AttachTo(svg);
            path.setAttribute("style", "stroke: black; stroke-width: 4; fill: none;");

            var path_d = "";



            var vpath = new ISVGPathElement().AttachTo(vsvg);
            vpath.setAttribute("style", "stroke: black; stroke-width: 1; fill: none;");

            var vpath_d = "";

            bool internal_ismousedown = false;

            Action<IEvent.MouseButtonEnum> internal_mousedown = button =>
            {
                internal_ismousedown = true;

                path = new ISVGPathElement().AttachTo(svg);

                if (button == IEvent.MouseButtonEnum.Left)
                    path.setAttribute("style", "stroke: black; stroke-width: 4; fill: none;");
                else
                    path.setAttribute("style", "stroke: rgb(0, 108, 115); stroke-width: 32; fill: none;");

                path_d = "";


                vpath = new ISVGPathElement().AttachTo(vsvg);

                if (button == IEvent.MouseButtonEnum.Left)
                    vpath.setAttribute("style", "stroke: black; stroke-width: 1; fill: none;");
                else
                    vpath.setAttribute("style", "stroke: rgb(0, 108, 115); stroke-width: 8; fill: none;");

                vpath_d = "";

                svgcursor1.fill(0, 0, 255);
                vcursor.fill(0, 0, 255);

                //path.d = "    M100,50  L10,10   L200,200   ";
                path_d += " M" + x + "," + y;
                path.d = path_d;

                vpath_d += " M" + (x / 4) + "," + (y / 4);
                vpath.d = vpath_d;
            };

            Action<IEvent.MouseButtonEnum> mousedown = button =>
            {
                at_mousedown(button);
                internal_mousedown(button);
            };

            Action internal_mouseup = delegate
            {
                internal_ismousedown = false;





                svgcursor1.fill(0, 255, 0);
                vcursor.fill(0, 255, 0);
            };

            Action mouseup = delegate
            {
                at_mouseup();
                internal_mouseup();
            };



            #region exit_MultiMouseMode
            Action internal_exit_MultiMouseMode = delegate
            {
                svgcursor1.fill(0, 0, 0);
                vcursor.fill(0, 0, 0);

                con.Opacity = 0.9;
                page.content.style.Opacity = 0.3;
                page.content.style.zIndex = 0;

                page.content.style.backgroundColor = "rgba(0, 148, 155, 1)";
                Native.Document.body.style.backgroundColor = "black";

                page.content.style.With(
                    (dynamic s) =>
                    {
                        s.webkitFilter = "blur(3px)";
                    }
                );

                page.info.style.With(
                    (dynamic s) =>
                    {
                        s.webkitFilter = "";
                    }
                );

                Shadows.WithEach(
                   f =>
                       f.GetHTMLTarget().style.With(
                           (dynamic s) =>
                           {
                               s.webkitFilter = "";
                           }
                       )
                 );


                fs.FormsByOwnership().WithEach(
                 f =>
                     f.GetHTMLTarget().style.With(
                         (dynamic s) =>
                         {
                             s.webkitFilter = "";

                         }
                     )
            );


                fvs.OwnedForms.WithEach(
                    k =>
                    {
                        k.GetHTMLTarget().style.display = IStyle.DisplayEnum.block;
                    }
                );




            };

            Action exit_MultiMouseMode = delegate
            {
                if (!canexit)
                    return;

                canexit = false;
                canenter = true;

                at_exit_MultiMouseMode();
                internal_exit_MultiMouseMode();
            };
            #endregion

            #region enter_MultiMouseMode
            Action internal_enter_MultiMouseMode = delegate
            {
                svgcursor1.fill(255, 0, 0);
                vcursor.fill(255, 0, 0);
                con.Opacity = 0.5;

                page.content.style.Opacity = 1.0;
                page.content.style.backgroundColor = "";
                Native.Document.body.style.backgroundColor = "rgba(0, 148, 155, 1)";

                page.content.style.zIndex = 20000;
                con.GetHTMLTarget().style.zIndex = 20002;
                page.content.style.With(
                    (dynamic s) =>
                    {
                        s.webkitFilter = "";
                    }
                );

                page.info.style.With(
                    (dynamic s) =>
                    {
                        s.webkitFilter = "blur(3px)";
                    }
                );


                fvs.OwnedForms.WithEach(
                     k =>
                     {
                         k.GetHTMLTarget().style.display = IStyle.DisplayEnum.none;
                     }
                 );

                Shadows.WithEach(
                  f =>
                      f.GetHTMLTarget().style.With(
                          (dynamic s) =>
                          {
                              s.webkitFilter = "blur(3px)";
                          }
                      )
                );


                fs.FormsByOwnership().WithEach(
                    f =>
                        f.GetHTMLTarget().style.With(
                            (dynamic s) =>
                            {
                                s.webkitFilter = "blur(3px)";
                            }
                        )
                );
            };

            Action enter_MultiMouseMode = delegate
            {
                if (!canenter)
                    return;

                canexit = true;
                canenter = false;

                at_enter_MultiMouseMode();
                internal_enter_MultiMouseMode();
            };
            #endregion





            #region onmousemove



            Native.Document.body.onmouseup +=
              e =>
              {
                  if (Native.Document.pointerLockElement == Native.Document.body)
                  {
                      mouseup();
                      return;
                  }
              };

            Native.Document.body.onmousedown +=
                e =>
                {
                    if (Native.Document.pointerLockElement == Native.Document.body)
                    {
                        mousedown(e.MouseButton);
                        return;
                    }

                    Console.WriteLine("requesting MultiMouse mode!");

                    x = e.CursorX;
                    y = e.CursorY;
                    e.preventDefault();
                    Native.Document.body.requestPointerLock();

                };

            Action<int, int> at_set_cursor_position = delegate { };


            var pxx = 0;
            var pyy = 0;

            var ghost_busy = false;

            Action<int, int> internal_set_cursor_position =
                 (xx, yy) =>
                 {
                     // already set to that exact location!
                     if (pxx == xx)
                         if (pyy == yy)
                             return;


                     pxx = xx;
                     pyy = yy;

                     vcursor.Element.style.SetSize(
                           cursor1.ImageDefaultWidth / 4,
                           cursor1.ImageDefaultHeight / 4
                       );

                     vcursor.Element.style.SetLocation(
                           (xx - 14) / 4,
                           (yy - (64 - 56)) / 4
                       );


                     svgcursor1.Element.style.SetLocation(

                         xx - 14,

                         // inscaope/svg Y is upside down!
                         yy - (64 - 56)

                     );

                     if (!ghost_busy)
                     {
                         ghost_busy = true;

                         svgcursor1ghost.Element.style.Opacity = 0.2;
                         svgcursor1ghost.Element.style.With(
                                (dynamic s) => s.webkitTransition = "all 0.5s linear"
                         );

                         svgcursor1ghost.Element.style.SetLocation(

                            pxx - 14,

                            // inscaope/svg Y is upside down!
                            pyy - (64 - 56)

                        );

                         new ScriptCoreLib.JavaScript.Runtime.Timer(
                             delegate
                             {
                                 svgcursor1ghost.Element.style.SetLocation(

                                    pxx - 14,

                                    // inscaope/svg Y is upside down!
                                    pyy - (64 - 56)

                                );

                                 ghost_busy = false;
                             }
                         ).StartTimeout(500);
                     }


                     // if this window will be activated next time we can continue where we were
                     // told to..
                     x = xx;
                     y = yy;

                     if (internal_ismousedown)
                     {
                         path_d += " L" + x + "," + y;
                         path.d = path_d;

                         vpath_d += " L" + (x / 4) + "," + (y / 4);
                         vpath.d = vpath_d;
                     }

                 };

            Action<int, int> set_cursor_position =
                (xx, yy) =>
                {
                    at_set_cursor_position(xx, yy);
                    internal_set_cursor_position(xx, yy);
                };

            Native.Document.body.onmousemove +=
                e =>
                {
                    if (Native.Document.pointerLockElement == Native.Document.body)
                    {
                        enter_MultiMouseMode();

                        x += e.movementX;
                        y += e.movementY;

                        // clip it
                        // fullscreen behaves differently?
                        x = x.Min(fvs.Width * 4).Max(0);
                        y = y.Min(fvs.Height * 4).Max(0);

                        set_cursor_position(x, y);
                    }
                    else
                    {
                        exit_MultiMouseMode();
                    }

                };
            #endregion

            internal_exit_MultiMouseMode();
            internal_set_cursor_position(0, 0);

            Native.document.body.ontouchstart +=
                 e =>
                 {
                     e.preventDefault();
                     e.stopPropagation();

                     e.touches[0].With(
                         touch =>
                         {
                             // how do we enter?
                             enter_MultiMouseMode();
                             // exit by broswer history move?

                             set_cursor_position(touch.clientX, touch.clientY);

                             // ipad has 11 touchpoints. multiply that with the number of devices/
                             // for now we support 1 pointer per session :)

                             if (e.touches.length == 1)
                                 mousedown(IEvent.MouseButtonEnum.Left);
                             else
                                 mousedown(IEvent.MouseButtonEnum.Right);

                         }
                     );
                 };

            Native.document.body.ontouchend +=
               e =>
               {

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



                   // ipad has 11 touchpoints. multiply that with the number of devices/
                   // for now we support 1 pointer per session :)

                   if (e.touches.length == 0)
                       mouseup();
                   else
                       mousedown(IEvent.MouseButtonEnum.Left);

               };

            Native.document.body.ontouchmove +=
                 e =>
                 {
                     e.preventDefault();
                     e.stopPropagation();


                     e.touches[0].With(
                         touch =>
                         {
                             set_cursor_position(touch.clientX, touch.clientY);
                         }
                     );
                 };



            #region onmessage

            bool disable_bind_reconfigure = false;


            Action<int, int> internal_reconfigure =
                delegate { };

            Action<MessageEvent, XElement> internal_onmessage =
                (e, xml) =>
                {
                    device_onmessage(0, xml);
                };

            Native.window.onmessage +=
                e =>
                {
                    // who sent this? :P
                    var source = (string)e.data;
                    //var now = DateTime.Now;
                    //Console.WriteLine(now + " " + source);


                    var xml = XElement.Parse(source);




                    internal_onmessage(e, xml);
                };

            var friendly_devices = new
            {
                source_device_id = 0,
                f = default(Form),
                children = new
                {
                    child_id = 0,
                    fc = default(Form)
                }.ToEmptyList()
            }.ToEmptyList();

            #region device_onmessage
            this.device_onmessage =
                (source_device_id, xml) =>
                {
                    // mothership to local network?
                    // source_device_id = 0 means it came from one of our virtual screens?

                    if (xml.Name.LocalName == "at_mousedown")
                    {
                        int button = int.Parse(xml.Attribute("button").Value);
                        internal_mousedown((IEvent.MouseButtonEnum)button);
                    }

                    if (xml.Name.LocalName == "at_mouseup")
                    {
                        internal_mouseup();
                    }

                    if (xml.Name.LocalName == "at_enter_MultiMouseMode")
                    {
                        internal_enter_MultiMouseMode();
                    }

                    if (xml.Name.LocalName == "at_exit_MultiMouseMode")
                    {
                        internal_exit_MultiMouseMode();
                    }

                    if (xml.Name.LocalName == "at_set_cursor_position")
                    {
                        int xx = int.Parse(xml.Attribute("x").Value);
                        int yy = int.Parse(xml.Attribute("y").Value);

                        internal_set_cursor_position(xx, yy);
                    }


                };
            #endregion

            var ListOfChildren = new { child_id = 0, fc = default(Form) }.ToEmptyList();

            // when is this called?
            this.device_bind =
                (mothership_postXElement) =>
                {
                    // we might now be able to invoke the server, and via that any other device
                    Console.WriteLine("device_bind");

                    #region at_enter_MultiMouseMode
                    at_enter_MultiMouseMode +=
                        delegate
                        {
                            var xml = new XElement("at_enter_MultiMouseMode");

                            mothership_postXElement(xml);
                        };
                    #endregion

                    #region at_exit_MultiMouseMode
                    at_exit_MultiMouseMode +=
                        delegate
                        {
                            mothership_postXElement(new XElement("at_exit_MultiMouseMode"));
                        };
                    #endregion

                    #region at_mousedown
                    at_mousedown +=
                      button =>
                      {
                          mothership_postXElement(new XElement("at_mousedown", new XAttribute("button", "" + (int)button)));
                      };
                    #endregion

                    #region at_mouseup
                    at_mouseup +=
                     delegate
                     {
                         mothership_postXElement(new XElement("at_mouseup"));
                     };
                    #endregion

                    #region at_set_cursor_position
                    at_set_cursor_position +=
                       (xx, yy) =>
                       {

                           var xml = new XElement("at_set_cursor_position",
                               // int not yet supported?
                                   new XAttribute("x", "" + xx),
                                   new XAttribute("y", "" + yy)
                               );

                           mothership_postXElement(
                               xml
                           );



                       };
                    #endregion

                    // now we can reply..
                    this.device_onmessage +=
                       (source_device_id, xml) =>
                       {
                           #region at_virtualwindowsync_reconfigure
                           if (source_device_id != 0)
                               if (xml.Name.LocalName == "at_virtualwindowsync_reconfigure")
                               {
                                   int __device_id = int.Parse(xml.Attribute("device_id").Value);

                                   if (__device_id == device_id)
                                   {
                                       // are we being reconfigured?

                                       friendly_devices.Where(k => k.source_device_id == source_device_id).WithEach(
                                           q =>
                                           {
                                               int dx = int.Parse(xml.Attribute("dx").Value);
                                               int dy = int.Parse(xml.Attribute("dy").Value);
                                               disable_bind_reconfigure = true;

                                               q.f.MoveTo(
                                                   fw.Left - dx,
                                                   fw.Top - dy
                                               );
                                               disable_bind_reconfigure = false;

                                           }
                                       );
                                   }
                               }
                           #endregion

                           #region at_virtualwindowsync
                           if (source_device_id != 0)
                               if (xml.Name.LocalName == "at_virtualwindowsync")
                               {
                                   Console.WriteLine("got at_virtualwindowsync");

                                   // do we know this device?
                                   var q = friendly_devices.FirstOrDefault(k => k.source_device_id == source_device_id);

                                   int w = int.Parse(xml.Attribute("w").Value);
                                   int h = int.Parse(xml.Attribute("h").Value);

                                   Action reposition = delegate { };

                                   if (q == null)
                                   {
                                       var fc = new Form { Text = new { source_device_id }.ToString() };

                                       q = new { source_device_id, f = fc, children = new { child_id = 0, fc = default(Form) }.ToEmptyList() };

                                       friendly_devices.Add(q);

                                       q.f.StartPosition = FormStartPosition.Manual;
                                       q.f.Show();
                                       // show should respect opacity?
                                       q.f.Opacity = 0.3;


                                       // where to put it?
                                       // left or right?

                                       var max_right = fvs.OwnedForms.Max(k => k.Right);
                                       var min_left = fvs.OwnedForms.Min(k => k.Left);

                                       if (source_device_id < device_id)
                                           q.f.Left = min_left - w;
                                       else
                                           q.f.Left = max_right;

                                       q.f.Top = fw.Top;
                                       q.f.Owner = fvs;

                                       var fcShadow = CreateShadow(q.f);
                                       Shadows.Add(fcShadow);

                                       #region from now on if we move any of our screens
                                       // in relation to this source_device_id we have to notify it

                                       Action SendDelta = delegate
                                       {
                                           var pdx = fc.Left - fw.Left;
                                           var pdy = fc.Top - fw.Top;

                                           mothership_postXElement(
                                             new XElement("at_virtualwindowsync_reconfigure",
                                                 new XAttribute("device_id", "" + source_device_id),
                                                 new XAttribute("dx", "" + pdx),
                                                 new XAttribute("dy", "" + pdy)
                                             )
                                           );
                                       };

                                       fw.LocationChanged +=
                                           delegate
                                           {
                                               if (disable_bind_reconfigure)
                                                   return;

                                               SendDelta();
                                           };

                                       fc.LocationChanged +=
                                           delegate
                                           {
                                               if (disable_bind_reconfigure)
                                                   return;


                                               SendDelta();
                                           };


                                       #endregion


                                   }

                                   // thanks for letting us know that you changed your size...
                                   q.f.Width = w;
                                   q.f.Height = h;


                                   xml.Elements("child").WithEach(
                                       cxml =>
                                       {
                                           // any new children?
                                           int child_id = int.Parse(cxml.Attribute("child_id").Value);

                                           int pdx = int.Parse(cxml.Attribute("pdx").Value);
                                           int pdy = int.Parse(cxml.Attribute("pdy").Value);

                                           int cw = int.Parse(cxml.Attribute("w").Value);
                                           int ch = int.Parse(cxml.Attribute("h").Value);

                                           var cq = q.children.FirstOrDefault(k => k.child_id == child_id);

                                           if (cq == null)
                                           {
                                               var fc = new Form { Text = new { source_device_id, child_id }.ToString() };

                                               cq = new { child_id, fc };

                                               q.children.Add(cq);

                                               cq.fc.StartPosition = FormStartPosition.Manual;
                                               cq.fc.Show();
                                               // show should respect opacity?
                                               cq.fc.Opacity = 0.2;

                                               // if this child needs to be between then add it
                                               // before reposition

                                               cq.fc.Owner = fvs;

                                               var fcShadow = CreateShadow(cq.fc);
                                               Shadows.Add(fcShadow);

                                           }


                                           cq.fc.Left = q.f.Left + pdx;
                                           cq.fc.Top = q.f.Top + pdy;

                                           // thanks for letting us know that you changed your size...
                                           cq.fc.Width = cw;
                                           cq.fc.Height = ch;
                                       }
                                   );

                               }
                           #endregion

                       };

                    // lets tell the world about virtual screens owned by us.
                    // lets start by advertising our size.

                    #region at_virtualwindowsync
                    var t = new ScriptCoreLib.JavaScript.Runtime.Timer(
                        delegate
                        {
                            // do we know whats the dx to other windows?
                            var xml = new XElement("at_virtualwindowsync",
                                // int not yet supported?
                                new XAttribute("w", "" + fw.Width),
                                new XAttribute("h", "" + fw.Height)


                            );

                            #region what about children?
                            ListOfChildren.WithEach(
                                c =>
                                {
                                    var pdx = c.fc.Left - fw.Left;
                                    var pdy = c.fc.Top - fw.Top;

                                    xml.Add(

                                        new XElement("child",
                                            new XAttribute("child_id", "" + c.child_id),
                                        // int not yet supported?
                                            new XAttribute("pdx", "" + pdx),
                                            new XAttribute("pdy", "" + pdy),
                                            new XAttribute("w", "" + c.fc.Width),
                                            new XAttribute("h", "" + c.fc.Height)
                                        )

                                    );
                                }
                            );
                            #endregion


                            mothership_postXElement(
                              xml
                            );

                            Console.WriteLine("sent at_virtualwindowsync");

                        }
                    );

                    t.StartInterval(5000);
                    #endregion

                };

            Action<IWindow, Form> bind =
                (w, fc) =>
                {
                    this.device_bind(w.postXElement);

                    internal_onmessage +=
                        (e, xml) =>
                        {
                            if (xml.Name.LocalName == "reconfigure")
                            {
                                // how do we know this reconfigrue event is for us?

                                if (e.source == w)
                                {
                                    disable_bind_reconfigure = true;

                                    int dx = int.Parse(xml.Attribute("dx").Value);
                                    int dy = int.Parse(xml.Attribute("dy").Value);

                                    //Console.WriteLine("reconfigure " + new { dx, dy, fw.Left });

                                    //fw.Left += dx;
                                    //fw.Top += dy;


                                    fc.MoveTo(
                                        fw.Left - dx,
                                        fw.Top - dy
                                    );

                                    disable_bind_reconfigure = false;
                                }
                            }
                        };

                    Action SendDelta = delegate
                    {
                        var pdx = fc.Left - fw.Left;
                        var pdy = fc.Top - fw.Top;

                        w.postXElement(
                          new XElement("reconfigure",
                              new XAttribute("dx", "" + pdx),
                              new XAttribute("dy", "" + pdy)
                          )
                        );
                    };

                    fw.LocationChanged +=
                        delegate
                        {
                            if (disable_bind_reconfigure)
                                return;

                            SendDelta();
                        };

                    fc.LocationChanged +=
                        delegate
                        {
                            if (disable_bind_reconfigure)
                                return;


                            SendDelta();
                        };
                };
            #endregion


            #region opener
            Native.window.opener.With(
                w =>
                {
                    // disable features
                    page.info.Hide();

                    Console.WriteLine("we have opener: " + w.document.location.href);

                    var fc = new Form { Text = "opener" };

                    fc.Owner = fvs;

                    Action cAtResize = delegate
                    {
                        fc.Text = "Opener " + new { w.Width, w.Height };
                        fc.Width = w.Width / 4;
                        fc.Height = w.Height / 4;
                    };

                    w.onresize += delegate
                    {
                        cAtResize();
                    };

                    var ct = new ScriptCoreLib.JavaScript.Runtime.Timer(
                       delegate
                       {
                           cAtResize();
                       }
                    );

                    ct.StartInterval(1000 / 15);

                    cAtResize();

                    fc.StartPosition = FormStartPosition.Manual;
                    fc.Show();
                    fc.Opacity = 0.7;
                    fc.BackColor = Color.Transparent;

                    var fcShadow = CreateShadow(fc);
                    Shadows.Add(fcShadow);



                    Native.window.requestAnimationFrame +=
                        delegate
                        {
                            // ScriptCoreLib Windows Forms has a few bugs:P
                            fc.MoveTo(fw.Left - fc.Width, fw.Top);

                            bind(w, fc);
                        };

                }
            );
            #endregion

            #region make info clickable

            page.info.onmousedown +=
             e =>
             {
                 if (internal_ismousedown)
                     return;

                 e.stopPropagation();
             };

            page.info.ontouchstart +=
              e =>
              {
                  if (internal_ismousedown)
                      return;


                  e.stopPropagation();
              };

            page.info.ontouchmove +=
          e =>
          {
              if (internal_ismousedown)
                  return;


              e.stopPropagation();
          };

            page.info.ontouchend +=
     e =>
     {
         if (internal_ismousedown)
             return;

         e.stopPropagation();
     };
            #endregion

            #region OpenChildSession



            page.OpenChildSession.onclick +=
                e =>
                {
                    e.preventDefault();

                    Console.WriteLine("open child session...");

                    Native.window.open(
                        Native.Document.location.href,
                        "_blank", 400, 400, true).With(
                        w =>
                        {
                            w.onload +=
                                delegate
                                {
                                    if (w.document.location.href == "about:blank")
                                        return;

                                    Console.WriteLine("child onload " + w.document.location.href);

                                    var fc = new Form { Text = "child" };



                                    Action cAtResize = delegate
                                    {
                                        fc.Text = "Child " + new { w.Width, w.Height };
                                        fc.Width = w.Width / 4;
                                        fc.Height = w.Height / 4;

                                        VirtualScreenUpdate();
                                    };

                                    w.onresize += delegate
                                    {
                                        cAtResize();

                                    };

                                    var ct = new ScriptCoreLib.JavaScript.Runtime.Timer(
                                       delegate
                                       {
                                           cAtResize();
                                       }
                                    );

                                    ct.StartInterval(1000 / 2);

                                    //cAtResize();

                                    fc.StartPosition = FormStartPosition.Manual;
                                    fc.Show();
                                    fc.Opacity = 0.5;
                                    // first child could be a monitor to our right
                                    fc.MoveTo(fw.Right, fw.Top);
                                    fc.Owner = fvs;
                                    fc.BackColor = Color.Transparent;

                                    fc.Width = 400 / 4;
                                    fc.Height = 400 / 4;

                                    VirtualScreenUpdate();



                                    fc.LocationChanged +=
                                        delegate
                                        {
                                            VirtualScreenUpdate();

                                        };

                                    var fcShadow = CreateShadow(fc);
                                    Shadows.Add(fcShadow);

                                    var token = new { child_id = random.Next(), fc };

                                    ListOfChildren.Add(token);

                                    #region FormClosing
                                    w.onbeforeunload +=
                                        delegate
                                        {
                                            if (fc == null)
                                                return;

                                            w = null;

                                            ct.Stop();
                                            fc.Close();
                                            fc = null;
                                        };

                                    Native.window.onbeforeunload +=
                                        delegate
                                        {
                                            if (w == null)
                                                return;

                                            w.close();
                                            w = null;
                                        };

                                    fc.FormClosing +=
                                        delegate
                                        {

                                            if (w == null)
                                                return;

                                            ListOfChildren.Remove(token);
                                            Shadows.Remove(fcShadow);

                                            fc = null;

                                            w.close();
                                            w = null;
                                        };
                                    #endregion



                                    bind(w, fc);


                                };
                        }
                    );
                };
            #endregion





            Native.document.documentElement.style.overflow = IStyle.OverflowEnum.hidden;
        }
示例#24
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);

        }
示例#25
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(IApp page)
        {
            #region IsRightScreen || IsLeftScreen
            var IsRightScreen = Native.Document.location.hash == "#/RightScreen";
            var IsLeftScreen = Native.Document.location.hash == "#/LeftScreen";

            if (IsRightScreen || IsLeftScreen)
            {
                if (IsRightScreen)
                {
                    "Right Screen".ToDocumentTitle();
                }

                if (IsLeftScreen)
                {
                    "Left Screen".ToDocumentTitle();
                }

                Native.Document.body.Clear();

                var a = new CSSTransform3DFPSBlueprint.HTML.Pages.App();

                a.Container.AttachToDocument();


                var hud = new IHTMLDiv().AttachToDocument();

                hud.style.position = IStyle.PositionEnum.absolute;
                hud.style.left = "0px";
                hud.style.top = "0px";
                hud.style.right = "0px";
                //hud.style.height = "2em";
                hud.style.zIndex = 1000;
                hud.style.backgroundColor = "rgba(0, 0, 0, 0.5)";
                hud.style.color = JSColor.White;

                var c = new IHTMLCenter { innerText = Native.Document.location.hash }.AttachTo(hud);

                new CSSTransform3DFPSBlueprint.Application().Initialize(a,
                   x =>
                   {
                       // we know that we are packaging this sub page 
                       // in our web app
                       x.floorplan.deskCube22.LeftWallSource = "/__Templates";
                       x.floorplan.deskCube22.LeftWallSourceAutoLoad = true;


                       var w = CSSTransform3DFPSBlueprint.Application.window;


                       var du = true;
                       var qx = new delta();
                       var qy = new delta();
                       var qz = new delta();
                       var qp = new delta();

                       x.AfterKeystateChange +=
                        delegate
                        {
                            var data = new XElement("keyState",
                                new XAttribute("w", "" + w.keyState.forward),
                                new XAttribute("s", "" + w.keyState.backward),
                                new XAttribute("a", "" + w.keyState.strafeleft),
                                new XAttribute("d", "" + w.keyState.straferight)
                            );

                            Native.Window.opener.With(
                                parent =>
                                {
                                    //c.innerText = data.ToString();

                                    parent.postMessage(data.ToString());
                                }
                            );

                        };

                       x.AfterCameraRotationChange +=
                           delegate
                           {
                               var data = new XElement("viewport.camera.rotation",
                                   new XAttribute("x", "" + w.viewport.camera.rotation.x),
                                   new XAttribute("y", "" + w.viewport.camera.rotation.y),
                                   new XAttribute("z", "" + w.viewport.camera.rotation.z)
                               );

                               Native.Window.opener.With(
                                   parent =>
                                   {
                                       //c.innerText = data.ToString();

                                       parent.postMessage(data.ToString());
                                   }
                               );

                           };

                       Func<string, bool> bool_Parse =
                           xx =>
                           {
                               return xx.ToLower() == "true";
                           };

                       Native.Window.onmessage +=
                            e =>
                            {
                                var data = XElement.Parse("" + e.data);

                                #region shared.perspective
                                if (data.Name.LocalName == "shared.perspective")
                                {
                                    w.viewport.node.style.width = "200%";

                                    if (IsRightScreen)
                                    {
                                        w.viewport.node.style.marginLeft = "-100%";

                                    }


                                    CSSTransform3DFPSBlueprint.Application.window.viewport.node.style.marginTop = "-25%";
                                    w.viewport.node.style.height = "150%";






                                    //if (IsRightScreen)
                                    //{
                                    //}
                                }
                                #endregion

                                var hasupdate = true;

                                if (data.Name.LocalName == "keyState")
                                {
                                    w.keyState.forward = bool_Parse(data.Attribute("w").Value);
                                    w.keyState.backward = bool_Parse(data.Attribute("s").Value);
                                    w.keyState.strafeleft = bool_Parse(data.Attribute("a").Value);
                                    w.keyState.straferight = bool_Parse(data.Attribute("d").Value);


                                }


                                if (data.Name.LocalName == "viewport.camera.rotation")
                                {
                                    new
                                    {
                                        x = int.Parse(data.Attribute("x").Value),
                                        y = int.Parse(data.Attribute("y").Value),
                                        z = int.Parse(data.Attribute("z").Value)
                                    }.With(
                                        r =>
                                        {
                                            w.viewport.camera.rotation.x = r.x;
                                            w.viewport.camera.rotation.y = r.y;
                                            w.viewport.camera.rotation.z = r.z;

                                        }
                                    );
                                }

                                if (data.Name.LocalName == "ChangeRotationBy")
                                {
                                    new
                                    {
                                        x = int.Parse(data.Attribute("x").Value),
                                        y = int.Parse(data.Attribute("y").Value),
                                    }.With(
                                        r =>
                                        {
                                            w.viewport.camera.rotation.x -= r.y;
                                            w.viewport.camera.rotation.z += r.x;

                                        }
                                    );
                                }


                                if (data.Name.LocalName == "range")
                                {
                                    qx.newvalue = int.Parse(data.Attribute("x").Value);
                                    qy.newvalue = int.Parse(data.Attribute("y").Value);
                                    qz.newvalue = int.Parse(data.Attribute("z").Value);
                                    var s = int.Parse(data.Attribute("s").Value) / 50.0;

                                    s *= s;
                                    s *= s;

                                    qp.newvalue = int.Parse(data.Attribute("p").Value);

                                    if (du)
                                    {
                                        qx.oldvalue = qx.newvalue;
                                        qy.oldvalue = qy.newvalue;
                                        qz.oldvalue = qz.newvalue;
                                        qp.oldvalue = qp.newvalue;
                                        du = false;
                                    }
                                    else
                                    {
                                        hasupdate = false;

                                        if (qx.newvalue != qx.oldvalue)
                                        {
                                            qx.dx = qx.newvalue - qx.oldvalue;
                                            qx.oldvalue = qx.newvalue;
                                            w.viewport.camera.rotation.x -= qx.dx * 0.2 * s;
                                            hasupdate = true;
                                        }

                                        if (qy.newvalue != qy.oldvalue)
                                        {
                                            qy.dx = qy.newvalue - qy.oldvalue;
                                            qy.oldvalue = qy.newvalue;

                                            var newy = w.viewport.camera.rotation.y - qy.dx * 0.1 * s;

                                            //Console.WriteLine(
                                            //     new
                                            //     {
                                            //         w.viewport.camera.rotation.y,
                                            //         newy
                                            //     }
                                            //);

                                            // { y = 0.09999999999999937, newy = -6.38378239159465e-16 }
                                            //-6.38378239159465e-16
                                            // small values cause an anomaly?
                                            if (Math.Abs(newy) < 0.05)
                                                w.viewport.camera.rotation.y = 0;
                                            else
                                                w.viewport.camera.rotation.y = newy;
                                            hasupdate = true;
                                        }

                                        if (qz.newvalue != qz.oldvalue)
                                        {
                                            qz.dx = qz.newvalue - qz.oldvalue;
                                            qz.oldvalue = qz.newvalue;
                                            w.viewport.camera.rotation.z -= qz.dx * 0.5 * s;
                                            hasupdate = true;
                                        }


                                        if (qp.newvalue != qp.oldvalue)
                                        {
                                            //qz.dx = qz.newvalue - qz.oldvalue;
                                            qp.oldvalue = qp.newvalue;
                                            w.viewport.node.style.perspective = "" + (500 + qp.newvalue * 4 * s);
                                            hasupdate = true;
                                        }
                                    }



                                }

                                //c.innerText = new { data, dx, newvalue, oldvalue }.ToString();

                                if (hasupdate)
                                    c.innerText = data.ToString();


                                //oldvalue = newvalue;
                                //w.viewport.camera.rotation.x -= e.movementY / 2;

                            };
                   }
               );




                return;
            }
            #endregion

            Action range_onchange = delegate
            {
            };

            #region bind
            Action<IHTMLButton, string, Action<IWindow, XElement>> bind =
                (btn, hash, yield) =>
                {
                    btn.onclick +=
                        delegate
                        {
                            btn.disabled = true;

                            var w = Native.Window.open(
                                hash,
                                "_blank",
                                400,
                                300,
                                false
                            );

                            w.focus();

                            w.onload +=
                                delegate
                                {
                                    Action onchange =
                                        delegate
                                        {


                                            //                       JellyworldExperiment.DualView.Application+<>c__DisplayClassc+<>c__DisplayClass14+<>c__DisplayClass16+<>c__DisplayClass18
                                            //script: error JSC1000: Method: <.ctor>b__7, Type: JellyworldExperiment.DualView.Application+<>c__DisplayClassc+<>c__DisplayClass14+<>c__DisplayClass16+<>c__DisplayClass18; emmiting failed : System.ArgumentNullException: Value cannot be null.
                                            //   at jsc.ILFlowStackItem.InlineLogic(   )
                                            //   at  .    .    ( ?   ,    , ILInstruction , ILFlowStackItem )
                                            //   at  .    .    ( ?   ,    , ILInstruction , ILFlowStackItem )
                                            //   at  . ?  .    (   , ILInstruction , ILFlowStackItem[] , Int32 , MethodBase )

                                            var xml = new XElement("range",
                                              new XAttribute("x", page.range_x.value),
                                              new XAttribute("y", page.range_y.value),
                                              new XAttribute("z", page.range_z.value),
                                              new XAttribute("s", page.range_s.value),
                                              new XAttribute("p", page.range_p.value)
                                          );

                                            w.postMessage(xml.ToString());

                                        };

                                    onchange();

                                    page.range_x.onchange +=
                                        delegate
                                        {
                                            onchange();
                                        };
                                    page.range_y.onchange +=
                                        delegate
                                        {
                                            onchange();
                                        };
                                    page.range_z.onchange +=
                                        delegate
                                        {
                                            onchange();
                                        };
                                    page.range_s.onchange +=
                                     delegate
                                     {
                                         onchange();
                                     };

                                    page.range_p.onchange +=
                                        delegate
                                        {
                                            onchange();
                                        };

                                    range_onchange += onchange;

                                    Native.Window.onmessage +=
                                         e =>
                                         {
                                             if (e.source != w)
                                                 return;

                                             var data = XElement.Parse("" + e.data);

                                             yield(w, data);

                                         };

                                    yield(w, null);
                                };
                        };


                };
            #endregion

            #region do bind
            var wLeftScreen = default(IWindow);
            var wRightScreen = default(IWindow);

            bind(page._LeftScreen, "#/LeftScreen",
                (w, data) =>
                {
                    if (wLeftScreen == null)
                    {
                        wLeftScreen = w;

                        w.onbeforeunload +=
                            delegate
                            {
                                page._LeftScreen.innerText = "closed";
                            };

                        Native.Window.onbeforeunload +=
                            delegate
                            {
                                wLeftScreen.close();
                            };
                    }


                    if (data != null)
                    {
                        page._LeftScreen.innerText = data.ToString();

                        if (wRightScreen != null)
                        {
                            wRightScreen.postMessage(data.ToString());
                        }
                    }
                }
            );

            bind(page._RightScreen, "#/RightScreen",
                (w, data) =>
                {
                    if (wRightScreen == null)
                    {
                        wRightScreen = w;

                        w.onbeforeunload +=
                             delegate
                             {
                                 page._RightScreen.innerText = "closed";
                             };


                        Native.Window.onbeforeunload +=
                            delegate
                            {
                                wRightScreen.close();
                            };
                    }

                    if (data != null)
                    {
                        page._RightScreen.innerText = data.ToString();


                        if (wLeftScreen != null)
                        {
                            wLeftScreen.postMessage(data.ToString());
                        }
                    }
                }
            );
            #endregion

            page._SharedPerspective.onclick +=
                delegate
                {
                    var data = new XElement("shared.perspective", "dummy");

                    if (wLeftScreen != null)
                        wLeftScreen.postMessage(data.ToString());

                    if (wRightScreen != null)
                        wRightScreen.postMessage(data.ToString());


                };

            forward = false;
            backward = false;
            strafeleft = false;
            straferight = false;

            this.AfterKeystateChange =
                delegate
                {
                    var data = new XElement("keyState",
                           new XAttribute("w", "" + forward),
                           new XAttribute("s", "" + backward),
                           new XAttribute("a", "" + strafeleft),
                           new XAttribute("d", "" + straferight)
                       );

                    Console.WriteLine("AfterKeystateChange: " + data);

                    if (wLeftScreen != null)
                        wLeftScreen.postMessage(data.ToString());

                    if (wRightScreen != null)
                        wRightScreen.postMessage(data.ToString());

                };

            ChangeRotationBy =
                (x, y) =>
                {
                    var data = new XElement("ChangeRotationBy",
                        new XAttribute("x", "" + x),
                        new XAttribute("y", "" + y)
                    );

                    Console.WriteLine("AfterKeystateChange: " + data);

                    if (wLeftScreen != null)
                        wLeftScreen.postMessage(data.ToString());

                    if (wRightScreen != null)
                        wRightScreen.postMessage(data.ToString());
                };

            #region onkeydown
            Native.Document.body.onkeydown += e =>
            {
                //Console.WriteLine(new { e.KeyCode });

                if (e.KeyCode == (int)Keys.W)
                    forward = true;
                if (e.KeyCode == (int)Keys.S)
                    backward = true;
                if (e.KeyCode == (int)Keys.A)
                    strafeleft = true;
                if (e.KeyCode == (int)Keys.D)
                    straferight = true;

                if (AfterKeystateChange != null)
                    AfterKeystateChange();
            };

            Native.Document.body.onkeyup += e =>
            {
                if (e.KeyCode == (int)Keys.W)
                    forward = false;
                if (e.KeyCode == (int)Keys.S)
                    backward = false;

                if (e.KeyCode == (int)Keys.A)
                    strafeleft = false;
                if (e.KeyCode == (int)Keys.D)
                    straferight = false;

                if (AfterKeystateChange != null)
                    AfterKeystateChange();
            };
            #endregion

            #region FaceDetectedAt

            var attimer = false;
            ScriptCoreLib.JavaScript.Runtime.Timer t = null;

            FaceDetectedAt =
                (Left, Top, Width, Height) =>
                {
                    page.SimulateFace.disabled = true;

                    var f = new { Left, Top, Width, Height };


                    if (t != null)
                        t.Stop();

                    t = new ScriptCoreLib.JavaScript.Runtime.Timer(
                        delegate
                        {
                            attimer = true;
                            FaceDetectedAt(Left, Top, Width, Height);
                        }
                    );

                    t.StartInterval(1000 / 100);

                    page.range_x.value = "" + (100 - Math.Max(0, (100 * f.Top / (Native.Window.Height - f.Height))).Min(100));

                    //Console.WriteLine(new { f, page.range_x.value });

                    var range_y_old = int.Parse(page.range_y.value);
                    var range_z_old = int.Parse(page.range_z.value);
                    var range_z_new =
                        (int)(100.0 * f.Left / (Native.Window.Width - f.Width)).Max(0).Min(100);

                    page.range_z.value = "" + range_z_new;

                    if (range_z_old == range_z_new)
                    {
                        if (attimer)
                        {
                            attimer = false;

                            if (range_y_old != 50)
                            {
                                if (range_y_old > 50)
                                    page.range_y.value = "" + (int)(range_y_old - 1);
                                else
                                    page.range_y.value = "" + (int)(range_y_old + 1);
                            }
                        }
                    }
                    else
                    {
                        //var range_y_new = (Math.Sign(range_z_old - range_z_new) * 4 + range_y_old).Min(100).Max(0);

                        //page.range_y.value = "" + range_y_new;
                    }


                    range_onchange();
                };
            #endregion


            Native.Document.body.onmousedown +=
                e =>
                {
                    if (e.Element != page.AskForDragPermission)
                        if (e.Element != Native.Document.body)
                        {
                            return;
                        }

                    e.preventDefault();

                    Native.Document.body.requestPointerLock();
                };

            Native.Document.body.onmousemove +=
                e =>
                {
                    if (Native.Document.pointerLockElement != Native.Document.body)
                        return;


                    this.ChangeRotationBy(
                        e.movementX,
                        e.movementY
                    );

                };

            Native.Document.body.onmouseup +=
               e =>
               {
                   if (Native.Document.pointerLockElement != Native.Document.body)
                       return;

                   Native.Document.exitPointerLock();
               };


            page.SimulateFace.onclick +=
                delegate
                {
                    page.SimulateFace.disabled = true;

                    new Form { Text = "Simulated Face Detection" }.With(
                        f =>
                        {
                            f.LocationChanged +=
                                delegate
                                {
                                    FaceDetectedAt(f.Left, f.Top, f.Width, f.Height);
                                };

                            f.SizeChanged +=
                                delegate
                                {
                                    FaceDetectedAt(f.Left, f.Top, f.Width, f.Height);
                                };

                        }
                    ).Show();


                };
        }
示例#26
0
            void t_Tick(Timer e)
            {
                laine.style.left = ((t.Counter % ViewWidth) - ViewWidth) + "px";
                antilaine.style.left = (-t.Counter % ViewWidth) + "px";

                if (System.Math.Abs(kalax - cursor.X) > 32)
                {
                    if (kalax > cursor.X)
                    {
                        piltkala.src = new kala().src;
                        kalax--;
                    }
                    else
                    {
                        piltkala.src = new kalar().src;
                        kalax++;

                    }

                    piltkala.style.left = kalax + "px";
                }
            }
示例#27
0
        static public void FadeAndRemove(IHTMLElement target, int waittime, int fadetime, params IHTMLElement[] cotargets)
        {
            // if IE
            target.style.height = target.clientHeight + "px";

            new Timer(
                delegate
                {
                    Timer a = null;

                    a = new Timer(
                        delegate
                        {

                            target.style.Opacity = 1 - (a.Counter / a.TimeToLive);

                            if (a.Counter == a.TimeToLive)
                            {

                                target.Orphanize();

                                foreach (IHTMLElement z in cotargets)
                                    z.Orphanize();

                                
                                
                            }

                        }
                        );


                    a.StartInterval(fadetime / 25, 25);
                }
            ).StartTimeout(waittime);
        }
示例#28
0
        public ApplicationContent(
            IApp page = null,
            IApplicationWebServiceX service = null)
        {
            // need absolute path when docked..
            page.style1.href = page.style1.href;

            // first order of business.
            // enable drop zone.
            var dz = new DropZone();


            dz.Container.AttachToDocument();
            dz.Container.Hide();

            var StayAlertTimer = default(Timer);
            var DoRefresh = default(Action);

            #region StayAlert
            Action<string> StayAlert =
                transaction_id =>
                {
                    StayAlertTimer = new Timer(
                        delegate
                        {
                            service.GetTransactionKeyAsync(
                                id =>
                                {
                                    if (id == transaction_id)
                                        return;

                                    // shot down during flight?
                                    if (!StayAlertTimer.IsAlive)
                                        return;

                                    Console.WriteLine("StayAlert " + new { id, transaction_id });

                                    DoRefresh();
                                }
                            );
                        }
                    );

                    StayAlertTimer.StartInterval(5000);
                };
            #endregion


            DoRefresh =
                delegate
                {
                    if (StayAlertTimer != null)
                        StayAlertTimer.Stop();

                    page.output.Clear();

                    new FileLoading().Container.AttachTo(page.output);

                    service.EnumerateFilesAsync(
                        y:
                        (
                            long ContentKey,
                            string ContentValue,
                            string ContentType,
                            long ContentBytesLength
                        ) =>
                        {
                            var e = new FileEntry();

                            #region ContentValue
                            e.ContentValue.value = ContentValue.TakeUntilLastIfAny(".");
                            e.ContentValue.onchange +=
                                delegate
                                {
                                    var ext = ContentValue.SkipUntilLastOrEmpty(".");

                                    if (ext != "")
                                        ext = "." + ext;

                                    ContentValue = e.ContentValue.value + ext;


                                    Console.WriteLine("before update!");

                                    service.UpdateAsync(
                                        ContentKey,
                                        ContentValue,
                                        // null does not really work?
                                        delegate
                                        {
                                            Console.WriteLine("update done!");
                                        }
                                    );

                                    e.open.href = Native.Document.location.href.TakeUntilLastIfAny("/") + "/io/" + ContentKey + "/" + ContentValue;
                                };
                            e.open.href = Native.Document.location.href.TakeUntilLastIfAny("/") + "/io/" + ContentKey + "/" + ContentValue;
                            e.open.target = Target;

                            #endregion

                            e.ContentType.innerText = ContentBytesLength + " bytes " + ContentType;


                            #region Delete
                            e.Delete.WhenClicked(
                                delegate
                                {
                                    //e.ContentValue.style.textDecoration = ""

                                    if (StayAlertTimer != null)
                                        StayAlertTimer.Stop();

                                    e.Container.style.backgroundColor = "red";

                                    service.DeleteAsync(
                                        ContentKey,
                                        delegate
                                        {

                                            DoRefresh();
                                        }
                                    );
                                }
                            );
                            #endregion


                            e.Container.AttachTo(page.output);



                            Console.WriteLine(
                                new { ContentKey, ContentValue, ContentType, ContentBytesLength }
                            );

                        },

                        done: transaction_id =>
                        {
                            Console.WriteLine(new { transaction_id });
                            new FileLoadingDone().Container.AttachTo(page.output);

                            StayAlert(transaction_id);
                        }
                    );
                };

            #region ondrop

            var TimerHide = new Timer(
                delegate
                {
                    dz.Container.Hide();
                }
            );

            Action<DragEvent> ondragover =
                evt =>
                {
                    //Console.WriteLine("ondragover");


                    evt.stopPropagation();
                    evt.preventDefault();

                    // ondragover { type = Files }

                    //foreach (var type in evt.dataTransfer.types)
                    //{
                    //    Console.WriteLine("ondragover " + new { type });
                    //}


                    if (evt.dataTransfer.types.Contains("Files"))
                    {


                        evt.dataTransfer.dropEffect = "copy"; // Explicitly show this is a copy.

                        dz.Container.Show();
                        TimerHide.Stop();
                    }

                    //}

                    //Console.WriteLine(" Native.Document.body.ondragover");
                };

            Native.Document.body.ondragover += ondragover;
            dz.Container.ondragover += ondragover;

            //dz.Container.ondragstart +=
            //    evt =>
            //    {
            //        Console.WriteLine("ondragstart");


            //        evt.stopPropagation();
            //        evt.preventDefault();
            //    };

            dz.Container.ondragleave +=
                 evt =>
                 {
                     //Console.WriteLine("ondragleave");

                     //Console.WriteLine(" dz.Container.ondragleave");

                     evt.stopPropagation();
                     evt.preventDefault();

                     TimerHide.StartTimeout(90);
                 };

            dz.Container.ondrop +=
                evt =>
                {
                    //Console.WriteLine("ondrop");

                    TimerHide.StartTimeout(90);

                    evt.stopPropagation();
                    evt.stopImmediatePropagation();

                    evt.preventDefault();

                    // can we use a webClient yet?
                    var xhr = new IXMLHttpRequest();

                    // does not work for chrome?
                    //xhr.setRequestHeader("WebServiceMethod", "FileStorageUpload");

                    // which server?
                    xhr.open(ScriptCoreLib.Shared.HTTPMethodEnum.POST, "/FileStorageUpload");

                    // http://stackoverflow.com/questions/13870853/how-to-upload-files-in-web-workers-when-formdata-is-not-defined

                    //var c = new WebClient();

                    ////c.UploadData(
                    //c.UploadProgressChanged +=
                    //    (sender, args) =>
                    //    {

                    //    };

                    //c.UploadFileAsync(



                    #region send
                    var d = new FormData();

                    evt.dataTransfer.files.AsEnumerable().WithEachIndex(
                        (f, index) =>
                        {
                            d.append("file" + index, f, f.name);
                        }
                    );

                    xhr.InvokeOnComplete(
                        delegate
                        {
                            Console.WriteLine("upload complete!");

                            DoRefresh();
                        }
                    );

                    var upload = new Uploading();

                    upload.Container.AttachTo(page.output);
                    // http://www.matlus.com/html5-file-upload-with-progress/
                    xhr.upload.onprogress +=
                        e =>
                        {
                            var p = (int)(e.loaded * 100 / e.total) + "%";

                            upload.status = p;

                            Console.WriteLine("upload.onprogress " + new { e.total, e.loaded });
                        };

                    xhr.send(d);
                    #endregion


                    if (StayAlertTimer != null)
                        StayAlertTimer.Stop();



                };
            #endregion




            DoRefresh();
        }
示例#29
0
        public StudioView(Action<IHTMLElement, Action<ISaveAction>> AddSaveButton = null)
        {
            Content.style.position = IStyle.PositionEnum.absolute;
            Content.style.left = "0px";
            Content.style.right = "0px";
            Content.style.top = "0px";
            Content.style.bottom = "0px";

            new TwentyTenWorkspace().ToBackground(Content.style, true);

            var WorkspaceHeaderTab0 = new IHTMLDiv().With(
                div =>
                {
                    div.style.position = IStyle.PositionEnum.absolute;
                    div.style.top = "0px";
                    div.style.left = "0px";
                    div.style.width = "14em";
                    div.style.height = "6em";

                    div.style.padding = "0.5em";

                    new Glow1().ToBackground(div.style, false);
                }
            ).AttachTo(Content);

            var WorkspaceHeaderTab1 = new IHTMLDiv().With(
                div =>
                {
                    div.style.position = IStyle.PositionEnum.absolute;
                    div.style.top = "0px";
                    div.style.left = "14em";
                    div.style.width = "20em";
                    div.style.height = "6em";

                    div.style.padding = "0.5em";

                    new Glow1().ToBackground(div.style, false);
                }
            ).AttachTo(Content);

            var WorkspaceHeaderTab2 = new IHTMLDiv().With(
                div =>
                {
                    div.style.position = IStyle.PositionEnum.absolute;
                    div.style.top = "0px";
                    div.style.left = "34em";
                    div.style.right = "6em";
                    div.style.height = "6em";

                    div.style.padding = "0.5em";

                    new Glow1().ToBackground(div.style, false);
                }
            ).AttachTo(Content);

            var WorkspaceHeaderTab7 = new IHTMLDiv().With(
                 div =>
                 {
                     div.style.position = IStyle.PositionEnum.absolute;
                     div.style.top = "0px";
                     div.style.width = "6em";
                     div.style.right = "0px";
                     div.style.height = "6em";

                     //div.style.padding = "0.5em";

                     new Glow1().ToBackground(div.style, false);
                 }
             ).AttachTo(Content);

            var WorkspaceHeaderTab0Text = default(IHTMLSpan);



            new DownloadSDK
            {

            }.AttachTo(
                 new IHTMLAnchor
                 {
                     title = "Download JSC SDK!",
                     href = "http://download.jsc-solutions.net"
                 }.AttachTo(WorkspaceHeaderTab7)
            );

            @"studio.jsc-solutions.net".ToDocumentTitle().With(
                title =>
                {
                    WorkspaceHeaderTab0Text = new IHTMLSpan { innerText = title };

                    WorkspaceHeaderTab0Text.AttachTo(WorkspaceHeaderTab0);
                    //WorkspaceHeaderTab0Text.style.SetLocation(16, 8);
                    WorkspaceHeaderTab0Text.style.fontFamily = IStyle.FontFamilyEnum.Tahoma;
                    WorkspaceHeaderTab0Text.style.color = Color.White;
                    WorkspaceHeaderTab0Text.style.display = IStyle.DisplayEnum.block;

                    // http://www.quirksmode.org/css/textshadow.html
                    WorkspaceHeaderTab0Text.style.textShadow = "#808080 4px 2px 2px";

                }
            );


            if (AddSaveButton != null)
                AddSaveButton(WorkspaceHeaderTab0Text, i => Save = i);

            // em + px :)
            var Workspace0 = new IHTMLDiv().With(
                div =>
                {
                    div.style.position = IStyle.PositionEnum.absolute;
                    div.style.left = "0px";
                    div.style.right = "0px";
                    div.style.bottom = "0px";
                    div.style.top = "6em";
                }
            ).AttachTo(Content);

            // workspace contains the split views
            var Workspace = new IHTMLDiv().With(
                div =>
                {
                    div.style.position = IStyle.PositionEnum.absolute;
                    div.style.left = "6px";
                    div.style.right = "6px";
                    div.style.bottom = "6px";
                    div.style.top = "6px";
                }
            ).AttachTo(Workspace0);

            // in this project we wont be having toolbox or toolbar yet

            Action<HorizontalSplit> ApplyStyle =
                t =>
                {
                    t.Split.Splitter.style.backgroundColor = Color.None;
                    t.SplitImageContainer.Orphanize();
                    t.SplitArea.Target.style.borderLeft = "0";
                    t.SplitArea.Target.style.borderRight = "0";
                    t.SplitArea.Target.style.width = "6px";
                    t.SplitArea.Target.style.Opacity = 0.7;

                    // should we obselete JSColor already?
                    t.SelectionColor = JSColor.Black;
                };

            var EditorTreeSplit = new HorizontalSplit
            {
                Minimum = 0,
                Maximum = 1,
                Value = 0.7,
            };

            EditorTreeSplit.With(ApplyStyle);

            EditorTreeSplit.Split.Splitter.style.backgroundColor = Color.None;


            EditorTreeSplit.Container.AttachTo(Workspace);



            var Split = new HorizontalSplit
            {
                Minimum = 0,
                Maximum = 1,
                Value = 0.3,
            };

            Split.With(ApplyStyle);

            Split.Split.Splitter.style.backgroundColor = Color.None;

            EditorTreeSplit.LeftContainer = Split.Container;



            var SolutionToolbox = new SolutionDockWindowPage();

            SolutionToolbox.HeaderText.innerText = "Toolbox";
            SolutionToolbox.Content.style.backgroundColor = Color.White;
            SolutionToolbox.Content.style.padding = "2px";
            SolutionToolbox.Content.style.overflow = IStyle.OverflowEnum.auto;
            SolutionToolbox.Content.Clear();


            var vv = new SolutionToolboxListView();

            vv.Container.style.color = Color.Black;
            //vv.Container.AttachTo(SolutionToolbox.Content);

            var items = new StockToolboxTabsForHTMLDocument();

            // jsc market components

            vv.Add(
             new SolutionToolboxListViewTab
             {
                 DataType = "DataTable",

                 Name = "DataTable",
                 Title = "DataTable",
                 Text = "DataTable",
                 Icon = new DataTableImage()
             }
          );

            vv.Add(
                new SolutionToolboxListViewTab
                {
                    DataType = "SpiralDataType",

                    Name = "Spiral1",
                    Title = "Spiral",
                    Text = "Spiral",
                    Icon = new Spiral()
                }
             );

            // can we drag this into 
            // code ?
            // msvs gets the image link
            //http://192.168.43.252:11924/assets/ScriptCoreLib.Ultra.Components/StockToolboxImageTransparent64.png?data-jsc-type=DAETruck
            vv.Add(
                  new SolutionToolboxListViewTab
                  {
                      DataType = "DAETruck",

                      Name = "DAETruck",
                      Title = "DAETruck",
                      Text = "DAETruck",
                      Icon = new DAETruck()
                  }
               );

            vv.Add(
                new SolutionToolboxListViewTab
                {
                    DataType = "WebGLEarthByBjorn",

                    Name = "WebGLEarthByBjorn",
                    Title = "WebGLEarthByBjorn",
                    Text = "WebGLEarthByBjorn",
                    Icon = new WebGLEarthByBjorn()
                }
                );


            items.WithEach(vv.Add);




            var Viewer = new SolutionDocumentViewer();
            SolutionDocumentViewerTab File7Tab = "Design/App.htm";
            Viewer.Add(File7Tab);

            #region OutputFile
            var OutputFile = new SolutionFile();
            var OutputFileViewer = new SolutionFileView();

            // fullscreen! :)
            OutputFileViewer.Container.style.height = "100%";

            OutputFile.IndentStack.Push(
                delegate
                {
                    OutputFile.Write(SolutionFileTextFragment.Comment, "" + DateTime.Now);
                    OutputFile.WriteSpace();
                }
            );

            Action<string> OutputWriteLine =
                n =>
                {
                    // Would we want to rewire System.Out? Console.WriteLine?
                    OutputFile.WriteIndent();
                    OutputFile.WriteLine(n);

                    // we could have a resume feature? now we just go and clear...
                    OutputFileViewer.File = OutputFile;
                };


            OutputWriteLine("studio.jsc-solutions.net ready!");
            #endregion

            SolutionDocumentViewerTab OutputTab = "Output";
            Viewer.Add(OutputTab);
            OutputTab.TabElement.style.Float = IStyle.FloatEnum.right;


            SolutionDocumentViewerTab AboutTab = "Project";
            Viewer.Add(AboutTab);
            AboutTab.TabElement.style.Float = IStyle.FloatEnum.right;


            var CurrentDesigner = new SolutionFileDesigner();




            var HTMLDesigner = new SolutionFileDesignerHTMLElementTabs();

            CurrentDesigner.Add(HTMLDesigner);


            // undoable?
            var sln = new SolutionBuilder();




            #region CodeSourceA
            var CodeSourceATab =
                new SolutionFileDesignerTab
                {
                    Image = new RTA_mode_html(),
                    Text = "Generated Code"
                };

            var CodeSourceAView = new SolutionFileView();

            CodeSourceAView.Container.style.position = IStyle.PositionEnum.absolute;
            CodeSourceAView.Container.style.left = "0px";
            CodeSourceAView.Container.style.right = "0px";
            CodeSourceAView.Container.style.top = "0px";
            CodeSourceAView.Container.style.bottom = "0px";

            CodeSourceAView.Container.style.display = IStyle.DisplayEnum.none;
            CodeSourceAView.Container.AttachTo(CurrentDesigner.Content);

            CodeSourceATab.Deactivated +=
                delegate
                {
                    CodeSourceAView.Container.style.display = IStyle.DisplayEnum.none;
                };

            CodeSourceATab.Activated +=
                delegate
                {
                    HTMLDesigner.HTMLDesignerContent.WhenContentReady(
                        body =>
                        {
                            var CodeSourceFile = new SolutionFile
                            {

                                Name = "Default.htm"
                            };

                            var Type = new SolutionProjectLanguageType
                            {
                                Comments = new SolutionFileComment[] { "This type was generated from the HTML file." },
                                Namespace = sln.Name + ".HTML.Pages",
                                Name = "IDefaultPage",
                                IsInterface = true,
                            };

                            (from n in body.AsXElement().DescendantsAndSelf()
                             let id = n.Attribute("id")
                             where id != null
                             select new { n, id }
                            ).WithEach(
                                k =>
                                {
                                    Type.Properties.Add(
                                        new KnownStockTypes.ScriptCoreLib.JavaScript.DOM.HTML.IHTMLElement().ToAutoProperty(k.id.Value)
                                    );
                                }
                            );

                            sln.Language.WriteType(CodeSourceFile, Type, null);

                            CodeSourceAView.File = CodeSourceFile;

                            CodeSourceAView.Container.style.display = IStyle.DisplayEnum.empty;
                        }
                    );
                };


            #endregion


            #region CodeSourceB
            var CodeSourceBTab =
                new SolutionFileDesignerTab
                {
                    Image = new RTA_mode_html(),
                    // all source code, not just html?
                    Text = "Source"
                };

            var CodeSourceBView = new SolutionFileView();

            CodeSourceBView.Container.style.position = IStyle.PositionEnum.absolute;
            CodeSourceBView.Container.style.left = "0px";
            CodeSourceBView.Container.style.right = "0px";
            CodeSourceBView.Container.style.top = "0px";
            CodeSourceBView.Container.style.bottom = "0px";

            CodeSourceBView.Container.style.display = IStyle.DisplayEnum.none;
            CodeSourceBView.Container.AttachTo(CurrentDesigner.Content);

            CodeSourceBTab.Deactivated +=
                delegate
                {
                    CodeSourceBView.Container.style.display = IStyle.DisplayEnum.none;
                };

            CodeSourceBTab.Activated +=
                delegate
                {

                    CodeSourceBView.Container.style.display = IStyle.DisplayEnum.empty;
                };


            #endregion

            #region CodeSourceFormsDesignerTab
            var CodeSourceFormsDesignerTab =
                new SolutionFileDesignerTab
                {
                    Image = new RTA_mode_design(),
                    // all source code, not just html?
                    Text = "Designer"
                };


            var CodeSourceFormsDesignerTabView = new SolutionFileView();

            CodeSourceFormsDesignerTabView.Container.style.With(
                style =>
                {
                    style.position = IStyle.PositionEnum.absolute;
                    style.left = "0px";
                    style.right = "0px";
                    style.top = "0px";
                    style.bottom = "0px";

                    style.display = IStyle.DisplayEnum.none;
                }
            );

            new IHTMLDiv().With(
                div =>
                {
                    div.style.position = IStyle.PositionEnum.absolute;
                    div.style.left = "16px";
                    div.style.top = "16px";
                    div.style.width = "400px";
                    div.style.height = "300px";
                    div.style.backgroundColor = Color.FromGray(0xe0);
                    div.style.border = "1px solid gray";
                    div.AttachTo(CodeSourceFormsDesignerTabView.Container);
                }
            );


            CodeSourceFormsDesignerTabView.Container.AttachTo(CurrentDesigner.Content);

            CodeSourceFormsDesignerTab.Deactivated +=
                delegate
                {
                    CodeSourceFormsDesignerTabView.Container.style.display = IStyle.DisplayEnum.none;
                };

            CodeSourceFormsDesignerTab.Activated +=
                delegate
                {

                    CodeSourceFormsDesignerTabView.Container.style.display = IStyle.DisplayEnum.empty;
                };


            #endregion

            CurrentDesigner.Add(CodeSourceFormsDesignerTab);
            CurrentDesigner.Add(CodeSourceBTab);
            CurrentDesigner.Add(CodeSourceATab);




            var wLeftScrollable = new System.Windows.Forms.Form
            {
                BackColor = global::System.Drawing.Color.White,
                Text = "Toolbox",
                ControlBox = false,
                ShowIcon = false,
                AutoScroll = true
            };

            vv.Container.AttachTo(
                wLeftScrollable.GetHTMLTargetContainer()
            );

            //wLeftScrollable.Show();

            Split.Split.LeftScrollable.style.zIndex = 0;
            wLeftScrollable.AttachFormTo(Split.Split.LeftScrollable);


            //wLeftScrollable.PopupInsteadOfClosing();

            //Split.Split.LeftScrollable = (IHTMLDiv)(object)SolutionToolbox.body;
            Split.Split.RightScrollable = Viewer.Container;

            // ...





            #region dynamic content
            Func<IEnumerable<XElement>> GetPages = delegate
            {
                return from n in sln.ApplicationPage.DescendantsAndSelf()
                       let type = n.Attribute(SolutionBuilderInteractive.DataTypeAttribute)
                       where type != null
                       let id = n.Attribute("id")
                       where id != null
                       select n;
            };

            sln.Interactive.GenerateApplicationExpressions +=
                Add =>
                {


                    // page.PageContainer.ReplaceWith(
                    GetPages().WithEach(
                        k =>
                        {
                            var id = k.Attribute("id").Value;

                            if (id == "Page1")
                            {
                                Add(
                                    new StockReplaceWithNewPageExpression(id)
                                );
                            }

                            if (id == "UserControl1")
                            {
                                Add(
                                    new StockReplaceWithNewUserControlExpression(sln.Name + ".Components", id)
                                );
                            }

                            if (id == "Applet1")
                            {
                                Add(
                                    new StockReplaceWithNewAppletExpression(sln.Name + ".Components", id)
                                );
                            }

                            if (id == "Sprite1")
                            {
                                Add(
                                    new StockReplaceWithNewSpriteExpression(sln.Name + ".Components", id)
                                );
                            }

                            if (id == "AppletUserControl1")
                            {
                                Add(
                                    new StockReplaceWithNewAppletExpression(sln.Name + ".Components", id)
                                );
                            }
                        }
                    );
                };

            sln.Interactive.GenerateHTMLFiles +=
                Add =>
                {

                    GetPages().WithEach(
                        k =>
                        {
                            var id = k.Attribute("id").Value;

                            if (id == "Page1")
                            {
                                var __Content = new XElement(StockPageDefault.Page);


                                __Content.Element("head").Element("title").Value = id;

                                Add(
                                    new SolutionProjectHTMLFile
                                    {
                                        Name = "Design/" + id + ".htm",
                                        Content = __Content
                                    }
                                );
                            }
                        }
                     );
                };

            sln.Interactive.GenerateTypes +=
                Add =>
                {
                    GetPages().WithEach(
                        k =>
                        {
                            var id = k.Attribute("id").Value;

                            if (id == "UserControl1")
                            {
                                Add(
                                    new StockUserControlType(sln.Name + ".Components", id)
                                );
                            }

                            if (id == "Applet1")
                            {
                                Add(
                                    new StockAppletType(sln.Name + ".Components", id)
                                );
                            }

                            if (id == "Sprite1")
                            {
                                Add(
                                    new StockSpriteType(sln.Name + ".Components", id)
                                );
                            }

                            if (id == "AppletUserControl1")
                            {
                                var UserControl2 = new StockUserControlType(sln.Name + ".Components", "UserControl2");

                                Add(
                                    UserControl2
                                );

                                Add(
                                    new StockUserControlAppletType(sln.Name + ".Components", id, UserControl2)
                                );
                            }
                        }
                     );
                };
            #endregion


            var _Solution = new TreeNode(VistaTreeNodePage.Create);


            var _Project = _Solution.Add();

            var About = new About();

            #region UpdateFile1Text
            Action UpdateFile1Text =
                delegate
                {

                    if (CodeSourceBView.File != null)
                    {
                        File7Tab.Text = CodeSourceBView.File.Name.SkipUntilLastIfAny("/");
                    }
                    else
                    {
                        File7Tab.Text = sln.Name;
                    }


                };
            #endregion



            #region Update
            Action Update =
                delegate
                {
                    sln.Name = About.ProjectName.value;

                    UpdateFile1Text();

                    _Project.Clear();
                    UpdateTree(sln, CodeSourceBView, _Solution, _Project);
                };
            #endregion


            var PreviousVersion = default(string);

            #region HTMLDesigner.HTMLDesignerContent
            HTMLDesigner.HTMLDesignerContent.WhenContentReady(
                body =>
                {
                    if (PreviousVersion == null)
                    {
                        var x = new XElement(body.AsXElement());
                        var y = x.ToString();
                        PreviousVersion = y;
                    }

                    Action<bool> HTMLDesignerContentCheck =
                        DoUpdate =>
                        {
                            var x = new XElement(body.AsXElement());
                            var y = x.ToString();

                            if (PreviousVersion != y)
                            {
                                PreviousVersion = y;


                                sln.ApplicationPage = x;

                                // allow any blur causing action to complete first
                                // we get reselected for some odd reason, why?
                                new Timer(
                                    delegate
                                    {
                                        if (DoUpdate)
                                        {
                                            OutputWriteLine("Designer has caused an update.");
                                            Update();
                                        }
                                        else
                                        {
                                            OutputWriteLine("Designer will cause an update.");
                                        }

                                    }
                                ).StartTimeout(700);
                            }
                        };

                    var HTMLDesignerContentDirty = new Timer(
                        delegate
                        {
                            HTMLDesignerContentCheck(false);
                        }
                    );

                    HTMLDesigner.HTMLDesignerContent.contentWindow.onfocus +=
                        delegate
                        {
                            OutputWriteLine("Designer activated.");
                            //"focus".ToDocumentTitle();

                            //HTMLDesignerContentDirty.StartInterval(700);
                        };

                    HTMLDesigner.HTMLDesignerContent.contentWindow.onblur +=
                        delegate
                        {
                            //HTMLDesignerContentDirty.Stop();

                            OutputWriteLine("Designer deactivated.");
                            //"blur".ToDocumentTitle();
                            HTMLDesignerContentCheck(true);

                        };
                }
            );
            #endregion

            #region CodeSourceBView.FileChanged
            CodeSourceBView.FileChanged +=
                delegate
                {
                    UpdateFile1Text();


                    OutputWriteLine("Select: " + CodeSourceBView.File.Name);

                    CodeSourceFormsDesignerTab.TabElement.Hide();

                    // hack :)
                    if (CodeSourceBView.File.Name.EndsWith("/App.htm"))
                    {
                        // currently we only have one element :)

                        HTMLDesigner.HTMLDesignerTab.RaiseActivated();

                        HTMLDesigner.HTMLDesignerTab.TabElement.style.display = IStyle.DisplayEnum.inline_block;
                        HTMLDesigner.HTMLSourceTab.TabElement.style.display = IStyle.DisplayEnum.none;
                        CodeSourceATab.TabElement.style.display = IStyle.DisplayEnum.inline_block;
                        CodeSourceBTab.TabElement.style.display = IStyle.DisplayEnum.inline_block;

                        HTMLDesigner.HTMLDesignerContent.WhenContentReady(
                            body =>
                            {
                                HTMLDesigner.HTMLDesignerContent.contentWindow.focus();
                            }
                        );

                        // show the design/source buttons
                    }
                    else if (CodeSourceBView.File.Name.EndsWith(".sln"))
                    {
                        AboutTab.Activate();
                    }
                    else if (CodeSourceBView.File.Name.EndsWith(sln.Language.ProjectFileExtension))
                    {
                        AboutTab.Activate();
                    }
                    else if (CodeSourceBView.File.Name.EndsWith(sln.Language.CodeFileExtension))
                    {
                        // show type outline / member
                        CodeSourceBTab.RaiseActivated();

                        HTMLDesigner.HTMLDesignerTab.TabElement.style.display = IStyle.DisplayEnum.none;
                        HTMLDesigner.HTMLSourceTab.TabElement.style.display = IStyle.DisplayEnum.none;
                        CodeSourceATab.TabElement.style.display = IStyle.DisplayEnum.none;
                        CodeSourceBTab.TabElement.style.display = IStyle.DisplayEnum.inline_block;

                        CodeSourceBView.File.ContextType.BaseType.With(
                            BaseType =>
                            {
                                if (BaseType is KnownStockTypes.System.Windows.Forms.UserControl)
                                {
                                    CodeSourceFormsDesignerTab.TabElement.Show();
                                    CodeSourceFormsDesignerTab.RaiseActivated();

                                }

                                if (BaseType is KnownStockTypes.System.ComponentModel.Component)
                                {
                                    CodeSourceFormsDesignerTab.TabElement.Show();
                                    CodeSourceFormsDesignerTab.RaiseActivated();

                                }
                            }
                        );

                    }


                };
            #endregion


            //AddSaveButton(WorkspaceHeader, i => Save = i);

            About.ProjectName.value = sln.Name;
            About.ProjectName.onchange +=
                delegate
                {
                    OutputWriteLine("Project name has changed.");
                    Update();
                };



            Viewer.Content.Clear();
            Viewer.Content.Add(About.Container);
            Viewer.Content.Add(CurrentDesigner.Container);
            Viewer.Content.Add(OutputFileViewer.Container);

            AboutTab.WhenActivated(About.Container);
            File7Tab.WhenActivated(CurrentDesigner.Container);
            OutputTab.WhenActivated(OutputFileViewer.Container);



            Viewer.First().Activate();

            //var SolutionExplorer = new SolutionDockWindowPage();

            //SolutionExplorer.HeaderText.innerText = "Solution Explorer";
            //SolutionExplorer.Content.style.backgroundColor = Color.White;
            //SolutionExplorer.Content.style.padding = "2px";
            //SolutionExplorer.Content.ReplaceContentWith(_Solution.Container);


            var fSolutionExplorer = new System.Windows.Forms.Form
            {
                BackColor = global::System.Drawing.Color.White,
                Text = "Solution Explorer",
                ControlBox = false,
                ShowIcon = false

            };

            EditorTreeSplit.Split.RightScrollable.style.zIndex = 0;
            EditorTreeSplit.Split.RightScrollable.style.position = IStyle.PositionEnum.relative;

            fSolutionExplorer.AttachFormTo(EditorTreeSplit.Split.RightScrollable);

            _Solution.Container.AttachTo(fSolutionExplorer.GetHTMLTargetContainer());

            _Solution.Container.style.overflow = IStyle.OverflowEnum.auto;
            _Solution.Container.style.height = "100%";
            _Solution.Container.style.backgroundColor = Color.White;

            //EditorTreeSplit.Split.RightContainer = (IHTMLDiv)(object)SolutionExplorer.Container;

            EditorTreeSplit.Container.AttachTo(Workspace);

            //CurrentDesigner.First().RaiseActivated();

            Update();

            #region CreateLanguageButton
            Action<IHTMLImage, string, SolutionProjectLanguage, string> CreateLanguageButton =
                (Icon, Text, Language, Name) =>
                {
                    var span = new IHTMLSpan(Text);

                    span.style.marginLeft = "0.7em";
                    span.style.marginRight = "0.7em";

                    new IHTMLButton { Icon /*, span */ }.AttachTo(WorkspaceHeaderTab1).With(
                        btn =>
                        {
                            btn.onclick +=
                                delegate
                                {
                                    sln.Language = Language;
                                    sln.Name = Language.LanguageSpelledName.Replace(" ", "") + "Project1";
                                    Update();
                                };

                            //btn.style.display = IStyle.DisplayEnum.block;
                        }
                    );
                };
            #endregion


            CreateLanguageButton(new VisualCSharpProject(), "C#", KnownLanguages.VisualCSharp, "VisualCSharpProject1");
            CreateLanguageButton(new VisualFSharpProject(), "F#", KnownLanguages.VisualFSharp, "VisualFSharpProject1");
            CreateLanguageButton(new VisualBasicProject(), "Visual Basic", KnownLanguages.VisualBasic, "VisualBasicProject1");

            var ListOfCreateProjectTypeButton = new List<IHTMLButton>();

            #region CreateProjectTypeButton
            Action<string, Action> CreateProjectTypeButton =
              (Text, Handler) =>
              {
                  var span = new IHTMLSpan(Text);

                  span.style.marginLeft = "0.7em";
                  span.style.marginRight = "0.7em";

                  new IHTMLButton { span }.AttachTo(WorkspaceHeaderTab2).With(
                      btn =>
                      {
                          ListOfCreateProjectTypeButton.Add(btn);

                          btn.onclick +=
                              delegate
                              {
                                  ListOfCreateProjectTypeButton.WithEach(n => n.disabled = true);

                                  Handler();
                              };

                          //btn.style.display = IStyle.DisplayEnum.block;
                      }
                  );
              };
            #endregion

            #region ToSpecificProjectType
            Action<string, Action> ToSpecificProjectType =
                (Text, Handler) =>
                {
                    CreateProjectTypeButton(Text,
                        delegate
                        {
                            Handler();


                            HTMLDesigner.HTMLDesignerContent.WhenDocumentReady(
                                document =>
                                {
                                    document.WithContent(sln.ApplicationPage);
                                    // we should now also lock the designer!
                                    document.DesignMode = false;
                                }
                            );

                            Update();
                        }
                    );
                };
            #endregion

            #region Avalon, Forms
            ToSpecificProjectType("Avalon App",
                delegate
                {
                    sln.WithCanvas();
                }
            );


            ToSpecificProjectType("Avalon Flash App",
               delegate
               {
                   sln.WithCanvasAdobeFlash();

               }
            );

            ToSpecificProjectType("Forms App",
                delegate
                {
                    sln.WithForms();
                }
            );


            ToSpecificProjectType("Forms Applet App",
               delegate
               {
                   sln.WithFormsApplet();

               }
            );
            #endregion

            ToSpecificProjectType("Flash App",
              delegate
              {
                  sln.WithAdobeFlash();
              }
            );

            ToSpecificProjectType("Flash Camera App",
                delegate
                {
                    sln.WithAdobeFlashCamera();
                }
              );

            ToSpecificProjectType("Flash Flare3D App",
               delegate
               {
                   sln.WithAdobeFlashWithFlare3D();
               }
             );

            ToSpecificProjectType("Applet App",
              delegate
              {
                  sln.WithJavaApplet();
              }
            );
        }
示例#30
0
        public void Tick(Timer t)
        {
            if (Index < 0)
            {
                if (Index == -1)
                {
                    this.Control.Dispose();
                    Index--;
                }

                return;
            }

            if (this.ReverseAnimation)
                this.Cache[this.Cache.Length - 1 - Index].ToBackground(this.Control);
            else
                this.Cache[Index].ToBackground(this.Control);

            Index++;

            if (Index > this.Cache.Length - 1)
            {
                if (OnlyOnce)
                {
                    Index = -1;
                }
                else
                {
                    if (this.WhenDone != null)
                    {
                        this.WhenDone();
                    }

                    Index = 0;
                }
            }
        }
示例#31
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(IApp page)
        {
            // localStorage not available on android webview!
            //E/Web Console( 3751): Uncaught TypeError: Cannot set property '20130329 Hello world' of null at http://192.168.1.107:25459/view-source:32300


            FormStyler.AtFormCreated = FormStylerLikeFloat.LikeFloat;

            new GrayPatternBackground.HTML.Images.FromAssets.background().ToDocumentBackground();

            Console.WriteLine("serial 57770");

            "My Notez (loading...)".ToDocumentTitle();


            service.AtPendingActions +=
                count =>
                {
                    if (service.ServicePending.ElapsedMilliseconds > 500)
                    {
                        if (service.ServicePending.ElapsedMilliseconds > 4000)
                        {
                            "My Notez (offline)".ToDocumentTitle();
                            return;
                        }

                        "My Notez (pending)".ToDocumentTitle();
                        return;
                    }

                    "My Notez".ToDocumentTitle();
                };

            Native.window.onbeforeunload +=
                e =>
                {
                    if (service.ServicePending.IsRunning)
                        e.Text = "The changes made here have not yet made it to the server.";
                };

            var storage = new MyLocalStorage
            {

                AtRemove =
                    x => service.remove_LocalStorage(x),

                AtSetItem =
                    (key, value) =>
                    {
                        service.set_LocalStorage(key, value);
                    }
            };

            Console.WriteLine("Do we have localStorage? [2]");

            Native.window.localStorage.With(
                localStorage =>
                {
                    Console.WriteLine("This browser has localStorage. Lets sync with that. [2]");

                    for (uint i = 0; i < localStorage.length; i++)
                    {
                        var key = localStorage.key(i);
                        var value = localStorage[key];

                        storage[key] = value;
                    }

                    // jsc why aint ths working?
                    //storage.AtRemove += localStorage.removeItem;
                    storage.AtRemove += key => localStorage.removeItem(key);
                    storage.AtSetItem += (key, value) => { localStorage[key] = value; };

                }
            );

            #region done
            Action done = delegate
                {



                    var hh = new HorizontalSplit
                    {
                        Minimum = 0.05,
                        Maximum = 0.95,
                        Value = 0.4,
                    };


                    hh.Container.AttachToDocument();
                    hh.Container.style.position = IStyle.PositionEnum.absolute;
                    hh.Container.style.left = "0px";
                    hh.Container.style.top = "0px";
                    hh.Container.style.right = "0px";
                    hh.Container.style.bottom = "0px";

                    hh.Split.Splitter.style.backgroundColor = "rgba(0,0,0,0.0)";


                    //var vv = new VerticalSplit
                    var f = new Form
                    {
                        StartPosition = FormStartPosition.Manual,
                        SizeGripStyle = SizeGripStyle.Hide,

                        Text = "Entries"
                    };

                    var f1 = new Form
                    {
                        StartPosition = FormStartPosition.Manual,
                        SizeGripStyle = SizeGripStyle.Hide,

                        Text = "My Files"
                    };

                    f1.Show();


                    var f2 = new Form
                    {
                        StartPosition = FormStartPosition.Manual,
                        SizeGripStyle = SizeGripStyle.Hide,

                        Text = "..."
                    };

                    f2.Show();

                    var w = new WebBrowser
                    {
                        Dock = DockStyle.Fill
                    };
                    w.GetHTMLTarget().name = "viewer";
                    w.AttachTo(f2);

                    w.Navigating +=
                        delegate
                        {
                            f2.Text = "Navigating";

                        };

                    w.Navigated +=
                       delegate
                       {
                           if (w.Url.ToString() == "about:blank")
                           {

                               f2.Text = "...";


                               return;
                           }

                           //ff.Text = w.DocumentTitle;
                           f2.Text = Native.window.unescape(
                               w.Url.ToString().SkipUntilLastIfAny("/").TakeUntilLastIfAny(".")
                               );



                       };

                    Native.window.requestAnimationFrame +=
                        delegate
                        {

                            var layout = new Abstractatech.JavaScript.FileStorage.HTML.Pages.App();

                            layout.Container.AttachTo(f1.GetHTMLTargetContainer());

                            Abstractatech.JavaScript.FileStorage.ApplicationContent.Target = w.GetHTMLTarget().name;


                            new Abstractatech.JavaScript.FileStorage.ApplicationContent(
                                layout,
                                service.service
                            );

                        };


                    var LeftScrollable = new IHTMLDiv { className = "SidebarForButtons" }.AttachTo(f.GetHTMLTargetContainer());

                    LeftScrollable.style.backgroundColor = "white";

                    var CreateNew = new IHTMLButton { innerText = "+ create new", className = "SidebarButton" }.AttachTo(
                      LeftScrollable
                     );

                    var ff = new Form
                    {
                        StartPosition = FormStartPosition.Manual,
                        SizeGripStyle = SizeGripStyle.Hide

                    };



                    f.Show();
                    ff.Show();




                    //var text = new TextEditor(hh.Split.RightScrollable);
                    var text = new TextEditor(ff.GetHTMLTargetContainer());

                    text.ContainerForBorders.style.border = "";

                    text.Control.style.position = IStyle.PositionEnum.absolute;
                    text.Control.style.left = "0px";
                    text.Control.style.top = "0px";
                    text.Control.style.right = "0px";
                    text.Control.style.bottom = "0px";


                    //Native.Window.onresize +=
                    //    delegate
                    //    {
                    //        var TopToolbarHeight = text.TopToolbar.clientHeight;

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

                    //        text.DesignerContainer.style.top = (TopToolbarHeight + 4) + "px";
                    //        text.SourceContainer.style.top = (TopToolbarHeight + 4) + "px";

                    //    };


                    #region DesignerContainer
                    text.DesignerContainer.style.position = IStyle.PositionEnum.absolute;
                    text.DesignerContainer.style.left = "0px";
                    text.DesignerContainer.style.top = "3em";
                    text.DesignerContainer.style.right = "0px";
                    text.DesignerContainer.style.bottom = "3em";
                    text.DesignerContainer.style.height = "";

                    text.Frame.style.position = IStyle.PositionEnum.absolute;
                    text.Frame.style.left = "0px";
                    text.Frame.style.top = "0px";
                    //text.Frame.style.right = "0px";
                    //text.Frame.style.bottom = "0px";
                    text.Frame.style.width = "100%";
                    text.Frame.style.height = "100%";
                    #endregion


                    #region SourceContainer
                    text.SourceContainer.style.position = IStyle.PositionEnum.absolute;
                    text.SourceContainer.style.left = "0px";
                    text.SourceContainer.style.top = "3em";
                    text.SourceContainer.style.right = "0px";
                    text.SourceContainer.style.bottom = "3em";
                    text.SourceContainer.style.height = "";

                    text.TextArea.style.position = IStyle.PositionEnum.absolute;
                    text.TextArea.style.left = "0px";
                    text.TextArea.style.top = "0px";
                    //text.Frame.style.right = "0px";
                    //text.Frame.style.bottom = "0px";
                    text.TextArea.style.width = "100%";
                    text.TextArea.style.height = "100%";
                    #endregion

                    text.BottomToolbarContainer.style.position = IStyle.PositionEnum.absolute;
                    text.BottomToolbarContainer.style.left = "0px";
                    text.BottomToolbarContainer.style.right = "0px";
                    text.BottomToolbarContainer.style.bottom = "0px";

                    var oldtitle = "";

                    Action DoRefresh = delegate { };

                    #region DoCreateNew
                    Action DoCreateNew = delegate
                    {
                        oldtitle = "";

                        #region default text
                        var now = DateTime.Now;


                        var yyyy = now.Year;
                        var mm = now.Month;
                        var dd = now.Day;


                        var yyyymmdd = yyyy
                            + mm.ToString().PadLeft(2, '0')
                            + dd.ToString().PadLeft(2, '0');

                        string header = yyyymmdd + @" New Header " + storage.Keys.Count();


                        text.InnerHTML = @"
<div><font face='Verdana' size='5' color='#0000fc'>" + header + @"</font></div><div><br /></div><blockquote style='margin: 0 0 0 40px; border: none; padding: 0px;'></blockquote><font face='Verdana'>This is your content.</font>
            ";
                        #endregion



                        DoRefresh();
                    };

                    CreateNew.onclick +=
                        delegate
                        {
                            DoCreateNew();
                        };
                    #endregion




                    var buttons = new List<IHTMLButton>();

                    Action EitherCreateNewOrSelectFirst = delegate
                    {
                        if (buttons.Count == 0)
                        {
                            DoCreateNew();
                        }
                        else
                        {
                            if (buttons.Any(k => k.innerText == oldtitle))
                            {
                                //already selected
                            }
                            else
                            {
                                oldtitle = buttons.First().innerText;

                                text.InnerHTML = storage[oldtitle];
                            }
                        }
                    };


                    #region Remove this document
                    var remove = text.AddButton(null, "Remove this document",
                          delegate
                          {
                              var button = buttons.FirstOrDefault(k => k.innerText == oldtitle);

                              if (button == null)
                                  return;

                              //Native.Window.localStorage.removeItem(button.innerText);
                              storage.Remove(button.innerText);


                              button.Orphanize();
                              buttons.Remove(button);

                              EitherCreateNewOrSelectFirst();
                          }
                      );
                    #endregion


                    IHTMLElement remove_element = remove;
                    remove_element.style.Float = IStyle.FloatEnum.right;

                    text.BottomToolbar.appendChild(remove_element);

                    #region new_SidebarButton
                    Func<IHTMLButton> new_SidebarButton =
                        delegate
                        {
                            var button = new IHTMLButton { className = "SidebarButton" }.AttachTo(
                                           LeftScrollable
                                        );

                            button.onclick +=
                                delegate
                                {
                                    oldtitle = "";
                                    text.InnerHTML = storage[button.innerText];
                                    DoRefresh();

                                };

                            button.oncontextmenu +=
                               e =>
                               {
                                   e.preventDefault();

                                   storage.Remove(button.innerText);


                                   button.Orphanize();
                                   buttons.Remove(button);

                                   EitherCreateNewOrSelectFirst();
                               };

                            buttons.Add(button);

                            return button;
                        };
                    #endregion

                    #region DoRefresh
                    DoRefresh = delegate
                   {
                       // what has changed
                       // text not default anymore?
                       // title change?


                       // document unloaded?
                       if (text.Document == null)
                           return;

                       var xml = text.Document.body.AsXElement();

                       // script: error JSC1000: No implementation found for this native method, please implement [static System.String.IsNullOrWhiteSpace(System.String)]

                       xml.Elements().FirstOrDefault(k => !string.IsNullOrWhiteSpace(k.Value)).With(
                           TitleElement =>
                           {
                               // take no action for no title
                               if (string.IsNullOrWhiteSpace(TitleElement.Value))
                                   return;

                               // is there a buttn with old title?


                               var button = buttons.FirstOrDefault(
                                   k =>
                                   {
                                       if (oldtitle == "")
                                       {
                                           return k.innerText == TitleElement.Value;
                                       }

                                       return k.innerText == oldtitle;
                                   }
                               );

                               if (button == null)
                               {
                                   button = new_SidebarButton();
                               }

                               button.innerText = TitleElement.Value;

                               buttons.WithEach(
                                   x => x.setAttribute("data-active", x == button)
                               );


                               if (oldtitle != "")
                               {
                                   if (oldtitle != TitleElement.Value)
                                       storage.Remove(oldtitle);


                               }

                               ff.Text = TitleElement.Value;

                               // src="http://192.168.1.100:5763/

                               var innerHTML = text.InnerHTML;

                               var href = Native.Document.location.href.TakeUntilLastOrEmpty("/");

                               // keep only relative paths to current host
                               var xinnerHTML = innerHTML.Replace("src=\"" + href + "/", "src=\"/");

                               if (innerHTML != xinnerHTML)
                               {
                                   text.InnerHTML = xinnerHTML;
                               }

                               storage[TitleElement.Value] = xinnerHTML;
                               oldtitle = TitleElement.Value;
                               //Console.WriteLine("TitleElement: " + TitleElement.Value);
                           }
                       );

                       // whats the title?
                   };
                    #endregion



                    foreach (var button_text in storage.Keys)
                    {
                        new_SidebarButton().innerText = button_text;
                    }



                    new ScriptCoreLib.JavaScript.Runtime.Timer(
                        t =>
                        {
                            DoRefresh();



                        }
                    ).StartInterval(500);


                    EitherCreateNewOrSelectFirst();








                    #region AtResize
                    Action AtResize = delegate
                    {
                        Native.Document.getElementById("feedlyMiniIcon").Orphanize();

                        Native.Document.body.style.minWidth = "";

                        //if (ff.GetHTMLTarget().parentNode == null)
                        //{
                        //    Native.Window.scrollTo(0, 0);
                        //    f.MoveTo(8, 8).SizeTo(Native.Window.Width - 16, Native.Window.Height - 16);

                        //    return;
                        //}

                        //if (f.GetHTMLTarget().parentNode == null)
                        //{
                        //    Native.Window.scrollTo(0, 0);
                        //    ff.MoveTo(8, 8).SizeTo(Native.Window.Width - 16, Native.Window.Height - 16);

                        //    return;
                        //}

                        //if (Native.Window.Width < 1024)
                        //{
                        //    Native.Document.body.style.minWidth = (Native.Window.Width * 2) + "px";


                        //    f.MoveTo(8, 8).SizeTo(Native.Window.Width - 16, Native.Window.Height - 16);

                        //    ff.MoveTo(Native.Window.Width + 8, 8).SizeTo(Native.Window.Width - 16, Native.Window.Height - 16);

                        //    // already scrolled...
                        //    if (w.Url.ToString() != "about:blank")
                        //        // docked?
                        //        if (ff.GetHTMLTarget().parentNode != null)
                        //            Native.Window.scrollTo(ff.Left - 8, ff.Top - 8);

                        //    return;
                        //}




                        f.MoveTo(16, 16).SizeTo(hh.LeftContainer.clientWidth - 32, Native.window.Height / 3 - 16 - 4);
                        f1.MoveTo(16, Native.window.Height / 3 + 4).SizeTo(hh.LeftContainer.clientWidth - 32, Native.window.Height / 3 - 8);
                        f2.MoveTo(16, Native.window.Height / 3 * 2 + 4).SizeTo(hh.LeftContainer.clientWidth - 32, Native.window.Height / 3 - 16);


                        ff.MoveTo(
                            Native.window.Width - hh.RightContainer.clientWidth + 16

                            , 16).SizeTo(hh.RightContainer.clientWidth - 32, Native.window.Height - 32);

                        //Console.WriteLine("LeftContainer " + new { hh.LeftContainer.clientWidth });
                        //Console.WriteLine("RightContainer " + new { hh.RightContainer.clientWidth });
                    };

                    hh.ValueChanged +=
                  delegate
                  {
                      AtResize();
                  };

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

                    Native.window.requestAnimationFrame +=
                delegate
                {
                    AtResize();
                };
                    #endregion

                    ff.PopupInsteadOfClosing(SpecialNoMovement: true, NotifyDocked: AtResize);
                    f.PopupInsteadOfClosing(SpecialNoMovement: true, NotifyDocked: AtResize);
                    f1.PopupInsteadOfClosing(SpecialNoMovement: true, NotifyDocked: AtResize);
                    f2.PopupInsteadOfClosing(SpecialNoMovement: true, NotifyDocked: AtResize);


                };
            #endregion

            var tt = default(ScriptCoreLib.JavaScript.Runtime.Timer);

            Action done_timeout = delegate
            {
                if (done == null)
                    return;

                tt.Stop();
                done();
                done = null;
            };


            service.get_LocalStorage(
                //add_localStorage: (key, value) => Native.Window.localStorage[key] = value,
                add_localStorage:
                    (key, value) =>
                    {
                        // what if we are resuming from offline edit.
                        // merge?


                        // keep the one we got from localStorage, because it has longer entry?
                        if (storage[key].Length > value.Length)
                            return;

                        storage[key] = value;
                    },

                done: done_timeout
            );


            // either server responds in 2000 or we consider us offline...
            tt = new ScriptCoreLib.JavaScript.Runtime.Timer(
                delegate
                {
                    done_timeout();
                }
            );

            tt.StartTimeout(3000);

        }