コード例 #1
0
            // dynamic does not work in static yet?
            //static 
            void InitializeContent()
        {
            floorplan = new Floorplan();






            Action<string, double, double, double, double, double, double, double, double, double> buildCube =
                (colour, w, h, d, x, y, z, rx, ry, rz) =>
                {
                    new cube(colour, w, h, d, x, y, z, rx, ry, rz);

                };



            var zoom = 4;
            var zz = 60;
            var low = -500;

            var __index = 0;

            #region CreateFromFloorplan
            Action CreateFromFloorplan = delegate
            {
                foreach (var item in floorplan.Controls)
                {
                    (item as DeskCube).With(
                        f =>
                        {


                            var cubeheight = Math.Max(300, f.CubeHeight);
                            var z = 0;
                            var cubetex = "rgba(0,0,0,0.1)";

                            if (f.LeftWallSource != null)
                                if (f.LeftWallSource.StartsWith("#cloud"))
                                {
                                    z = low;
                                    cubetex = "";
                                }

                            if (f.WallSourceRight != null)
                                if (f.WallSourceRight.StartsWith("#cloud"))
                                {
                                    z = low;
                                    cubetex = "";
                                }

                            if (f.WallSourceTop != null)
                                if (f.WallSourceTop.StartsWith("#cloud"))
                                {
                                    z = low;
                                    cubetex = "";
                                }

                            if (f.WallSourceBottom != null)
                                if (f.WallSourceBottom.StartsWith("#cloud"))
                                {
                                    z = low;
                                    cubetex = "";
                                }

                            new cube(
                                cubetex,

                                 //w, h, d, x, y, z, rx, ry, rz
                                f.Width * zoom,

                                f.Height * zoom,

                                cubeheight / 4 * zoom,
                                //0,

                                -f.Right * zoom,

                                f.Top * zoom,

                                -(cubeheight / 4 * zoom) + zz - z * zoom,

                                //-250, 

                                0, 0, 0
                            ).With(
                                cube =>
                                {

                                    #region LoadContent
                                    Action<IHTMLDiv, string> LoadContent =
                                        (westContainer, src) =>
                                        {
                                            if (src == "#window" || src == "#webfiles")
                                            {
                                                var morespace = new IHTMLDiv().AttachTo(westContainer);


                                                // 3by3 grid
                                                morespace.style.position = IStyle.PositionEnum.absolute;
                                                morespace.style.top = -westContainer.clientHeight + "px";
                                                morespace.style.left = 0 + "px";
                                                morespace.style.width = westContainer.clientWidth + "px";
                                                morespace.style.height = westContainer.clientHeight + "px";

                                                // 3D DOCK
                                                var ff = new Form { Text = "Gallery #" + __index };

                                                ff.StartPosition = FormStartPosition.Manual;
                                                ff.Show();
                                                ff.Left = 8;

                                                ff.Top = westContainer.clientHeight + -27;

                                                ff.Width = westContainer.clientWidth - 16;
                                                ff.Height = westContainer.clientHeight + 27 - 8;

                                                ff.GetHTMLTarget().AttachTo(morespace);
                                                ff.GetHTMLTarget().className = "nolock";

                                                var ffw = new WebBrowser { Dock = DockStyle.Fill };

                                                ffw.AttachTo(ff);

                                                ffw.Navigate(

                                                    Native.Document.location.href + src + __index
                                                    );

                                                __index++;

                                                ff.PopupInsteadOfClosing(
                                                    SpecialNoMovement: true
                                                );


                                                return;
                                            }

                                            new IHTMLIFrame { allowFullScreen = true, src = src, frameBorder = "0" }.AttachTo(westContainer).With(
                                                iframe =>
                                                {
                                                    iframe.style.position = IStyle.PositionEnum.absolute;
                                                    iframe.style.left = "0px";
                                                    iframe.style.top = "0px";
                                                    iframe.style.width = "10%";
                                                    iframe.style.height = "10%";
                                                    iframe.style.transform = "scale(10.0)";
                                                    iframe.style.transformOrigin = "0% 0%";
                                                }
                                            );

                                            // disable mouse
                                            new IHTMLDiv { }.AttachTo(westContainer).With(
                                                 overlay =>
                                                 {
                                                     overlay.style.position = IStyle.PositionEnum.absolute;
                                                     overlay.style.left = "0px";
                                                     overlay.style.top = "0px";
                                                     overlay.style.width = "100%";
                                                     overlay.style.height = "100%";

                                                     overlay.style.backgroundColor = "red";
                                                     overlay.style.Opacity = 0;
                                                 }
                                             );
                                        };
                                    #endregion



                                    #region WallSourceRight
                                    if (!string.IsNullOrEmpty(f.WallSourceBottom))
                                        new IHTMLDiv { }.AttachTo(cube.south.node).With(
                                           westContainer =>
                                           {

                                               //innerText = f.LeftWallSource
                                               //btn.className = "nolock";


                                               //westContainer.style.transform = "rotateZ(-90deg)";
                                               westContainer.style.transformOrigin = "0% 0%";

                                               westContainer.style.position = IStyle.PositionEnum.absolute;
                                               westContainer.style.width = cube.south.node.clientWidth + "px";
                                               westContainer.style.left = "0px";
                                               westContainer.style.top = "0px";
                                               westContainer.style.height = cube.south.node.clientHeight + "px";


                                               if (f.LeftWallSourceAutoLoad)
                                               {
                                                   LoadContent(westContainer, f.WallSourceBottom);
                                               }

                                           }
                                       );
                                    #endregion
                                    #region WallSourceRight
                                    if (!string.IsNullOrEmpty(f.WallSourceTop))
                                        new IHTMLDiv { }.AttachTo(cube.north.node).With(
                                           westContainer =>
                                           {

                                               //innerText = f.LeftWallSource
                                               //btn.className = "nolock";


                                               //westContainer.style.transform = "rotateZ(-90deg)";
                                               westContainer.style.transformOrigin = "0% 0%";

                                               westContainer.style.position = IStyle.PositionEnum.absolute;
                                               westContainer.style.width = cube.north.node.clientWidth + "px";
                                               westContainer.style.left = "0px";
                                               westContainer.style.top = "0px";
                                               westContainer.style.height = cube.north.node.clientHeight + "px";



                                               if (f.LeftWallSourceAutoLoad)
                                               {
                                                   LoadContent(westContainer, f.WallSourceTop);

                                               }

                                           }
                                       );
                                    #endregion

                                    #region WallSourceRight
                                    if (!string.IsNullOrEmpty(f.WallSourceRight))
                                        new IHTMLDiv { }.AttachTo(cube.east.node).With(
                                           westContainer =>
                                           {

                                               //innerText = f.LeftWallSource
                                               //btn.className = "nolock";


                                               westContainer.style.transform = "rotateZ(-90deg)";
                                               westContainer.style.transformOrigin = "0% 0%";

                                               westContainer.style.position = IStyle.PositionEnum.absolute;
                                               westContainer.style.width = cube.east.node.clientHeight + "px";
                                               westContainer.style.top = cube.east.node.clientHeight + "px";
                                               westContainer.style.height = cube.east.node.clientWidth + "px";



                                               if (f.LeftWallSourceAutoLoad)
                                               {
                                                   LoadContent(westContainer, f.WallSourceRight);

                                               }

                                           }
                                       );
                                    #endregion

                                    #region LeftWallSource
                                    if (!string.IsNullOrEmpty(f.LeftWallSource))
                                        new IHTMLDiv { }.AttachTo(cube.west.node).With(
                                            westContainer =>
                                            {

                                                //innerText = f.LeftWallSource
                                                //btn.className = "nolock";


                                                westContainer.style.transform = "rotateZ(90deg)";
                                                westContainer.style.transformOrigin = "0% 0%";

                                                westContainer.style.position = IStyle.PositionEnum.absolute;
                                                westContainer.style.width = cube.west.node.clientHeight + "px";
                                                westContainer.style.left = cube.west.node.clientWidth + "px";
                                                westContainer.style.height = cube.west.node.clientWidth + "px";

                                                if (f.LeftWallSourceAutoLoad)
                                                {
                                                    LoadContent(westContainer, f.LeftWallSource);

                                                }

                                            }
                                        );
                                    #endregion


                                }
                            );

                        }
                    );
                    (item as Floor).With(
                        f =>
                        {

                            window.viewport.camera.position.x = (f.Left + f.Width / 2) * zoom;
                            window.viewport.camera.position.y = -(f.Top + f.Height / 2) * zoom;

                            buildCube("white",

                                 //w, h, d, x, y, z, rx, ry, rz
                                f.Width * zoom,

                                f.Height * zoom,

                                10,
                                //0,

                                -f.Right * zoom, f.Top * zoom,

                                0 - low * zoom + zz,
                                //-250, 

                                0, 0, 0);

                        }
                    );
                }
            };

            CreateFromFloorplan();

            //zz += 300;

            //CreateFromFloorplan();
            #endregion


            //avoid out of memory - elements will go missing
            //zz += 300;

            //CreateFromFloorplan();







            #region onkeydown
            Native.Document.body.onkeydown += e =>
            {
                //Console.WriteLine(new { e.KeyCode });

                if (e.KeyCode == (int)Keys.W)
                    window.keyState.forward = true;
                if (e.KeyCode == (int)Keys.S)
                    window.keyState.backward = true;
                if (e.KeyCode == (int)Keys.A)
                    window.keyState.strafeleft = true;
                if (e.KeyCode == (int)Keys.D)
                    window.keyState.straferight = true;

                if (AfterKeystateChange != null)
                    AfterKeystateChange();
            };

            Native.Document.body.onkeyup += e =>
            {
                if (e.KeyCode == (int)Keys.W)
                    window.keyState.forward = false;
                if (e.KeyCode == (int)Keys.S)
                    window.keyState.backward = false;

                if (e.KeyCode == (int)Keys.A)
                    window.keyState.strafeleft = false;
                if (e.KeyCode == (int)Keys.D)
                    window.keyState.straferight = false;

                if (AfterKeystateChange != null)
                    AfterKeystateChange();
            };
            #endregion

            Func<INode, bool> isnolock =
                p =>
                {
                    var nolock = false;

                    while (p != Native.Document.body)
                    {
                        if (((IHTMLElement)p).className == "nolock")
                            nolock = true;

                        p = p.parentNode;
                    }

                    return nolock;
                };

            #region onmousemove
            Native.Document.body.tabIndex = 101;
            Native.Document.body.onmousedown +=
                e =>
                {
                    var nolock = isnolock(e.Element);
                    if (nolock)
                        return;

                    e.PreventDefault();
                    Native.Document.body.focus();
                    Native.Document.body.requestPointerLock();
                };

            Native.Document.body.onmousemove +=
                e =>
                {
                    if (Native.Document.pointerLockElement == Native.Document.body)
                    {
                        var x = window.viewport.camera.rotation.x;
                        x -= e.movementY / 2;

                        x = Math.Min(x, -60).Max(-120);

                        //Console.WriteLine(new { x });
                        window.viewport.camera.rotation.x = x;


                        var z = window.viewport.camera.rotation.z;
                        z += e.movementX / 2;


                        window.viewport.camera.rotation.z = z;

                        if (AfterCameraRotationChange != null)
                            AfterCameraRotationChange();
                    }
                    else
                    {
                        var nolock = isnolock(e.Element);

                        if (nolock)
                            Native.Document.body.style.cursor = IStyle.CursorEnum.auto;
                        else
                            Native.Document.body.style.cursor = IStyle.CursorEnum.move;
                    }
                };


            Native.Document.body.onmouseup +=
                 e =>
                 {
                     if (Native.Document.pointerLockElement == Native.Document.body)
                     {
                         Native.Document.exitPointerLock();
                     }
                 };
            #endregion




            #region loop
            Action loop = delegate
            {
                // is external target working bot ways?
                //window.speed = window.speed;

                //Console.WriteLine(new { window.keyState.forward });

                #region speed
                if (window.keyState.backward)
                {
                    if (window.speed > -window.maxSpeed)
                        window.speed -= window.accel;
                }
                else if (window.keyState.forward)
                {
                    if (window.speed < window.maxSpeed)
                        window.speed += window.accel;
                }
                else if (window.speed > 0)
                {
                    window.speed = Math.Max(window.speed - window.accel, 0);
                }
                else if (window.speed < 0)
                {
                    window.speed = Math.Max(window.speed + window.accel, 0);
                }
                else
                {
                    window.speed = 0;
                }
                #endregion


                #region strafespeed
                if (window.keyState.straferight)
                {
                    if (window.strafespeed > -window.maxSpeed)
                        window.strafespeed -= window.accel;
                }
                else if (window.keyState.strafeleft)
                {
                    if (window.strafespeed < window.maxSpeed)
                        window.strafespeed += window.accel;
                }
                else if (window.strafespeed > 0)
                {
                    window.strafespeed = Math.Max(window.strafespeed - window.accel, 0);
                }
                else if (window.strafespeed < 0)
                {
                    window.strafespeed = Math.Max(window.strafespeed + window.accel, 0);
                }
                else
                {
                    window.strafespeed = 0;
                }
                #endregion


                // sideway
                {

                    var xo = Math.Sin(window.viewport.camera.rotation.z * 0.0174532925);
                    var yo = Math.Cos(window.viewport.camera.rotation.z * 0.0174532925);

                    window.viewport.camera.position.x -= xo * window.speed;
                    window.viewport.camera.position.y -= yo * window.speed;
                }

                {
                    var xo = Math.Sin(window.viewport.camera.rotation.z * 0.0174532925 - 3.14 / 2);
                    var yo = Math.Cos(window.viewport.camera.rotation.z * 0.0174532925 - 3.14 / 2);

                    window.viewport.camera.position.x -= xo * window.strafespeed;
                    window.viewport.camera.position.y -= yo * window.strafespeed;
                }

                window.viewport.camera.update();


            };


            loop.AtAnimationFrame();
            #endregion

        }
コード例 #2
0
        /// <summary>
        /// This is a javascript application.
        /// </summary>
        /// <param name="document">HTML document rendered by the web server which can now be enhanced.</param>
        public Application(IApp document)
        {
            // 
            //document.body.AsXElement().Elements("script").Remove();
            //document.body.AsXElement().Elements("script").WithEach(k => k.Remove());

            var f = new Form { Text = "Visual Editor" };

            f.PopupInsteadOfClosing(HandleFormClosing: true);

            f.Width = 600;

            var diagnostics = new IHTMLDiv().AttachTo(document.body.parentNode);
            //var diagnostics = new IHTMLBody().AttachTo(Native.document.body.parentNode);

            diagnostics.style.backgroundColor = "rgba(0, 0, 0, 0)";
            diagnostics.style.position = IStyle.PositionEnum.absolute;
            diagnostics.style.overflow = IStyle.OverflowEnum.hidden;

            diagnostics.style.left = "0px";
            diagnostics.style.top = "-100%";
            diagnostics.style.width = "100%";
            diagnostics.style.height = "100%";



            f.Show();
            f.GetHTMLTarget().AttachTo(diagnostics);

            //Uncaught TypeError: Cannot call method 'write' of null 
            var editor = new TextEditor(f.GetHTMLTargetContainer());

            var snd = new HTML.Audio.FromAssets.SAMPLES036();
            snd.load();

            var snd2 = new HTML.Audio.FromAssets.Hammertime();
            snd2.load();


            Action reverse = delegate { };

            Action Hide =
                delegate
                {
                    //
                    (document.body.style as dynamic).webkitFilter = "";

                    diagnostics.style.top = "-100%";
                    diagnostics.style.backgroundColor = "rgba(0, 0, 0, 0)";

                    snd2.play();
                    snd2 = new HTML.Audio.FromAssets.Hammertime();
                    snd2.load();

                    reverse();
                };

            Action Show =
                delegate
                {
                    if (diagnostics.style.top != "-100%")
                        return;

                    // { -webkit-filter: grayscale(0.5) blur(10px);
                    (document.body.style as dynamic).webkitFilter = "grayscale(0.5) blur(2px)";

                    diagnostics.style.top = "0%";
                    diagnostics.style.backgroundColor = "rgba(0, 0, 0, 0.5)";


                    snd.play();
                    snd = new HTML.Audio.FromAssets.SAMPLES036();
                    snd.load();


                    // using undo context? save load and store ops to revert them
                    editor.InnerHTML = document.body.innerHTML;

                    reverse = delegate
                    {
                        document.body.innerHTML = editor.InnerHTML;

                        reverse = delegate { };
                    };
                };



            Hide();

            // http://www.w3schools.com/css3/css3_transitions.asp
            diagnostics.style.transition = "all 0.2s ease-in-out";




            Action Toggle =
                delegate
                {
                    if (diagnostics.style.top != "-100%")
                    {
                        Hide();

                    }
                    else
                    {
                        Show();

                    }
                };

            diagnostics.onclick +=
                e =>
                {
                    if (e.Element == diagnostics)
                        Hide();

                };

            Action<IEvent> AtKeyCode =
               e =>
               {
                   var KeyCode = e.KeyCode;

                   new { KeyCode }.ToString().ToDocumentTitle();

                   if (KeyCode == 27)
                   {
                       e.preventDefault();
                       e.stopPropagation();

                       Hide();

                   }


                   // e
                   if (KeyCode == 69)
                   {
                       e.preventDefault();
                       e.stopPropagation();

                       Show();

                   }

                   // US
                   if (KeyCode == 222)
                   {
                       e.preventDefault();
                       e.stopPropagation();


                       Toggle();
                   }
                   // EE
                   if (KeyCode == 192)
                   {
                       e.preventDefault();
                       e.stopPropagation();


                       Toggle();
                   }
               };

            // rosyln could pick up change requests from comments
            // should not see this event for popup action
            //f.FormClosing +=
            //    (s, e) =>
            //    {
            //        e.Cancel = true;

            //        //Hide();
            //    };

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

            // what if it is reloaded? popup
            editor.Document.WhenContentReady(
                delegate
                {
                    editor.Document.onkeyup += e => AtKeyCode(e);
                }
            );


         
        }
コード例 #3
0
        public Application(IApp page)
        {
            // jsc does not yet pre package chrome apps nor extensions
            // thus we do it manually.
            // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2014/20140705/20140712
            // X:\jsc.svn\examples\javascript\chrome\extensions\ChromeTabsExperiment\ChromeTabsExperiment\Application.cs

            // A single extension can override only one page. For example, an extension can't override both the Bookmark Manager and History pages.


            // we could provide special API for scriptcorelib runtime on the tab being loaded
            // http://blog.chromium.org/

            // what else can we override besides options?
            // "options_page": "Application.htm",
            // https://code.google.com/p/chromium/issues/detail?id=171752
            // https://developer.chrome.com/extensions/options

            // can we provide an API about available android devices?

            #region self_chrome_tabs
            dynamic self = Native.self;
            dynamic self_chrome = self.chrome;
            object self_chrome_tabs = self_chrome.tabs;

            if (self_chrome_tabs != null)
            {
                #region Suspend
                chrome.runtime.Suspend += delegate
                  {
                      // dispose all injection done so far?
                      Console.WriteLine("chrome.runtime.Suspend");
                  };
                #endregion


                // jsc, add chrome nuget
                #region Installed
                chrome.runtime.Installed += delegate
                {
                    // our API does not have a Show
                    new chrome.Notification
                    {
                        Message = "Extension Installed!"
                    };
                };
                #endregion

                Action<string> AtMessageFromTabToExtensionForApplication = delegate { };

                Action<string> AtUDPString = delegate { };

                var IgnoreSecondaryUpdatesFor = new List<TabIdInteger>();

                #region Updated
                chrome.tabs.Updated +=
                    async (i, x, tab) =>
                    {
                        // chrome://newtab/

                        if (tab.url.StartsWith("chrome-devtools://"))
                            return;

                        if (tab.url.StartsWith("chrome://"))
                            return;

                        if (tab.status != "complete")
                            return;


                        if (IgnoreSecondaryUpdatesFor.Contains(tab.id))
                            return;

                        // inject?

                        // what if we sent the uri to our android tab?
                        var n = new Notification
                        {
                            Message = "Updated! " + new { tab.id, tab.url }
                        };

                        IgnoreSecondaryUpdatesFor.Add(tab.id);



                        // X:\jsc.svn\core\ScriptCoreLib\JavaScript\BCLImplementation\System\Net\WebClient.cs

                        //var aFileParts = new[] { code };
                        //var oMyBlob = new Blob(aFileParts, new { type = "text/javascript" }); // the blob
                        //var url = oMyBlob.ToObjectURL();

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


                        // when will roslyn learn to expose events as async?
                        await tab.pageAction.async.onclick;

                        var nn = new Notification
                        {
                            Message = "Clicked " + new { tab.id, tab.url }
                        };



                        var code = await new WebClient().DownloadStringTaskAsync(
                             new Uri(Worker.ScriptApplicationSource, UriKind.Relative)
                        );


                        //Console.WriteLine("before insertCSS");

                        // https://developer.chrome.com/extensions/tabs#type-Tab
                        // http://stackoverflow.com/questions/9795058/how-to-run-chrome-tabs-insertcss-from-the-background-page-on-each-page
                        // chrome::
                        tab.id.insertCSS(
                            new
                            {
                                // .css do we have a CSS parser/builder available yet?

                                //code = "body { border: 1em solid red; }"
                                code = "body { border-left: 1em solid yellow; }"
                            },
                            null
                        );

                        // await tab.id.Run(async delegate {});
                        //};


                        // Unchecked runtime.lastError while running tabs.executeScript: No source code or file specified.
                        // https://developer.chrome.com/extensions/tabs#method-executeScript
                        // https://developer.chrome.com/extensions/tabs#type-InjectDetails
                        // https://developer.chrome.com/extensions/content_scripts#pi

                        // Content scripts execute in a special environment called an isolated world. 
                        // They have access to the DOM of the page they are injected into, but not to any JavaScript variables or 
                        // functions created by the page. It looks to each content script as if there is no other JavaScript executing
                        // on the page it is running on. The same is true in reverse: JavaScript running on the page cannot call any 
                        // functions or access any variables defined by content scripts.

                        var result = await tab.id.executeScript(
                            //new { file = url }
                            new { code }
                        );




                        // how to use connect?
                        var p = tab.id.connect();
                        var p_disconnected = false;

                        p.onDisconnect.addListener(
                            new Action(
                                delegate
                                {
                                    p_disconnected = true;
                                }
                            )
                        );


                        p.onMessage.addListener(
                            new Action<string>(
                                data =>
                                {
                                    AtMessageFromTabToExtensionForApplication(data);

                                    //Console.WriteLine("extension: onMessage " + new { data });
                                    //new Notification
                                    //{
                                    //    Message = "extension onMessage: " + new { tab.id, data }
                                    //};
                                }
                            )
                        );


                        //p.postMessage("hello executeScript");


                        // lets enable workers within tab
                        p.postMessage(new { code });

                        AtUDPString +=
                            xml =>
                            {
                                //Console.WriteLine("extension: " + new { xml });

                                if (p_disconnected)
                                    return;

                                if (tab.active)
                                {
                                    // only if active tab?
                                    p.postMessage(new { xml });
                                }
                            };
                    };
                #endregion





                #region __MulticastListenExperiment

                // can this chrome.extension connect to a chrome app?
                var __MulticastListenExperiment = "aemlnmcokphbneegoefdckonejmknohh";

                Console.WriteLine("chrome.runtime.connect " + new { __MulticastListenExperiment });

                // what if the app is not loaded, or is inactive?

                chrome.runtime.connect(__MulticastListenExperiment).With(
                      port =>
                      {
                          // Uncaught TypeError: Cannot read property 'id' of undefined
                          Console.WriteLine("chrome.runtime.connect OK " + new { __MulticastListenExperiment, chrome.runtime.lastError });
                          // 0:60ms chrome.runtime.connect OK { __MulticastListenExperiment = aemlnmcokphbneegoefdckonejmknohh, lastError =  } 
                          //Console.WriteLine("chrome.runtime.connect OK " + new { __MulticastListenExperiment, chrome.runtime.lastError, port.sender.id });


                          port.onDisconnect.addListener(
                              new Action(
                                  delegate
                                  {
                                      Console.WriteLine("chrome.runtime.connect onDisconnect " + new { __MulticastListenExperiment });
                                  }
                              )
                          );

                          // we wont know if we got the connection...
                          port.onMessage.addListener(
                                new Action<object>(
                                    message =>
                                    {
                                        // %c0:182ms app to extension { message = hello from app }

                                        //Console.WriteLine("app to extension " + new { message, port.sender.id });
                                        Console.WriteLine("app to extension " + new { message });

                                        //var nn = new chrome.Notification
                                        //{
                                        //    Title = "app to extension",
                                        //    Message = new { message }.ToString(),
                                        //};

                                        AtUDPString((string)message);
                                    }
                                )
                            );

                          AtMessageFromTabToExtensionForApplication +=
                              message =>
                              {
                                  port.postMessage(message);
                              };
                      }
                  );
                #endregion


                //Console.WriteLine("chrome.runtime.connect exit " + new { __MulticastListenExperiment });

                return;
            }
            #endregion

            Native.body.style.borderTop = "1em solid yellow";

            // if we were injected by executeScript, how would we launch a worker now?

            // VM608:41423


            // https://code.google.com/p/v8/wiki/JavaScriptStackTraceApi
            //getFileName: if this function was defined in a script returns the name of the script

            //var xx = new Exception();

            //Console.WriteLine(new { xx.StackTrace });
            //0:46ms { StackTrace = Error
            //    at AgsABmfn8j_aa_bqCu59PrPg (http://192.168.43.252:12879/view-source:27498:56)


            //0:25ms { StackTrace = Error
            //    at AgsABmfn8j_aa_bqCu59PrPg (<anonymous>:27498:56)
            //    at mV1GtUeaNze1ZFoeDPNoHQ.type$mV1GtUeaNze1ZFoeDPNoHQ.AwAABkeaNze1ZFoeDPNoHQ (<anonymous>:59652:9)


            // can we atleast try to ask for the source?


            Action<string> Notify = delegate { };

            new xxAvatar().Create();



            #region go worker
            new IHTMLButton { 
                "go worker: ",
               (

                    // we can read our own data, and any other browser extension can too, encrypt it?
                    from x in new xxAvatar()
                    orderby x.Key descending
                    //select x.Tag
                    //select new  {x.Tag}
                    select new xxAvatarRow { Tag = x.Tag}
                ).FirstOrDefaultAsync()
            }.AttachToDocument().With(
            button =>
            {
                button.style.position = IStyle.PositionEnum.@fixed;
                button.style.left = "1em";
                button.style.bottom = "1em";
                //button.style.zIndex = 1000;
                button.style.zIndex = 10000;




                button.onclick +=
                    async e =>
                    {
                        e.Element.disabled = true;


                        button.innerText = "working... ";


                        // live updates from worker via DB.
                        button.Add(

                             () => (

                                // we can read our own data, and any other browser extension can too, encrypt it?
                                from xx in new xxAvatar()
                                orderby xx.Key descending
                                //select x.Tag
                                //select new  {x.Tag}
                                select new xxAvatarRow { Tag = xx.Tag }
                            ).FirstOrDefaultAsync()

                        );


                        Native.body.style.borderTop = "1em solid blue";


                        var scopedata1 = "enter";
                        var scopedata2 = "exit";

                        var x = await Task.Run(
                            async delegate
                            {
                                var s = Stopwatch.StartNew();



                                for (int index = 0; index < 10; index++)
                                {

                                    // does it show up?
                                    await new xxAvatar().InsertAsync(
                                        new xxAvatarRow
                                        {
                                            Tag = "tab worker! " + scopedata1 + new { index, s.ElapsedMilliseconds, Thread.CurrentThread.ManagedThreadId },
                                        }
                                    );

                                    Console.WriteLine(new { Thread.CurrentThread.ManagedThreadId });
                                    await Task.Delay(99);
                                }


                                // does it show up?
                                await new xxAvatar().InsertAsync(
                                    new xxAvatarRow
                                    {
                                        Tag = "tab worker! " + scopedata2 + new { s.ElapsedMilliseconds, Thread.CurrentThread.ManagedThreadId },
                                    }
                                );

                                return "webview worker calling extension " + new { s.ElapsedMilliseconds, Thread.CurrentThread.ManagedThreadId };
                            }
                        );


                        button.innerText = "go worker: ";


                        // live updates from worker via DB.
                        button.Add(

                            // show a static field, so we wont spam console
                             (

                                // we can read our own data, and any other browser extension can too, encrypt it?
                                from xx in new xxAvatar()
                                orderby xx.Key descending
                                //select x.Tag
                                //select new  {x.Tag}
                                select new xxAvatarRow { Tag = xx.Tag }
                            ).FirstOrDefaultAsync()

                        );

                        Notify(x);

                        Native.body.style.borderTop = "1em solid pink";
                        e.Element.disabled = false;
                    };




            }
            );
            #endregion



            var forms = new List<Form>();



            #region onxmlmessage
            Action<XElement> onxmlmessage = null;

            onxmlmessage =
                xml =>
                {
                    // we are working within another webapp
                    // the tab was told by the extension
                    // the extension was told by the app
                    // the app was told by udp broadcast
                    // that a jsc app is now running.

                    // cool.

                    // can we load it into here?

                    if (xml.Value.StartsWith("Visit me at "))
                    {
                        // what about android apps runnning on SSL?
                        // what about preview images?
                        // do we get localhost events too?

                        var uri = "http://" + xml.Value.SkipUntilOrEmpty("Visit me at ");

                        if (forms.Any(x => x.Text == uri))
                        {
                            // look already opened!
                            return;
                        }

                        // X:\jsc.internal.git\market\chrome\ChromeMyJscSolutionsNet\ChromeMyJscSolutionsNet\Application.cs

                        // "X:\jsc.svn\examples\javascript\android\com.abstractatech.appmanager\com.abstractatech.appmanager.sln"
                        // X:\jsc.svn\examples\javascript\android\com.abstractatech.appmanager\com.abstractatech.appmanager\Application.cs




                        // can we pop ourselves out of here too?
                        // can chrome>extensions do AppWindows?


                        // on some pages they style our div. shall we use a non div to get nonstyled element?
                        // or do we need shadow DOM? is it even available yet for us?
                        var f = new Form { Text = uri, ShowIcon = false };
                        forms.Add(f);

                        var w = new WebBrowser();
                        w.Dock = DockStyle.Fill;

                        f.Controls.Add(w);

                        w.Navigate(uri);
                        f.Show();

                        f.FormClosed +=
                            delegate
                            {
                                Console.WriteLine("FormClosed " + new { uri });

                                forms.Remove(f);

                            };

                        // if we close it we want it to be gone for good.
                        // the extension cannot detatch our frame. it may need to ask the app to reopen this virtual tab...
                        f.PopupInsteadOfClosing(HandleFormClosing: false,

                            SpecialCloseOnLeft:
                                delegate
                                {
                                    // shall we ask app:: to reopen uri in AppWindow?
                                    Notify(xml.ToString());

                                    f.Close();
                                }
                        );


                    }

                };
            #endregion


            #region Connect
            object self_chrome_runtime = self_chrome.runtime;
            Console.WriteLine(new { self_chrome_runtime });
            // 0:39ms { self_chrome_runtime = [object Object] }
            if (self_chrome_runtime != null)
            {
                chrome.runtime.Connect +=
                        e =>
                        {
                            // port
                            // extension connects to injected tab?
                            Console.WriteLine("chrome.runtime.Connect " + new { Native.document.domain });
                            //Console.WriteLine("chrome.runtime.Connect " + new { Native.document.domain, e.sender.id });

                            //0:123ms chrome.runtime.Connect
                            //0:126ms webview: onMessage { data = hello executeScript }


                            //http://stackoverflow.com/questions/15798516/is-there-an-event-for-when-a-chrome-extension-popup-is-closed


                            e.onDisconnect.addListener(
                                new Action(
                                    delegate
                                    {
                                        // extension unloaded
                                        Native.body.style.borderTop = "0em solid red";
                                        Native.body.style.borderLeft = "0em solid red";

                                        forms.WithEach(f => f.Close());

                                    }
                                )
                            );



                            e.onMessage.addListener(
                                new Action<dynamic>(
                                    data =>
                                    {
                                        string xml = data.xml;
                                        if (xml != null)
                                        {
                                            // tab injection was notified by extension, by app, by udp android?
                                            Native.body.style.borderLeft = "1em solid red";

                                            // 0:40394ms { xml = <string c="1">Visit me at 192.168.1.67:6169</string> }
                                            Console.WriteLine(new { xml });


                                            // X:\jsc.internal.git\market\chrome\ChromeMyJscSolutionsNet\ChromeMyJscSolutionsNet\Application.cs

                                            onxmlmessage(
                                                XElement.Parse(xml)
                                                );

                                        }

                                        string code = data.code;
                                        if (code != null)
                                        {

                                            //Console.WriteLine("webview: onMessage " + new { data });

                                            // %c0:41906ms extension: onMessage { data = connected! }
                                            //e.postMessage("got code! " + new { code.Length });

                                            Native.body.style.borderTop = "1em solid red";

                                            // InternalInlineWorker

                                            // http://stackoverflow.com/questions/21408510/chrome-cant-load-web-worker
                                            // this wont work for file:// tabs

                                            // message: "Failed to construct 'Worker': Script at 'blob:null/f544915f-b855-480b-8db8-bd6c686829b9#worker' cannot be accessed from origin 'null'."
                                            var aFileParts = new[] { code };
                                            var oMyBlob = new Blob(aFileParts, new { type = "text/javascript" }); // the blob
                                            var url = oMyBlob.ToObjectURL();

                                            InternalInlineWorker.ScriptApplicationSourceForInlineWorker = url;

                                            Notify = x =>
                                            {
                                                // Error in event handler for (unknown): Attempting to use a disconnected port object Stack trace: Error: Attempting to use a disconnected port object
                                                e.postMessage(x);
                                            };
                                        }
                                    }
                                )
                            );


                        };

                //chrome.runtime.Message +=
                //    delegate
                //    {
                //        Console.WriteLine("chrome.runtime.Message");
                //    };
            }
            #endregion





            // 0:168ms chrome.runtime.Connect
            // https://developer.chrome.com/extensions/tabs#method-sendMessage
            // chrome extension wont call here?
            //Native.window.onmessage +=
            //    e =>
            //    {
            //        Console.WriteLine(
            //            "onmessage: " +
            //            new { e.data }
            //        );




            //        e.postMessage("ok");

            //    };
        }
コード例 #4
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)
        {
            sprite.wmode();

            sprite.AttachSpriteToDocument().With(
                   embed =>
                   {
                       embed.style.SetLocation(0, 0);
                       embed.style.SetSize(Native.Window.Width, Native.Window.Height);

                       Native.Window.onresize +=
                           delegate
                           {
                               embed.style.SetSize(Native.Window.Width, Native.Window.Height);
                           };
                   }
               );


            #region con
            var con = new ConsoleForm();

            con.InitializeConsoleFormWriter();

            con.Show();

            con.Height = 150;
            con.Left = Native.Window.Width - con.Width;
            con.Top = 0;

            Native.Window.onresize +=
                  delegate
                  {
                      con.Left = Native.Window.Width - con.Width;
                      con.Top = 0;
                  };


            con.Opacity = 0.6;




            // !! not compatible yet

            con.HandleFormClosing = false;
            con.PopupInsteadOfClosing();
            #endregion



            sprite.fps +=
                (fps, nid) =>
                {
                    new { fps, nid }.ToString().ToDocumentTitle();
                };


            #region context_new_remotegame
            sprite.context_new_remotegame +=
                remotegame =>
                {
                    var remotegame_con = new ConsoleForm();

                    remotegame_con.Show();
                    remotegame_con.Left = 0;
                    remotegame_con.Top = Native.Window.Height - remotegame_con.Height;

                    remotegame_con.Opacity = 0.5;

                    remotegame.AtTitleChange +=
                        e => remotegame_con.Text = e;

                    remotegame.AtWriteLine +=
                        e =>
                        {
                            remotegame_con.textBox1.AppendText(e + Environment.NewLine);
                            remotegame_con.textBox1.ScrollToCaret();
                        };


                    remotegame_con.HandleFormClosing = false;
                    remotegame_con.PopupInsteadOfClosing();
                };
            #endregion


            var sprites_events = new BindingListWithEvents<ApplicationSprite>();
            var sprites = sprites_events.Source;

            sprites_events.Added +=
                (fsprite, i) =>
                {
                    Console.WriteLine(i + "# Console ready!");

                    fsprite.InitializeConsoleFormWriter(
                        Console_Write: x => Console.Write(x),
                        Console_WriteLine: x =>
                            {
                                var lines = x.Split(Environment.NewLine);

                                foreach (var item in lines)
                                {
                                    Console.WriteLine(i + "# " + item);
                                }
                            }
                    );

                    #region lets do two way binding here.



                    // fsprite -> sprite
                    fsprite.context_onmessage += xml =>
                    {
                        // script: error JSC1000: No implementation found for this native method, please implement [static System.Linq.Enumerable.Except(System.Collections.Generic.IEnumerable`1[[FlashHeatZeekerWithStarlingB2.ApplicationSprite, FlashHeatZeekerWithStarlingB2.Application, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]], System.Collections.Generic.IEnumerable`1[[FlashHeatZeekerWithStarlingB2.ApplicationSprite, FlashHeatZeekerWithStarlingB2.Application, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]])]

                        sprites.WithEach(
                            x =>
                            {
                                // prevent echo
                                if (x == fsprite)
                                    return;

                                x.game_postMessage(xml);
                            }
                        );
                    };

                    #endregion
                };


            sprites.Add(sprite);

            #region game_InitializeFrameDiagnostics
            sprite.game_InitializeFrameDiagnostics(
                __FrameDiagnostics =>
                {
                    Console.WriteLine("new FrameDiagnostics");

                    var x = new FrameDiagnostics();

                    x.Show();

                    Console.WriteLine("new FrameDiagnostics Show, can you see it?");


                    Native.Window.onresize +=
                      delegate
                      {
                          x.Left = Native.Window.Width - x.Width;
                          x.Top = Native.Window.Height - x.Height;
                      };


                    x.Initialize(__FrameDiagnostics);

                    // Error	8	'Abstractatech.ConsoleFormPackage.Library.ConsoleForm' does not contain a definition for 'PopupInsteadOfClosing' and no extension method 'PopupInsteadOfClosing' accepting a first argument of type 'Abstractatech.ConsoleFormPackage.Library.ConsoleForm' could be found (are you missing a using directive or an assembly reference?)	X:\jsc.svn\examples\actionscript\svg\FlashHeatZeeker\FlashHeatZeekerWithStarlingB2\Application.cs	85	17	FlashHeatZeekerWithStarlingB2
                    // wtf?
                    x.PopupInsteadOfClosing();
                    x.Opacity = 0.7;

                    // can we pop it up?


                    x.JoinMultiplayer.Click +=
                        delegate
                        {
                            var f = new Form();
                            // make it small
                            f.Height = 200;

                            var fsprite = new ApplicationSprite();
                            fsprite.src_fixup();
                            fsprite.wmode();


                            var fspriteelement = fsprite.AttachSpriteTo(
                                f.GetHTMLTargetContainer()
                            );

                            #region ClientSizeChanged / PopupInsteadOfClosing has a bug
                            f.ClientSizeChanged +=
                                delegate
                                {
                                    var cs = f.ClientSize;

                                    fspriteelement.style.SetSize(cs.Width,
                                        cs.Height
                                    );
                                };
                            #endregion

                            f.Show();
                            f.PopupInsteadOfClosing();

                            // do events break if popup mode is changed?
                            fsprite.fps +=
                                  (fps, nid) =>
                                  {
                                      new { fps, nid }.ToString().ToTitle(f);
                                  };




                            sprites.Add(fsprite);
                            // what if we have more of these?
                        };
                }
            );
            #endregion








        }
コード例 #5
0
                public GooApplication(IGoo goopage, HistoryScope<ApplicationState> gooscope)
                {
                    // init state! this will be sent to server at every new web call.
                    this.state = gooscope.state;
                    FlashTitle();


                    Native.document.title = state.title;
                    Native.document.body.style.borderTop = "1em red solid";

                    Action ShowDataTable =
                        delegate
                        {
                            goopage.output.Clear();

                            var f = new Form
                            {
                                Text = new { this.state.data.TableName }.ToString(),
                                ControlBox = false,
                                ShowIcon = false,

                                //WindowState = FormWindowState.Maximized
                            };

                            new DataGridView
                            {
                                // script: error JSC1000: No implementation found for this native method, please implement [System.Windows.Forms.DataGridView.set_BorderStyle(System.Windows.Forms.BorderStyle)]
                                //BorderStyle = BorderStyle.Fixed3D 
                                //AutoSize = true,
                                AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells,

                                DataSource = this.state.data,
                                Dock = DockStyle.Fill
                            }.AttachTo(f);

                            // do we need this?

                            f.GetHTMLTarget().AttachTo(goopage.output);

                            f.Show();

                            f.WindowState = FormWindowState.Maximized;
                            f.PopupInsteadOfClosing(
                                HandleFormClosing: false

                                // , 
                                // does not play well with maximized yet
                                //SpecialNoMovement: true
                                );

                        };

                    if (this.state.data == null)
                    {
                        // can we remove this from history then?

                        new IHTMLButton { innerText = "a page reload makes us forget DataTable. go back and get new data!" }.AttachTo(goopage.output).WhenClicked(
                            delegate
                            {

                                Native.window.history.back();
                            }
                        );

                        new IHTMLBreak().AttachTo(goopage.output);

                        new IHTMLButton { innerText = "or get new data, if the server is available" }.AttachTo(goopage.output).WhenClicked(
                            async delegate
                            {
                                Native.document.body.style.borderTop = "1em black solid";

                                this.reason = "page reload makes us forget DataTable";
                                //this.state = (await this.DoEnterData()).state;

                                var x = await this.DoEnterData();

                                this.state = x.state;

                                Native.document.body.style.borderTop = "1em red solid";

                                ShowDataTable();
                            }
                        );
                    }
                    else
                    {
                        ShowDataTable();
                    }

                    #region undo
                    gooscope.With(
                         async delegate
                         {
                             await gooscope;



                             // time to undo
                             Native.document.body.style.borderTop = "0.3em yellow solid";
                         }
                     );
                    #endregion

                }
コード例 #6
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)
        {
            FormStyler.AtFormCreated = FormStylerLikeFloat.LikeFloat;

            // http://html5doctor.com/drag-and-drop-to-server/

            #region ondrop
            Native.document.body.ondragover +=
                evt =>
                {
                    evt.stopPropagation();
                    evt.preventDefault();

                    evt.dataTransfer.dropEffect = "copy"; // Explicitly show this is a copy.


                    page.Header.style.color = JSColor.Green;


                    var types = evt.dataTransfer.types == null ? 0 : evt.dataTransfer.types.Length;

                    if (evt.dataTransfer.types != null)
                        foreach (var type in evt.dataTransfer.types.AsEnumerable())
                        {
                            Console.WriteLine(
                                new { type }
                                );
                        }

                    var items = evt.dataTransfer.items == null ? 0u : evt.dataTransfer.items.length;
                    var files = evt.dataTransfer.files == null ? 0u : evt.dataTransfer.files.length;



                    Console.WriteLine("ondragover: " +
                        new
                        {

                            types,
                            items,
                            files
                        }
                    );
                };


            Native.document.body.ondragleave +=
                delegate
                {
                    page.Header.style.color = JSColor.None;
                };

            #region DetectCanvasFromBytesExperiment
            Action<Form, WebBrowser, string, string, long> DetectCanvasFromBytesExperiment =
                (ff, web, ContentValue, src, ContentBytesLength) =>
                {
                    web.Navigated +=
                           async delegate
                           {
                               if (ContentValue != "png.png")
                                   return;

                               // X:\jsc.svn\examples\javascript\canvas\CanvasFromBytes\CanvasFromBytes\Application.cs
                               //Console.WriteLine("interesting, is it one of ours? " + new { ContentValue });
                               ff.Text = "interesting, is it one of ours? " + new { ContentValue };

                               var csrci = new IHTMLImage { src = src };

                               //await csrci.async.onlo
                               await csrci;

                               if (csrci.width != csrci.height)
                                   return;


                               var w = csrci.width;


                               // do the reverse
                               var z = new CanvasRenderingContext2D(w, w);
                               z.drawImage(csrci, 0, 0, w, w);
                               //z.canvas.AttachToDocument();

                               // whats the bytes?

                               var zbytes = z.bytes;

                               ff.Text = "will decode " + new { zbytes.Length, ContentBytesLength }.ToString();

                               #region decode
                               var decodebytes = await Task.Factory.StartNew(
                                   new { zbytes },
                                   scope =>
                                   {
                                       // Native.Console.WriteLine += ?

                                       // { Length = 2053956, u4 = 3c68746d } 

                                       Console.WriteLine(
                                        new
                                        {
                                            scope.zbytes.Length,

                                            u4 = new[] { 
                                            scope.zbytes[0 * 4 + 0],
                                            scope.zbytes[0 * 4 +1],
                                            scope.zbytes[0 * 4 +2],
                                            scope.zbytes[0 * 4 +3]
                                        }.ToHexString()
                                        }
                                       );


                                       // Uncaught Error: InvalidOperationException: { MethodToken = dAAABv_a4OTKgLfLC20SaJA } function is not available at { href =

                                       var wwbytes = new byte[scope.zbytes.Length / 4];
                                       var wi = 0;

                                       for (int i = 0; i < scope.zbytes.Length; i += 4)
                                       {
                                           // that be the red
                                           //wwbytes[wi] = scope.zbytes[i];

                                           // bet we need alpha
                                           wwbytes[wi] = scope.zbytes[i + 3];
                                           wi++;
                                       }



                                       return wwbytes;
                                   }
                               );
                               #endregion


                               var html = Encoding.UTF8.GetString(decodebytes);

                               ff.Text = "decoded " + new { html.Length, ContentBytesLength }.ToString();

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


                               // um hide old data.
                               web.Hide();

                               var xweb = new WebBrowser { Dock = DockStyle.Fill };
                               xweb.AttachTo(ff);
                               xweb.DocumentText = html;
                               ff.Text = "!decoded " + new { html.Length, ContentBytesLength }.ToString();
                           };

                };
            #endregion


            Native.document.body.ondrop +=
                evt =>
                {
                    //if (evt.dataTransfer == null)
                    //    return;

                    var types = evt.dataTransfer.types == null ? 0 : evt.dataTransfer.types.Length;

                    var items = evt.dataTransfer.items == null ? 0u : evt.dataTransfer.items.length;
                    var files = evt.dataTransfer.files == null ? 0u : evt.dataTransfer.files.length;


                    Console.WriteLine("ondrop: " +
                        new
                        {

                            types,
                            items,
                            files
                        }
                    );


                    page.Header.style.color = JSColor.None;


                    //var xfiles = evt.dataTransfer.files.AsEnumerable().Concat(
                    //    from x in evt.dataTransfer.items.AsEnumerable()
                    //    let f = x.getAsFile()
                    //    where f != null
                    //    select f
                    //);

                    #region DataTable
                    if (evt.dataTransfer.items != null)
                    {
                        // X:\jsc.svn\examples\javascript\DragDataTableIntoCSVFile\DragDataTableIntoCSVFile\Application.cs

                        evt.dataTransfer.items.AsEnumerable().Where(
                            x =>

                                x.type.ToLower() ==

                                // let jsc type system sort it out?
                                // how much reflection does jsc give us nowadays?
                                typeof(DataTable).Name.ToLower()

                        ).WithEach(
                            async x =>
                            {
                                // http://www.whatwg.org/specs/web-apps/current-work/multipage/dnd.html#dfnReturnLink-0
                                var DataTable_xml = await x.getAsString();

                                var DataTable = StringConversionsForDataTable.ConvertFromString(DataTable_xml);

                                var ff = new Form { Text = new { typeof(DataTable).Name }.ToString() };

                                var g = new DataGridView { DataSource = DataTable, Dock = DockStyle.Fill };

                                ff.Controls.Add(g);


                                ff.Show();

                            }
                        );
                    }
                    #endregion

                    #region files
                    evt.dataTransfer.files.AsEnumerable().WithEachIndex(
                        (f, index) =>
                        {
                            Console.WriteLine(
                                new
                                {

                                    f.name,
                                    f.size,
                                    f.lastModifiedDate
                                }
                            );

                            var ff = new Form();
                            ff.PopupInsteadOfClosing(HandleFormClosing: false);



                            ff.Text = new { f.type, f.name, f.size }.ToString();


                            ff.Show();

                            ff.MoveTo(
                                evt.CursorX + 32 * index,
                                evt.CursorY + 24 * index
                            );

                            var fc = ff.GetHTMLTargetContainer();

                            fc.title = ff.Text;

                            #region image
                            var i = default(IHTMLImage);

                            if (f.type.StartsWith("image/"))
                            {
                                // um would we have a timing issue here?
                                f.ToDataURLAsync(
                                    src =>
                                    {
                                        i = new IHTMLImage { src = src }.AttachTo(fc);
                                        i.style.width = "100%";

                                        i.InvokeOnComplete(
                                            delegate
                                            {

                                                ff.ClientSize = new System.Drawing.Size(
                                                    // keep it reasonable!
                                                    i.width.Min(600),
                                                    i.height.Min(400)
                                                );

                                            }
                                        );
                                    }
                                );
                            }
                            #endregion

                            // http://html5doctor.com/drag-and-drop-to-server/

#if FUTURE
                            service.XUpload(f, delegate { });
#endif


                            var d = new FormData();

                            d.append("foo", f, f.name);

                            var xhr = new IXMLHttpRequest();

                            xhr.open(ScriptCoreLib.Shared.HTTPMethodEnum.POST, "/upload");

                            #region InvokeOnComplete
                            xhr.InvokeOnComplete(
                                delegate
                                {
                                    Console.WriteLine("upload complete!");

                                    SystemSounds.Beep.Play();

                                    //Console.Beep();
                                    XElement.Parse(xhr.responseText).Elements("ContentKey").WithEach(
                                        ContentKey =>
                                        {
                                            var __ContentKey = (Table1_ContentKey)int.Parse(ContentKey.Value);

                                            var web = new WebBrowser { Dock = DockStyle.Fill };

                                            web.Hide();
                                            web.AttachTo(ff);


                                            var src = "/io/" + ContentKey.Value;

                                            if (i == null)
                                            {
                                                web.Show();
                                            }
                                            else
                                            {
                                                web.Navigated +=
                                                    delegate
                                                    {
                                                        i.Orphanize();
                                                        web.Show();
                                                    };
                                            }


                                            // "X:\jsc.svn\examples\javascript\canvas\CanvasFromBytes\png.png"
                                            DetectCanvasFromBytesExperiment(
                                                ff,
                                                web,
                                                 f.name,
                                                src,
                                               (long)f.size
                                            );

                                            web.Navigate(src);


                                            //if (i != null)
                                            //{
                                            //    i.src = src;
                                            //}

                                            __ContentKey.SetLeft(ff.Left);
                                            __ContentKey.SetTop(ff.Top);

                                            ff.LocationChanged +=
                                                delegate
                                                {
                                                    __ContentKey.SetLeft(ff.Left);
                                                    __ContentKey.SetTop(ff.Top);
                                                };

                                            ff.SizeChanged +=
                                                delegate
                                                {
                                                    __ContentKey.SetWidth(ff.Width);
                                                    __ContentKey.SetHeight(ff.Height);
                                                };

                                            ff.FormClosing +=
                                                delegate
                                                {
                                                    __ContentKey
                                                        .Delete();
                                                };


                                            #region onmousewheel
                                            ff.GetHTMLTarget().With(
                                                ffh =>
                                                {
                                                    dynamic ffhs = ffh.style;
                                                    // http://css-infos.net/property/-webkit-transition
                                                    //ffhs.webkitTransition = "webkitTransform 0.3s linear";

                                                    ffh.onmousewheel +=
                                                        e =>
                                                        {
                                                            e.preventDefault();
                                                            e.stopPropagation();


                                                            if (e.WheelDirection > 0)
                                                            {
                                                                ff.Width = (int)(ff.Width * 1.1);
                                                                ff.Height = (int)(ff.Height * 1.1);
                                                            }
                                                            else
                                                            {
                                                                ff.Width = (int)(ff.Width * 0.9);
                                                                ff.Height = (int)(ff.Height * 0.9);
                                                            }

                                                        };

                                                }
                                            );
                                            #endregion

                                        }
                                    );
                                }
                            );
                            #endregion


                            //------WebKitFormBoundaryDmGHAZzeMBbcD5mu
                            //Content-Disposition: form-data; name="foo"; filename="FlashHeatZeeker.UnitPedControl.ApplicationSprite.swf"
                            //Content-Type: application/x-shockwave-flash


                            //------WebKitFormBoundaryDmGHAZzeMBbcD5mu--

                            Console.WriteLine("before upload...");
                            xhr.send(d);
                        }
                    );
                    #endregion


                    // let's disable other handlers
                    //evt.dataTransfer = null;

                    evt.stopPropagation();
                    evt.stopImmediatePropagation();

                    evt.preventDefault();
                };
            #endregion

            #region restore
            {
                var index = 0;

                default(Table1_ContentKey).WithEach(
                    (__ContentKey, ContentBytesLength, ContentValue, Left, Top, Width, Height) =>
                    {

                        var ff = new Form();
                        ff.PopupInsteadOfClosing(HandleFormClosing: false);


                        ff.Text = new { __ContentKey, ContentValue, ContentBytesLength }.ToString();


                        ff.Show();

                        if (Left > 0)
                            ff.MoveTo(
                                Left,
                                Top
                            );
                        else

                            ff.MoveBy(
                                32 * index,
                                24 * index
                            );

                        index++;

                        #region onmousewheel
                        ff.GetHTMLTarget().With(
                            ffh =>
                            {
                                dynamic ffhs = ffh.style;
                                // http://css-infos.net/property/-webkit-transition
                                //ffhs.webkitTransition = "webkitTransform 0.3s linear";

                                ffh.onmousewheel +=
                                    e =>
                                    {
                                        e.preventDefault();
                                        e.stopPropagation();

                                        if (e.WheelDirection > 0)
                                        {
                                            ff.Width = (int)(ff.Width * 1.1);
                                            ff.Height = (int)(ff.Height * 1.1);
                                        }
                                        else
                                        {
                                            ff.Width = (int)(ff.Width * 0.9);
                                            ff.Height = (int)(ff.Height * 0.9);
                                        }

                                    };

                            }
                        );
                        #endregion



                        //var fc = ff.GetHTMLTargetContainer();
                        var src = "/io/" + __ContentKey;

                        //var i = new IHTMLImage { src = src }.AttachTo(fc);
                        //i.style.width = "100%";

                        var web = new WebBrowser { Dock = DockStyle.Fill };

                        web.AttachTo(ff);

                        //script: error JSC1000: No implementation found for this native method, please implement [System.Windows.Forms.WebBrowser.add_DocumentCompleted(System.Windows.Forms.WebBrowserDocumentCompletedEventHandler)]
                        //script: warning JSC1000: Did you reference ScriptCoreLib via IAssemblyReferenceToken?
                        //script: error JSC1000: error at DropFileIntoSQLite.Application+<>c__DisplayClass2e.<.ctor>b__15,
                        // assembly: V:\DropFileIntoSQLite.Application.exe
                        // type: DropFileIntoSQLite.Application+<>c__DisplayClass2e, DropFileIntoSQLite.Application, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null

                        //web.DocumentCompleted +=
                        //    delegate
                        //    {



                        //};

                        DetectCanvasFromBytesExperiment(
                            ff,
                            web,
                            ContentValue,
                            src,
                            ContentBytesLength
                        );


                        web.Navigate(src);

                        if (Width > 0)
                            ff.SizeTo(
                               Width,
                               Height
                           );
                        //else
                        //    i.InvokeOnComplete(
                        //        delegate
                        //        {


                        //            ff.ClientSize = new System.Drawing.Size(i.width, i.height);

                        //        }
                        //    );

                        ff.LocationChanged +=
                            delegate
                            {
                                __ContentKey.SetLeft(ff.Left);
                                __ContentKey.SetTop(ff.Top);
                            };

                        ff.SizeChanged +=
                            delegate
                            {
                                __ContentKey.SetWidth(ff.Width);
                                __ContentKey.SetHeight(ff.Height);
                            };

                        ff.FormClosing +=
                            delegate
                            {
                                __ContentKey.Delete();
                            };
                    }
                );
            }
            #endregion



            // can we write about this?
            #region bookmark launcher
            var href = @"javascript:
((function(h,i)
{ 
    

    var a=-1, 
    b='onreadystatechange', 
    c=document.getElementsByTagName('HEAD')[0], 
    d, 
    e, 
    f, 
    g=c.childNodes, 
    d; 

    e=document.createElement('base');   
    e.href='%%';
    c.appendChild(e);     

    d = function () 
    {  
        next: while (1)  
        {   
            a++;     
            if (a ==h.length)   
            {   
                i();    
                return;   
            }     

            /*
            for (f=0;f<g.length;f++)   
            {   
                var v =g[f];    
                var w =h[a];       

                if (v.nodeName =='SCRIPT')    
                    if (v.src ==w || v.src.substr(v.src.length - w.length - 1,w.length + 1) =='/' + w)    
                        continue next;   
            } */      
            e=document.createElement('SCRIPT');   
            e.src='%%' + h[a];     
            e[b in e?b:'onload']=  function()    
            {       
                var f=e.readyState;    
                if(f==null||f=='loaded'||f=='complete')     
                    d();    
            };  
 
        c.appendChild(e);     
        return;  
    } 
}; 
d();

}

)(['view-source'],function(){}))".Replace("%%", Native.Document.location + "");

            page.Header.draggable = true;
            page.Header.ondragstart +=
                e =>
                {
                    e.dataTransfer.setData("text/uri-list", href);
                };


            IStyleSheet.Default["#Header:hover"].style.color = "red";
            IStyleSheet.Default["#Header:hover"].style.cursor = IStyle.CursorEnum.pointer;

            #endregion


            new About().Show();
        }
コード例 #7
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);

        }
コード例 #8
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)
        {
            //content.AttachControlTo(page.Content);
            //content.AutoSizeControlTo(page.ContentSize);

            FormStyler.AtFormCreated = FormStylerLikeFloat.LikeFloat;

            // I want animated background!
            new WebGLClouds.Application();

            //Native.Document.body.lastChild.MoveNodeToFirst();

            var f = new Form();

            content.BackColor = Color.Transparent;
            content.Dock = DockStyle.Fill;
            content.AttachTo(f);

            f.Show();


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


            Action ResizeMargin = delegate
            {
                if (f.GetHTMLTarget().parentNode == null)
                    Native.Document.body.style.marginLeft = 16 + "px";
                else
                    Native.Document.body.style.marginLeft = (f.Width + 32) + "px";
            };

            Action AtResize = delegate
            {
                ResizeMargin();

                f.MoveTo(16, 16);
                f.SizeTo(
                    f.Width,
                    f.Height.Min(Native.window.Height - 32)
                );
            };

            // why this not working?
            //f.SizeChanged +=
            content.ClientSizeChanged +=
                delegate
                {
                    ResizeMargin();
                };


            //new ScriptCoreLib.JavaScript.Runtime.Timer(
            //    delegate
            //    {

            //    }
            //).StartInterval();

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

            AtResize();


            f.PopupInsteadOfClosing(SpecialNoMovement: true);
        }