static void InitializeContnt(IDefaultPage page) { Action<dynamic> stream = x => { object time = x.time; object i = x.i; Native.document.title = new { time, i }.ToString(); Console.WriteLine(new { time, i }.ToString()); page.Content.innerText = new { time, i }.ToString(); }; dynamic window = Native.window; window.stream = stream; var stop = new IHTMLButton("Stop").AttachToDocument(); var iframe = new IHTMLIFrame { src = "/stream" }.AttachToDocument(); iframe.Hide(); page.Start.disabled = true; stop.onclick += delegate { stop.Orphanize(); page.Start.disabled = false; iframe.Orphanize(); }; Native.document.body.style.cursor = IStyle.CursorEnum.@default; }
/// <summary> /// This is a javascript application. /// </summary> /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param> public Application(IDefaultPage page) { Action</*dynamic*/ IHTMLInput, string, Func<IHTMLScript>> apply = (btn, text, js) => { btn.disabled = true; var Content = js(); Content.AttachToHead(); var DisableScript = new IHTMLButton { innerText = "disable " + text }; DisableScript.AttachTo(page.Content); DisableScript.onclick += delegate { DisableScript.Orphanize(); Content.Orphanize(); btn.disabled = false; }; }; page.Bar.onclick += delegate { apply(page.Bar, "Boo.js", () => new WithJavaScript.JavaScript.Bar().Content); }; page.Foo.onclick += delegate { apply(page.Foo, "Foo.js", () => new WithJavaScript.JavaScript.Foo().Content); }; @"Hello world".ToDocumentTitle(); // Send data from JavaScript to the server tier service.WebMethod2( @"A string from JavaScript.", value => value.ToDocumentTitle() ); }
/// <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) { new IHTMLButton { "go" }.AttachToDocument().WhenClicked( async button => { new IHTMLPre { "enter go" }.AttachToDocument(); var c = new IHTMLButton { "continue" }.AttachToDocument(); await base.DelayedClickHandler(c.async.onclick); c.Orphanize(); new IHTMLPre { "exit go" }.AttachToDocument(); } ); }
/// <summary> /// This is a javascript application. /// </summary> /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param> public Application(IApp page) { var c = "mymenu"; var css = Native.css[" ." + c]; new IHTMLPre { new { css.rule } }.AttachToDocument(); css.style.color = "blue"; new IHTMLButton { className = c, innerText = "menu1" }.AttachToDocument().With( async e => { while (await e.async.onclick) { css.style.display = IStyle.DisplayEnum.none; var back = new IHTMLButton { "go back from " + new { e.innerText } }.AttachToDocument(); await back.async.onclick; back.Orphanize(); css.style.display = IStyle.DisplayEnum.empty; } } ); new IHTMLButton { className = c, innerText = "menu2" }.AttachToDocument().With( async e => { while (await e.async.onclick) { css.style.display = IStyle.DisplayEnum.none; var back = new IHTMLButton { "go back from " + new { e.innerText } }.AttachToDocument(); await back.async.onclick; back.Orphanize(); css.style.display = IStyle.DisplayEnum.empty; } } ); }
/// <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) { // can we do the same with onclick already? new IHTMLButton { "encrypt" }.AttachToDocument().WhenClicked( async btn => { var data = Encoding.UTF8.GetBytes("hello world"); var enc = await this.Encrypt(data); // shall we show the encrypted bytes? // what about encrypte png/gif? // what about doing this in the worker thread? new IHTMLElement(IHTMLElement.HTMLElementEnum.hr).AttachToDocument(); foreach (var item in enc.bytes) { new IHTMLCode { " 0x" + item.ToString("x2") }.AttachToDocument(); } new IHTMLElement(IHTMLElement.HTMLElementEnum.hr).AttachToDocument(); var decrypt = new IHTMLButton { "decrypt" }.AttachToDocument(); await decrypt.async.onclick; decrypt.Orphanize(); var xdata = await this.Decrypt(enc); var xstring = Encoding.UTF8.GetString(xdata); new IHTMLPre { new { xstring } }.AttachToDocument(); } ); }
static void InitializeContnt(IDefaultPage page) { Action <dynamic> stream = x => { object time = x.time; object i = x.i; Native.document.title = new { time, i }.ToString(); Console.WriteLine(new { time, i }.ToString()); page.Content.innerText = new { time, i }.ToString(); }; dynamic window = Native.window; window.stream = stream; var stop = new IHTMLButton("Stop").AttachToDocument(); var iframe = new IHTMLIFrame { src = "/stream" }.AttachToDocument(); iframe.Hide(); page.Start.disabled = true; stop.onclick += delegate { stop.Orphanize(); page.Start.disabled = false; iframe.Orphanize(); }; Native.document.body.style.cursor = IStyle.CursorEnum.@default; }
// asus has 2015 that works? /// <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) { // http://www.sitepoint.com/using-fourier-transforms-web-audio-api/ new { }.With( async delegate { var start = new IHTMLButton { "connect" }; var stop = new IHTMLButton { "disconnect" }; var a = new AudioContext(); var o = a.createOscillator(); o.start(0); o.frequency.value = 440; o.type = OscillatorType.sawtooth; o.frequency.valueInput = new IHTMLInput { type = ScriptCoreLib.Shared.HTMLInputTypeEnum.range, min = 1, max = 2000 }.AttachToDocument(); new IHTMLLabel { () => $"frequency: { o.frequency.value }Hz" + $" type: { o.type }" }.AttachToDocument(); //.onchange += // eee => // { // var i = ((IHTMLInput)eee.Element); // o.frequency.value = i.valueAsNumber; // }; new IHTMLHorizontalRule { }.AttachToDocument(); new IHTMLButton { nameof(OscillatorType.sawtooth) }.AttachToDocument().onclick += delegate { o.type = OscillatorType.sawtooth; }; new IHTMLButton { nameof(OscillatorType.sine) }.AttachToDocument().onclick += delegate { o.type = OscillatorType.sine; }; new IHTMLButton { nameof(OscillatorType.square) }.AttachToDocument().onclick += delegate { o.type = OscillatorType.square; }; new IHTMLButton { nameof(OscillatorType.triangle) }.AttachToDocument().onclick += delegate { o.type = OscillatorType.triangle; }; new IHTMLHorizontalRule { }.AttachToDocument(); //s.Add() new IHTMLButton { "Beep()" }.AttachToDocument().onclick += async delegate { //Console.Beep(frequency: 400, duration: 300); o.frequency.value = 400; o.type = OscillatorType.square; o.connect(o.context.destination); await Task.Delay(300); o.disconnect(); }; new IHTMLButton { "Console.Beep()" }.AttachToDocument().onclick += delegate { Console.Beep(); //Console.Beep(frequency: 400, duration: 300); }; new IHTMLButton { () => $"Console.Beep({ o.frequency.value }Hz, 300)" }.AttachToDocument().onclick += delegate { Console.Beep(frequency: (int)o.frequency.value, duration: 300); }; retry: var ee = await start.AttachToDocument().async.onclick; start.Orphanize(); o.connect(a.destination); var e = await stop.AttachToDocument().async.onclick; stop.Orphanize(); o.disconnect(); goto retry; } ); }
/// <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) { // d = ((4 * _8CEABtNdQz66ZYUODttTfw(b)) / 3); Native.window.localStorage["body"].With( body => { var xbody = XElement.Parse(body); //page.body.ReplaceWith( page.body.AsXElement().ReplaceWith(xbody); } ); AtFoo = delegate { new IHTMLPre { "AtFoo" }.AttachToDocument(); }; binary = Encoding.UTF8.GetBytes("hash me").ToMD5Bytes(); var go = new IHTMLButton { "go " + binary.ToHexString() }.AttachToDocument().WhenClicked( async button => { await WebMethod2("hi"); new IHTMLPre { new { Counter } }.AttachToDocument(); } ); // X:\jsc.internal.svn\compiler\jsc.meta\jsc.meta\Commands\Rewrite\RewriteToJavaScriptDocument.InjectJavaScriptBootstrap.cs //Native.window.onbeforeunload += // delegate // { // // X:\jsc.svn\examples\javascript\test\TestSameServerResponseWithDifferentFields\TestSameServerResponseWithDifferentFields\Application.cs // // this will not work for refresh. why? should it? // Dispose(); // }; //e = ( function () { var c$69 = d.constructor; return 'Interfaces' in c$69 ? ('f7G82WqfyzOLoZ_b8v0KVxw' in c$69.Interfaces) : false; } )(); //f.asIDisposable = (d instanceof f7G82WqfyzOLoZ_b8v0KVxw ? d : null); //object x = this; //var isIDisposable = x is IDisposable; //// 0:37ms { isIDisposable = true, asIDisposable = } //var asIDisposable = x as IDisposable; //Console.WriteLine(new { isIDisposable, asIDisposable }); Native.window.onbeforeunload += delegate { //if (x is IDisposable) //{ // ((IDisposable)x).Dispose(); //} // dont save our button since we will re add it. go.Orphanize(); // did we not already resolve html to xelement in another example? // error on line 11 at column 79: Opening and ending tag mismatch: link line 0 and body Native.window.localStorage["body"] = Native.document.body.AsXElement().ToString(); }; }
/// <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) { // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2015/201503/20150323 // X:\jsc.svn\examples\javascript\Test\TestWebCrypto\TestWebCrypto\Application.cs // X:\jsc.svn\examples\javascript\async\Test\TestWebCryptoAsync\TestWebCryptoAsync\Application.cs // X:\jsc.svn\examples\javascript\Test\TestWebCryptoEncryption\TestWebCryptoEncryption\Application.cs // X:\jsc.svn\examples\javascript\Test\TestWebCryptoKeyExport\TestWebCryptoKeyExport\Application.cs // https://dvcs.w3.org/hg/webcrypto-api/raw-file/tip/spec/Overview.html // Protected Document Exchange // assetsLibrary with encryption/DLC ? new IHTMLButton { "generateKey in UI" }.AttachToDocument().onclick += async delegate { new IHTMLElement(IHTMLElement.HTMLElementEnum.hr).AttachToDocument(); var sw = Stopwatch.StartNew(); var publicExponent = new Uint8Array(new byte[] { 0x01, 0x00, 0x01 }); new IHTMLPre { "before generateKey " + new { sw.ElapsedMilliseconds } }.AttachToDocument(); // http://blog.engelke.com/2014/08/23/public-key-cryptography-in-the-browser/ var algorithm = new { name = "RSA-OAEP", hash = new { name = "SHA-256" }, modulusLength = 2048, publicExponent, }; var pgenerateKeyAsync = Native.crypto.subtle.generateKeyAsync(algorithm, false, new[] { "encrypt", "decrypt" }); // https://developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules/Promise.jsm/Promise new IHTMLPre { "after generateKey " + new { pgenerateKeyAsync, sw.ElapsedMilliseconds } }.AttachToDocument(); var key = await pgenerateKeyAsync; // continue generateKey {{ privateKey = [object CryptoKey], publicKey = [object CryptoKey], ElapsedMilliseconds = 5021 }} new IHTMLPre { "continue generateKey " + new { key.privateKey, key.publicKey, key.publicKey.extractable, sw.ElapsedMilliseconds } }.AttachToDocument(); var ybytes = Encoding.UTF8.GetBytes("hello world"); new IHTMLPre { "before encrypt " + new { sw.ElapsedMilliseconds } }.AttachToDocument(); var pencrypt = Native.crypto.subtle.encryptAsync( algorithm, key.publicKey, ybytes ); new IHTMLPre { "after encrypt " + new { pencrypt, sw.ElapsedMilliseconds } }.AttachToDocument(); var xbytes = await pencrypt; new IHTMLPre { "continue encrypt " + new { xbytes.Length, sw.ElapsedMilliseconds } }.AttachToDocument(); // continue encrypt {{ Length = 256, ElapsedMilliseconds = 5021 }} new IHTMLElement(IHTMLElement.HTMLElementEnum.hr).AttachToDocument(); foreach (var item in xbytes) { new IHTMLCode { " 0x" + item.ToString("x2") }.AttachToDocument(); } new IHTMLElement(IHTMLElement.HTMLElementEnum.hr).AttachToDocument(); var decrypt = new IHTMLButton { "decrypt" }.AttachToDocument(); await decrypt.async.onclick; decrypt.Orphanize(); new IHTMLPre { "before decryptAsync " + new { xbytes, xbytes.Length } }.AttachToDocument(); var zbytes = await Native.crypto.subtle.decryptAsync(algorithm, key.privateKey, xbytes ); new IHTMLElement(IHTMLElement.HTMLElementEnum.hr).AttachToDocument(); foreach (var item in zbytes) { new IHTMLCode { " 0x" + item.ToString("x2") }.AttachToDocument(); } new IHTMLElement(IHTMLElement.HTMLElementEnum.hr).AttachToDocument(); var zstring = Encoding.UTF8.GetString(zbytes); // which is it? new IHTMLPre { new { zstring } }.AttachToDocument(); }; }
/// <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); }
/// <summary> /// This is a javascript application. /// </summary> /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param> public Application(IDefault page) { Action</*dynamic*/ IHTMLInput, string, Func<IHTMLLink>> apply = (btn, text, css) => { btn.disabled = true; var Content = css(); Content.AttachToHead(); var AddDynamicRule = new IHTMLButton { innerText = "add dynamic rule to " + text }; var DisableStyle = new IHTMLButton { innerText = "disable style " + text }; AddDynamicRule.AttachTo(page.Content); AddDynamicRule.onclick += delegate { AddDynamicRule.disabled = true; var rule1 = Content.StyleSheet.AddRule("button", s => { s.style.color = "green"; } ); var DisableDynamicRule = new IHTMLButton { innerText = "disable dynamic rule from " + text }; DisableDynamicRule.AttachTo(page.Content); DisableStyle.onclick += delegate { DisableDynamicRule.Orphanize(); }; DisableDynamicRule.onclick += delegate { // remove the last rule? :) Content.StyleSheet.RemoveRule(Content.StyleSheet.Rules.Length - 1); AddDynamicRule.disabled = false; DisableDynamicRule.Orphanize(); }; }; DisableStyle.AttachTo(page.Content); DisableStyle.onclick += delegate { AddDynamicRule.Orphanize(); DisableStyle.Orphanize(); Content.Orphanize(); btn.disabled = false; }; }; page.Bar.onclick += delegate { apply(page.Bar, "Boo.css", () => new WithStylesheet.Styles.BooStyle().Content); }; page.Foo.onclick += delegate { apply(page.Foo, "Foo.css", () => new WithStylesheet.Styles.FooStyle().Content); }; @"Hello world".ToDocumentTitle(); // Send data from JavaScript to the server tier service.WebMethod2( @"A string from JavaScript.", value => value.ToDocumentTitle() ); }
/// <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) { // Initialize ApplicationSprite sprite.AttachSpriteToDocument(); // how did it work before? #if v #region visualize Action<bool, byte[], Action<double, double, Action<double>, IWindow>> visualize_and_getpadding = null; visualize_and_getpadding = (allowpadding, bytes, set_padding) => { var r = new BinaryReader(new MemoryStream(bytes)); var floats = new double[bytes.Length / 4]; //Console.WriteLine("floats " + new { floats.Length }); for (int i = 0; i < floats.Length; i++) { // X:\jsc.svn\core\ScriptCoreLib\JavaScript\BCLImplementation\System\IO\BinaryReader.cs // do we do floats? floats[i] = r.ReadSingle(); } var paddingmode_yellow = allowpadding; var paddingsamples_yellow = 0; var paddingmode_yellow_agg = 0.0; var paddingmode_yellow_grace = 411; var paddingmode_red = allowpadding; var paddingsamples_red = 0; var paddingmode_red_agg = 0.0; var paddingmode_red_grace = 411; #region max var min = 0.0; var minset = false; var max = 0.0; var maxset = false; for (int ix = 0; ix < floats.Length; ix += 2) { // arg[0] is typeof System.Single //script: error JSC1000: No implementation found for this native method, please implement [static System.Console.WriteLine(System.Single)] var l0 = floats[ix]; var r0 = floats[ix + 1]; if (l0 != 0) if (minset) { min = Math.Min(min, l0); } else { min = l0; minset = true; } if (maxset) { max = Math.Max(max, l0); } else { max = l0; maxset = true; } } var absmax = max.Max(Math.Abs(min)); #endregion #region paddingmode_yellow for (int ix = 0; ix < floats.Length; ix += 2) { // arg[0] is typeof System.Single //script: error JSC1000: No implementation found for this native method, please implement [static System.Console.WriteLine(System.Single)] var l0 = floats[ix]; var r0 = floats[ix + 1]; if (paddingmode_yellow) { // discard noise if (Math.Abs(l0) > 0.08 * absmax) paddingmode_yellow_agg += Math.Abs(l0); } if (paddingmode_yellow_agg > absmax * 2.1) { if (Math.Abs(l0) < 0.02 * absmax) { paddingmode_yellow = false; } } if (paddingmode_yellow) { paddingsamples_yellow++; if (paddingmode_yellow_agg > absmax * 3.2) { if (paddingmode_yellow_grace > 0) { paddingmode_yellow_grace--; } else { // rollback paddingsamples_yellow -= 411; paddingmode_yellow = false; } } } } #endregion // count down while near zero, then wait for zero #region paddingmode_red for (int ix = floats.Length - 1; ix >= 0; ix -= 2) { var l0 = floats[ix]; var r0 = floats[ix + 1]; if (paddingmode_red) { // discard noise if (Math.Abs(l0) > 0.08 * absmax) paddingmode_red_agg += Math.Abs(l0); } if (paddingmode_red_agg > absmax * 2.1) { if (Math.Abs(l0) < 0.02 * absmax) { paddingmode_red = false; } } if (paddingmode_red) { paddingsamples_red++; if (paddingmode_red_agg > absmax * 3.2) { if (paddingmode_red_grace > 0) { paddingmode_red_grace--; } else { // rollback paddingsamples_red -= 411; paddingmode_red = false; } } } } #endregion var w = new IWindow(); w.onload += delegate { Console.WriteLine("onload"); try { //BitConverter.ToSingle( w.document.body.style.margin = "0px"; // verbose huh. svg::svg? var svg = new ISVGSVGElement().AttachTo(w.document.body); var path_current = new ISVGPathElement().AttachTo(svg); path_current.setAttribute("style", "stroke-width: 5; stroke: blue; fill: none;"); var path = new ISVGPathElement().AttachTo(svg); path.setAttribute("style", "stroke: black; fill: none;"); var path_loop2 = new ISVGPathElement().AttachTo(svg); path_loop2.setAttribute("style", "stroke: green; fill: none;"); var xw = new StringBuilder().Append("M0,400 "); // done { min = 7.847271400218976e-44, max = 2.320612754833406e-38, paddingsamples = 1337 } w.document.body.style.minHeight = 800 + "px"; var scalex = 4 / 44.1; w.document.body.style.minWidth = floats.Length * scalex * 2 + "px"; w.document.body.style.overflow = IStyle.OverflowEnum.auto; // we should have 4096 stereo samples var samples = floats.Length; var samplesperchannel = samples / 2; #region xw for (int ix = 0; ix < floats.Length; ix += 2) { // arg[0] is typeof System.Single //script: error JSC1000: No implementation found for this native method, please implement [static System.Console.WriteLine(System.Single)] var l0 = floats[ix]; var r0 = floats[ix + 1]; // 0 is -60db // max is 0db // http://audio.tutsplus.com/articles/general/all-youll-ever-need-to-know-about-samples-and-bits/ //iy = (200.0 - l0 * 1E37 * 200); var iy = (400.0 - l0 * 400.0); xw.Append(" L" + (ix * scalex) + "," + iy); //Console.WriteLine("" + ReadFloat32(i)); } #endregion #region xw_loop2 var xw_loop2 = new StringBuilder(); for (int ix = paddingsamples_yellow * 2; ix < floats.Length - paddingsamples_red * 2; ix += 2) { // arg[0] is typeof System.Single //script: error JSC1000: No implementation found for this native method, please implement [static System.Console.WriteLine(System.Single)] var l0 = floats[ix]; var r0 = floats[ix + 1]; var iy = (400.0 - l0 * 400.0); if (xw_loop2.ToString().Length == 0) xw_loop2.Append(" M" + ((2 * (samplesperchannel - paddingsamples_red - paddingsamples_yellow) * scalex) + ((ix + 1) * scalex)) + "," + iy); else xw_loop2.Append(" L" + ((2 * (samplesperchannel - paddingsamples_red - paddingsamples_yellow) * scalex) + ((ix + 1) * scalex)) + "," + iy); } #endregion // A frame rate of 44,100 is 44,100 samples per SECOND, or 44.1 kHz. var duration_seconds = samplesperchannel / 44100; w.document.title = new { samplesperchannel, paddingsamples_yellow, paddingsamples_red, duration_seconds }.ToString(); Console.WriteLine("done " + new { min, max, paddingsamples_yellow, paddingsamples_red }); //xw.Append(" L30,210"); path.d = xw.ToString(); path_loop2.d = xw_loop2.ToString(); var path_zero = new ISVGPathElement().AttachTo(svg); path_zero.setAttribute("style", "stroke-width: 1; stroke: gray; fill: none;"); path_zero.d = "M0,400 L" + (2 * samplesperchannel * scalex) + ",400"; //var path_leftpadding = new ISVGPathElement().AttachTo(svg); //path_leftpadding.setAttribute("style", "stroke-width: 5; stroke: red; fill: none;"); //path_leftpadding.d = "M0,400 L" + (2 * paddingsamples * scalex) + ",400"; var path_leftpadding_yellow = new ISVGPathElement().AttachTo(svg); path_leftpadding_yellow.setAttribute("style", "stroke-width: 3; stroke: yellow; fill: none;"); path_leftpadding_yellow.d = "M0,400 L" + (2 * paddingsamples_yellow * scalex) + ",400"; var path_leftpadding_red = new ISVGPathElement().AttachTo(svg); path_leftpadding_red.setAttribute("style", "stroke-width: 3; stroke: red; fill: none;"); path_leftpadding_red.d = "M" + (2 * (samplesperchannel - paddingsamples_red) * scalex) + ",400 L" + (2 * (samplesperchannel - 0) * scalex) + ",400"; Action<double> set_position = position => { var x = (2 * position * scalex); path_current.d = "M" + x + ",50 L" + x + ",750 L" + (x + MP3PitchLoop.BLOCK_SIZE * 2 * scalex) + ",750 L" + (x + MP3PitchLoop.BLOCK_SIZE * 2 * scalex) + ",50 L" + x + ",50"; }; set_padding( paddingsamples_yellow, paddingsamples_red, set_position, w ); set_position(paddingsamples_yellow); } catch (Exception error) { Console.WriteLine("error " + new { error.Message, error }); } Console.WriteLine("done"); }; }; #endregion #region f Func<IHTMLButton, Action<string, PlayAtAndAllowToStop>> f = x => (base64, playat) => { var bytes = Convert.FromBase64String(base64); visualize_and_getpadding( true, bytes, (paddingleft, paddingright, set_position, w) => { var toolbar = new IHTMLDiv().AttachTo(w.document.body); toolbar.style.SetLocation(4, 4); toolbar.style.position = IStyle.PositionEnum.@fixed; new IHTMLButton { innerText = "play" }.AttachTo(toolbar).WhenClicked( delegate { playat( "" + paddingleft, "" + paddingright, yield_stop: stop => { var stopbtn = new IHTMLButton { innerText = "Stop" }; stopbtn.WhenClicked( delegate { stop(); stopbtn.Orphanize(); } ); stopbtn.AttachTo(toolbar); }, yield_position_anddiagnostics: (position, diagnostics) => { set_position(Convert.ToDouble(position)); if (!string.IsNullOrEmpty(diagnostics)) { Console.WriteLine(diagnostics); var diagnostics_bytes = Convert.FromBase64String(diagnostics); visualize_and_getpadding( false, diagnostics_bytes, delegate { } ); } } ); } ); } ); }; #endregion page.VisualizeDiesel.WhenClicked( delegate { sprite.BytesForDiesel(f(page.VisualizeDiesel)); } ); page.VisualizeHelicopter.onclick += delegate { sprite.BytesForHelicopter(f(page.VisualizeHelicopter)); }; page.VisualizeJeep.onclick += delegate { sprite.BytesForJeep(f(page.VisualizeJeep)); }; page.VisualizeTone.onclick += delegate { sprite.BytesForTone(f(page.VisualizeTone)); }; page.VisualizeSandrun.onclick += delegate { sprite.BytesForSandrun(f(page.VisualizeSandrun)); }; #endif page.PlayDiesel.onclick += delegate { sprite.PlayDiesel(); }; page.PlayHelicopter.onclick += delegate { sprite.Playhelicopter1(); }; page.PlayJeep.onclick += delegate { sprite.PlayJeep(); }; page.PlayTone.onclick += delegate { sprite.PlayTone(); }; page.PlaySandrun.onclick += delegate { sprite.PlaySandrun(); }; }
/// <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) { that = this; this.page = page; Native.window.localStorage["poison"] = "1"; page.Login.Historic( async scope => { var button = new IHTMLButton { innerText = "Login" }; if (that.cookie.BooleanValue == false) { that.page.Login.style.borderLeft = "1em solid red"; //that.page.Login.innerText = "Home"; button.AttachToDocument(); button.onclick += delegate { that.page.Login.style.borderLeft = "1em solid green"; that.cookie.BooleanValue = true; button.disabled = true; }; } else { that.page.Login.style.borderLeft = "1em solid green"; } await scope; button.Orphanize(); that.page.Login.style.borderLeft = ""; } ); page.View1.Historic( async scope => { if (that.cookie.BooleanValue == false) { that.page.View1.style.borderLeft = "1em solid red"; } else { that.page.View1.style.borderLeft = "1em solid green"; } await scope; that.page.View1.style.borderLeft = ""; } ); page.View2.Historic( async scope => { if (that.cookie.BooleanValue == false) { that.page.View2.style.borderLeft = "1em solid red"; } else { that.page.View2.style.borderLeft = "1em solid green"; } await scope; that.page.View2.style.borderLeft = ""; } ); page.Logout.Historic( async scope => { that.page.Logout.style.borderLeft = "1em solid red"; that.cookie.BooleanValue = false; await scope; that.page.Logout.style.borderLeft = ""; } ); }
public Application(IApp page) { // X:\jsc.svn\examples\javascript\chrome\extensions\ChromeTabsExperiment\ChromeTabsExperiment\Application.cs dynamic self = Native.self; dynamic self_chrome = self.chrome; object self_chrome_tabs = self_chrome.tabs; #region self_chrome_tabs if (self_chrome_tabs != null) { Console.WriteLine("extension is now running..."); #region isYTMissing new { }.With( async delegate { var vid = "TXExg6Xj3aA"; var thumbnail = $"https://img.youtube.com/vi/{vid}/0.jpg"; var thumbnailImage = new IHTMLImage { src = thumbnail }; // wont get those events for 404? //Native.window.onerror += err => //{ // Console.WriteLine( // "window onerror " + // new // { // thumbnail, // err, // thumbnailImage.complete, // thumbnailImage.width, // thumbnailImage.naturalWidth, // thumbnailImage.naturalHeight // } // ); //}; //thumbnailImage.onerror += err => //{ // Console.WriteLine( // "thumbnailImage onerror " + // new // { // thumbnail, // err, // thumbnailImage.complete, // thumbnailImage.width, // thumbnailImage.naturalWidth, // thumbnailImage.naturalHeight // } // ); //}; await thumbnailImage.async.oncomplete; Console.WriteLine( new { thumbnail, thumbnailImage.complete, thumbnailImage.width, thumbnailImage.naturalWidth, thumbnailImage.naturalHeight } ); var thumbnailBytes = await thumbnailImage.async.bytes; Console.WriteLine( new { thumbnailBytes.Length } ); // crc? var sw = Stopwatch.StartNew(); var crc = CRCExample.ActionScript.Crc32Helper.GetCrc32(thumbnailBytes); // 247ms {{ crc = 9e47636d, ElapsedMilliseconds = 7 }} var isYTMissing = 0x9e47636d == crc; Console.WriteLine( new { crc = crc.ToString("x8"), sw.ElapsedMilliseconds, isYTMissing } ); } ); #endregion var oncePerTab = new Dictionary<TabIdInteger, object>(); chrome.tabs.Updated += async (i, x, tab) => { // chrome://newtab/ // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2015/201504/20150423 #region tab if (tab == null) { Console.WriteLine("bugcheck :198 iframe? called with the wrong state?"); return; } Console.WriteLine("enter async chrome.tabs.Updated " + new { tab.url, tab.status }); if (tab.url.StartsWith("chrome-devtools://")) { return; } if (tab.url.StartsWith("chrome://")) return; // while running tabs.insertCSS: The extensions gallery cannot be scripted. if (tab.url.StartsWith("https://chrome.google.com/webstore/")) return; if (tab.status != "complete") { Console.WriteLine("exit async chrome.tabs.Updated, not complete?"); return; } #endregion if (oncePerTab.ContainsKey(tab.id)) return; oncePerTab[tab.id] = new object(); // where is the hop to iframe? // X:\jsc.svn\examples\javascript\Test\TestSwitchToIFrame\TestSwitchToIFrame\Application.cs // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2015/201504/20150403 //await (HopToChromeTab)tab.id; Console.WriteLine("chrome.tabs.Updated will delay, to increment state"); // why do we need this fake await? // cannot resume state otherwise? await Task.Delay(1); // // X:\jsc.svn\market\synergy\javascript\chrome\chrome\chrome.idl var tabIdString = Convert.ToString((object)tab.id); // 13032ms chrome.tabs.Updated will HopToChromeTab {{ tabIdString = 608 }} Console.WriteLine("chrome.tabs.Updated will HopToChromeTab " + new { tabIdString }); // state1: await (HopToChromeTab)tab; // TypeError: Cannot set property 'ztabIdString' of null ztabIdString = tabIdString; //await tab.id; // are we now on the tab? // can we jump back? // 531ms yt found {{ Length = 108 }} // X:\jsc.svn\examples\javascript\test\TestShadowForIFrame\TestShadowForIFrame\Application.cs //var yt1 = Native.document.querySelectorAll(" [class='youtube-player']"); // <iframe width="420" height="315" src="https://www.youtube.com/embed/sJIh70IZua8" frameborder="0" allowfullscreen=""></iframe> // 503ms create iframe... {{ ztabIdString = null }} // what about jumping with files/uploads? Console.WriteLine("create iframe... " + new { ztabIdString }); iframe = new IHTMLIFrame { //src = "about:blank" //new XElement("button", "did extension send us our code? " ) new XElement("script", new XAttribute("src", url), " ") }.AttachTo( Native.document.documentElement ); var yt1 = Native.document.querySelectorAll("iframe"); Console.WriteLine("yt found " + new { yt1.Length }); yt1.WithEach( async e => { //if (e == null) // return; var xiframe = (IHTMLIFrame)e; //13ms yt found { { Length = 9 } } //VM1190: 51533 515ms enter catch //{ // mname = < 01ed > ldloca.s.try } ClauseCatchLocal: // VM1190: 51533 515ms TypeError: Cannot read property 'src' of null if (!xiframe.src.StartsWith("https://www.youtube.com/")) { return; } // can we interact, swap the videos? var size = new { xiframe.clientWidth, xiframe.clientHeight }; var swap = new IHTMLDiv { //new IHTMLPre { xiframe.src }, //new IHTMLContent { } }; new IStyle(swap) { backgroundColor = "yellow", width = size.clientWidth + "px", height = size.clientHeight + "px", overflow = IStyle.OverflowEnum.hidden }; // https://code.google.com/p/dart/issues/detail?id=19561 // 27ms HierarchyRequestError: Failed to execute 'createShadowRoot' on 'Element': Author-created shadow roots are disabled for this element. //swap.AttachTo(xiframe.shadow); xiframe.ReplaceWith(swap); var sh = new IHTMLDiv { }.AttachTo(swap.shadow); var vid = xiframe.src.TakeUntilIfAny("?").SkipUntilOrEmpty("/embed/"); // Remote Address:[2a00: 1450:400f:802::100e]:443 //Request URL: https://img.youtube.com/vi/TXExg6Xj3aA/0.jpg //Request Method: GET //Status Code: 404 OK var thumbnail404 = $"https://img.youtube.com/vi/{vid}/0.jpg"; // lets look at the image. is the video removed? // https://img.youtube.com/vi/TXExg6Xj3aA/0.jpg // http://stackoverflow.com/questions/22097747/getimagedata-error-the-canvas-has-been-tainted-by-cross-origin-data //.AttachToHead(); new IStyle(sh) { width = size.clientWidth + "px", height = size.clientHeight + "px", overflow = IStyle.OverflowEnum.hidden, position = IStyle.PositionEnum.relative, backgroundImage = $"url('{thumbnail404}')", }; //var info = new IHTMLPre { xiframe.src }; var info = new IHTMLPre { new { vid } }; // so we can later find it again... lookup_info[thumbnail404] = info; // assume its not missing until we know more lookup_info_YTmissing[thumbnail404] = false; info.AttachTo(sh); new IStyle(info) { backgroundColor = "rgba(0,0,255, 0.5)", color = "rgba(255,255,0, 0.9)", left = "0px", bottom = "0px", right = "0px", //height = size.clientHeight + "px", position = IStyle.PositionEnum.absolute }; // at this point we need to consult the extension as it can download the bytes new { }.With( async delegate { var xtabIdString = ztabIdString; var xthumbnail404 = thumbnail404; // 517ms about to jump to extension to inspect the damn image... {{ xthumbnail404 = https://img.youtube.com/vi/TXExg6Xj3aA/0.jpg, xtabIdString = 608 }} Console.WriteLine("about to jump to extension to inspect the damn image... " + new { xthumbnail404, xtabIdString }); // fixup? await Task.Delay(1); await default(HopToExtension); Console.WriteLine("about to jump to extension to inspect the damn image... done " + new { xthumbnail404, xtabIdString }); // 43228ms about to jump to extension to inspect the damn image... done {{ xthumbnail404 = https://img.youtube.com/vi/TXExg6Xj3aA/0.jpg, xtabIdString = 608 }} // can we jump back once we know what it was? var thumbnailImage = new IHTMLImage { src = xthumbnail404 }; await thumbnailImage.async.oncomplete; var thumbnailBytes = await thumbnailImage.async.bytes; var sw = Stopwatch.StartNew(); var crc = CRCExample.ActionScript.Crc32Helper.GetCrc32(thumbnailBytes); // we only do strings at this point, not integers, we could do booleans tho... var isYTMissing = Convert.ToString(0x9e47636d == crc); var xtab = await chrome.tabs.get(tabId: Convert.ToInt32(xtabIdString)); //xthumbnail404 = https://img.youtube.com/vi/BZIeqnQ1rY0/0.jpg, isYTMissing = false, xtabIdString = 608, url = https://zproxy.wordpress.com/2015/04/05/thought-form-magicians/ }} // xthumbnail404 = https://img.youtube.com/vi/TXExg6Xj3aA/0.jpg, isYTMissing = true, xtabIdString = 608, url = https://zproxy.wordpress.com/2015/04/05/thought-form-magicians/ }} Console.WriteLine(">> " + new { xthumbnail404, isYTMissing, xtabIdString, xtab.url }); // can we jump back to the tab to color it red if missing? // 43340ms >> {{ xthumbnail404 = https://img.youtube.com/vi/TXExg6Xj3aA/0.jpg, isYTMissing = true, xtabIdString = 608 }} //(HopToChromeTab) // ok now we now what tab we are in but even if we jump back. we wont have a ref to the infobar? await (HopToChromeTab)xtab; Console.WriteLine(">> " + new { xthumbnail404, isYTMissing, xtabIdString } + " back in the tab?"); // would the old variables be reconnected for us? // jumps should be able to resume an old startemachine. lookup_info_YTmissing[xthumbnail404] = Convert.ToBoolean(isYTMissing); var xinfo = lookup_info[xthumbnail404]; //xthumbnail404 = https://img.youtube.com/vi/BZIeqnQ1rY0/0.jpg, isYTMissing = false, xtabIdString = 744 }} back in the tab? if (Convert.ToBoolean(isYTMissing)) { // yikes. video pulled! new IStyle(xinfo) { backgroundColor = "rgba(255,0,0, 0.7)", }; new IHTMLSpan { " do we have a local copy?" }.AttachTo(xinfo); // we should send udp to the archive server? // if it has how can we load it up? return; } new IStyle(xinfo) { backgroundColor = "rgba(255,255,0, 0.5)", }; } ); // https://www.youtube.com/embed/jQLNMljadyo?vers // https://www.youtube.com/embed/M4RBW85J4Cg // http://img.youtube.com/vi/<insert-youtube-video-id-here>/0.jpg await sh.async.onmouseover; // no reason to load it. its missing! if (lookup_info_YTmissing[thumbnail404]) return; xiframe.AttachTo(sh); info.AttachTo(sh); var copyToToolbar = new IHTMLButton { "+" }.AttachTo(info); await copyToToolbar.async.onclick; copyToToolbar.Orphanize(); //width = "128px", //xiframe.style.transform = "scale(0.2)"; new IStyle(xiframe) { width = (128) + "px", height = (96) + "px", }; // This video contains content from WMG. It is restricted from playback on certain sites. xiframe.AttachTo( //iframe.contentWindow.document.documentElement iframe.contentWindow.document.body ); } ); Console.WriteLine("create iframe... done"); //iframe.allowTransparency = true; // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2015/201504/20150423 // __8__1 is null. why? a struct? // b.__this.__8__1.scope = new ctor$vQEABrCB_bTmuL0jGQp_bnVw(b.__this._iframe_5__2); // oh crap. the container is initialized before await (HopToChromeTab)tab; thus lost due to context switch. var scope = new { iframe }; //Console.WriteLine("iframe visible? " + new { scope }); new IStyle(iframe) { borderWidth = "0", // wont animate? transition = "left 300ms linear", // dont want the white box while it loads.. backgroundColor = "rgba(0, 0, 255, 0)", position = IStyle.PositionEnum.@fixed, //left = "1px", top = "32px", width = "128px", // animateIFrame // pre hide it left = "-120px", //height = "100px", // wont work on slashdot? //bottom = "3em" // can we be topmost? //zIndex = 30000 zIndex = 1999999999 }; fixHeight(iframe); animateIFrame(iframe); //var __iframe = iframe; await iframe.async.onload; //new IStyle(iframe) //{ // backgroundColor = "rgba(0, 0, 255, 0.7)", //}; Console.WriteLine("lets hop from tab context to iframe context... "); await (HopToIFrame)iframe; Console.WriteLine("lets hop from tab context to iframe context... done!"); new IStyle(Native.document.body) { margin = "0px", //marginRight = "1em", padding = "0px", paddingRight = "1em", transition = "background-color 300ms linear", backgroundColor = "rgba(0, 0, 255, 0.1)", //border = "1px solid red" }; var button4 = new IHTMLButton { "hop to parent, extension, app" }.AttachToDocument(); new IStyle(button4) { display = IStyle.DisplayEnum.block }; // not yet. need a new example button4.disabled = true; //Native.body.backgroundColor = "rgba(0, 0, 255, 0.7)"; //var text3 = new IHTMLTextArea { value = "hey" }.AttachToDocument(); // need to use static, as scope variables are being encapsulated, and due to context jumps we dont support it yet text3 = new IHTMLTextArea { value = "hey" }.AttachToDocument(); text3.style.width = "100%"; var button3 = new IHTMLButton { "hop to parent, extension" }.AttachToDocument(); new IStyle(button3) { display = IStyle.DisplayEnum.block }; button3.onclick += async delegate { // can we hop back? var data3 = text3.value; Console.WriteLine("enter button3 " + new { data3 }); // 2602ms enter button3 {{ data3 = hey }} // why do we need this fake await? // cannot resume state otherwise? await Task.Delay(1); await default(HopToParent); var tab_title = Native.document.title; // 3105ms are strings being synchronized to iframe? {{ tab_title = IANA — IANA-managed Reserved Domains, data3 = null }} Console.WriteLine("are strings being synchronized from iframe? " + new { tab_title, data3 }); /// 2926ms will hop back to extension!? can we resume later? await default(HopToExtension); //Native.window.alert("hi! i am back home! do we even know which tab we were in? did i get some data yet? " + new { tab_title }); Console.WriteLine("hi! i am back home! do we even know which tab we were in? did i get some data yet? " + new { tab_title, data3 }); // 13844ms hi! i am back home! do we even know which tab we were in? did i get some data yet? {{ tab_title = IANA — IANA-managed Reserved Domains }} // lets guess which tab we clicked on? var tt = await chrome.tabs.getCurrent(); // https://developer.chrome.com/extensions/tabs // https://developer.chrome.com/extensions/windows // https://developer.chrome.com/extensions/processes //chrome.runtime. new chrome.Notification( title: new { data3, tt }.ToString() ); //chrome.tabs.rel // can we do appwindow here or we need to jump out of extension? }; var button2 = new IHTMLButton { "hop to parent" }.AttachToDocument(); new IStyle(button2) { display = IStyle.DisplayEnum.block }; button2.onclick += async delegate { // can we hop back? Console.WriteLine("enter button2"); // why do we need this fake await? // cannot resume state otherwise? await Task.Delay(1); await default(HopToParent); var tab_title = Native.document.title; Console.WriteLine("are strings being synchronized to iframe? " + new { tab_title }); // we are jumping back, yet into a new state machine. //Native.window.alert("hi! in a tab, in an extension! " + new //{ // Native.document.title // , // iframe //}); // can we jump back? is the iframe awaiting for multiple jumps? await (HopToIFrame)iframe; Native.window.alert("hi! iframe, in a tab, in an extension! " + new { Native.document.title, tab_title }); // ok. we now know how to // jump from extension to tab to iframe to tab to iframe // what about workers, and jumping back to extension? // but likely we did not jump to the same data? }; var button1 = new IHTMLButton { "click me" }.AttachToDocument(); new IStyle(button1) { display = IStyle.DisplayEnum.block }; //new { }.With( // async delegate // { // // stack variables not visible, why? // while (await button1.async.onmouseover) // { // new IStyle(Native.document.body) // { // backgroundColor = "rgba(0, 0, 255, 0.8)", // }; // await button1.async.onmouseout; // new IStyle(Native.document.body) // { // backgroundColor = "rgba(0, 0, 255, 0.2)", // }; // } // } //); //oldschool as a workaround button1.onclick += delegate { Native.window.alert("hi! iframe, in a tab, in an extension! " + new { Native.document.title }); }; button1.onmouseover += e => { new IStyle(Native.document.body) { backgroundColor = "rgba(255, 0, 0, 0.9)", }; e.stopPropagation(); }; button1.onmouseout += delegate { new IStyle(Native.document.body) { backgroundColor = "rgba(0, 0, 255, 0.1)", }; }; // we are in iframe! Native.document.onmouseover += delegate { new IStyle(Native.document.body) { backgroundColor = "rgba(0, 0, 255, 0.3)", }; }; Native.document.onmouseout += delegate { new IStyle(Native.document.body) { backgroundColor = "rgba(0, 0, 255, 0.1)", }; }; //var f = new IHTMLButton { "in the frame! click to notify parent" }.AttachToDocument(); //await default(HopToParent); // why need this stackfix? //var stackfix_iframe = iframe; // new { }.With( // async delegate // { // while (await Native.window.async.onresize) // { // stackfix_iframe.style.height = (Native.window.Height - 64) + "px"; // } // } //); // X:\jsc.svn\examples\javascript\Test\TestHopFromIFrame\TestHopFromIFrame\Application.cs // can we jump? // <div class="player-video-title">Ariana Grande - One Last Time (Official)</div> //Native.document.title = "(" + Native.document.title + ")"; // X:\jsc.svn\examples\javascript\xml\FindByClassAndObserve\FindByClassAndObserve\Application.cs // luckyly its only hidden... no need to await the element and find it later // <span id="eow-title" class="watch-title " dir="ltr" title="THORnews Weird Weather Watch! Wind Dragon inbound to USA Pacific Coast!"> //var yt0 = Native.document.querySelectorAll(" [class='player-video-title']"); //var yt1 = Native.document.querySelectorAll(" [class='watch-title ']"); //yt0.Concat(yt1).WithEach( // async e => // { // do // { // Native.document.title = e.innerText; // // X:\jsc.svn\examples\javascript\chrome\extensions\ChromeExtensionHopToTabThenIFrame\ChromeExtensionHopToTabThenIFrame\Application.cs // // we would need to jump back here to do extension notification // // the jump back would be to another state machine tho // // we would need other ports opened? // Native.document.documentElement.style.borderLeft = "1em solid yellow"; // for (int xi = 0; xi < 5; xi++) // { // Native.body.style.borderLeft = "1em solid yellow"; // await Task.Delay(100); // Native.body.style.borderLeft = "1em solid black"; // await Task.Delay(100); // } // Native.document.documentElement.style.borderLeft = "1em solid red"; // // or actually instead of jumping back we need to send back progress? // } // while (await e.async.onmutation); // } // ); // lets start monitoring }; return; } #endregion // 420ms TypeError: Cannot read property 'url' of null Console.WriteLine("nop"); #if true #region inside iframe if (Native.window.parent != Native.window) { // X:\jsc.svn\examples\javascript\chrome\extensions\ChromeExtensionHopToTabThenIFrame\ChromeExtensionHopToTabThenIFrame\Application.cs // inside iframe new { }.With( async delegate { // start the handshake // we gain intellisense, but the type is partal, likely not respawned, acivated, initialized //var m = await Native.window.parent.postMessageAsync<TestSwitchToServiceContextAsync.ShadowIAsyncStateMachine>(); // new IHTMLPre { // "inside iframe awaiting onmessage" //}.AttachToDocument(); // first null jump //Native.window.parent.postMessage(r.shadowstate); var m = await Native.window.parent.postMessageAsync(default(TestSwitchToServiceContextAsync.ShadowIAsyncStateMachine)); Console.WriteLine("iframe got the first state..."); // we can now send one hop back? InternalInvoke(m.data); } ); return; } #endregion #endif Console.WriteLine("nop"); // we made the jump? //Native.body.style.borderLeft = "0em solid red"; // yes we did. can we talk to the chrome extension? // lets do some SETI // The runtime.onMessage event is fired in each content script running in the specified tab for the current extension. // Severity Code Description Project File Line //Error 'runtime.onMessage' is inaccessible due to its protection level ChromeExtensionHopToTabThenIFrame X:\jsc.svn\examples\javascript\chrome\extensions\ChromeExtensionHopToTabThenIFrame\ChromeExtensionHopToTabThenIFrame\Application.cs 272 // public static event System.Action<object, object, object> Message Action<object> PostToExtension = null; #region Connect chrome.runtime.Connect += port => { Console.WriteLine("chrome.runtime.Connect " + new { port.name, port.sender }); // 8295ms will invoke sendResponse... done?? {{ message = jump! }} //port.postMessage("jump! " + new { port.name, port.sender }); PostToExtension = xdata => { // PostToExtension {{ xdata = [object Object] }} Console.WriteLine("PostToExtension " + new { xdata }); //Console.WriteLine("PostToExtension " + new { xdata = JSON.stringify(xdata) }); port.postMessage(xdata); }; }; #endregion #region chrome.runtime.Message chrome.runtime.Message += (object message, chrome.MessageSender sender, IFunction sendResponse) => { var s = (TestSwitchToServiceContextAsync.ShadowIAsyncStateMachine)message; if (url != null) { Console.WriteLine("jumping back to tab for more? done"); InternalInvoke(s); return; } Console.WriteLine("chrome.runtime.Message " + new { s.state, sender.id, code = s.code.Length }); // at this point we can initialize hop to iframe since we have the code we can actually use? // 276ms xonmessage {{ state = 1, id = fkgibadjpabiongmgoeomdbcefhabmah, code = 3296612 }} #region url var aFileParts = new[] { s.code }; var oMyBlob = new Blob(aFileParts, new { type = "text/javascript" }); //var url = oMyBlob.ToObjectURL(); url = URL.createObjectURL(oMyBlob); #endregion Console.WriteLine("will we want to jump back to extension?"); HopToExtension.VirtualOnCompleted += (that, continuation) => { Console.WriteLine("will hop back to extension!? can we resume later?"); var r = TestSwitchToServiceContextAsync.ShadowIAsyncStateMachine.ResumeableFromContinuation(continuation); // can we only send once? //Console.WriteLine("will invoke sendResponse... " + new { sendResponse }); Console.WriteLine("will invoke sendResponse... "); //sendResponse.apply(null, r); //will invoke sendResponse... //(program):51533 1664ms enter catch //{ // mname = < 0154 > ldarg.0.try } ClauseCatchLocal: // (program):51533 1664ms TypeError: Converting circular structure to JSON // planB PostToExtension(r.shadowstate); }; InternalInvoke(s); //Task.Delay(1000).ContinueWith( // delegate // { // sendResponse.apply(null, "response"); // } //); }; #endregion // Native.window.onmessage += e => //{ //}; }