Exemplo n.º 1
0
    /// <summary>
    /// Default entry into managed code.
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public async Task <object> Invoke(object input)
    {
        if (console == null)
        {
            console = await WebSharpJs.NodeJS.Console.Instance();
        }

        try
        {
            var document = await HtmlPage.GetDocument();

            // Get a reference to the top-level <html> element.
            var element = await document.GetDocumentElement();

            // Process the starting element reference
            await ProcessElement(element, 0);

            await console.Log(elementTree);

            await console.Log($"Hello:  {input}");
        }
        catch (Exception exc) { await console.Log($"extension exception:  {exc.Message}"); }

        return(null);
    }
Exemplo n.º 2
0
    /// <summary>
    /// Default entry into managed code.
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public async Task <object> Invoke(object input)
    {
        if (console == null)
        {
            console = await WebSharpJs.NodeJS.Console.Instance();
        }

        try
        {
            var document = await HtmlPage.GetDocument();

            var info = await HtmlPage.GetBrowserInformation();

            var infoText = $"Name: {info.Name}<br />Browser Version: {info.BrowserVersion}<br />Platform: {info.Platform}<br />Cookies Enabled: {info.CookiesEnabled}<br />User Agent: {info.UserAgent}";

            var paragraph = await document.GetElementById("info");

            await paragraph.SetProperty("innerHTML", infoText);

            await console.Log($"Hello:  {input}");
        }
        catch (Exception exc) { await console.Log($"extension exception:  {exc.Message}"); }

        return(null);
    }
Exemplo n.º 3
0
    /// <summary>
    /// Default entry into managed code.
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public async Task <object> Invoke(object input)
    {
        if (console == null)
        {
            console = await WebSharpJs.NodeJS.Console.Instance();
        }

        try
        {
            // Get a reference to the HTML DOM document.
            var document = await HtmlPage.GetDocument();

            // Get a reference to the body element.
            var body = await document.GetElementById("docBody");

            // Create a <main> type element
            var mainElement = await document.CreateElement("main");

            // Append the newly created element to the page DOM
            await body.AppendChild(mainElement);

            // Get a collection of all the <main> type element in the page and using
            // Linq get the first of the collection.
            var content = (await document.GetElementsByTagName("main")).First();

            // Get a collection of all the <link> elements
            var links = await document.QuerySelectorAll("link[rel=\"import\"]");

            // Loop through all of the <link> elements found
            foreach (var link in links)
            {
                // Access the contents of the import document by examining the
                // import property of the corresponding <link> element
                var template = await link.GetProperty <HtmlElement>("import").ContinueWith(
                    async(t) =>
                {
                    // For all imported contents obtain a reference to the <template>
                    return(await t.Result?.QuerySelector(".task-template"));
                }
                    ).Result;

                // Create a clone of the template’s content using the importNode property and
                // passing in the content of the template
                var clone = await document.Invoke <HtmlElement>("importNode",
                                                                await template.GetProperty <HtmlElement>("content"), true);

                // Append the newly created cloned template to the content element.
                await content.AppendChild(clone);
            }
        }
        catch (Exception exc) { await console.Log($"extension exception:  {exc.Message}"); }

        return(null);
    }
Exemplo n.º 4
0
    /// <summary>
    /// Default entry into managed code.
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public async Task <object> Invoke(object input)
    {
        if (console == null)
        {
            console = await WebSharpJs.NodeJS.Console.Instance();
        }

        try
        {
            var document = await HtmlPage.GetDocument();

            var printPDFBtn = await document.GetElementById("print-pdf");

            var ipcRenderer = await IpcRenderer.Create();

            await printPDFBtn?.AttachEvent("click",
                                           new EventHandler(async(sender, evt) =>
            {
                await console.Log("clicked");
                ipcRenderer.Send("print-to-pdf");
            })
                                           );

            ipcRenderer.On("wrote-pdf",
                           new IpcRendererEventListener(async(result) =>
            {
                var state = result.CallbackState as object[];
                var parms = state[1] as object[];
                foreach (var parm in parms)
                {
                    await console.Log(parm);
                }
                var pathLabel = await document.GetElementById("file-path");
                await pathLabel.SetProperty("innerHTML", $"Wrote PDF to: {parms[0]}");
            }));
        }
        catch (Exception exc) { await console.Log($"extension exception:  {exc.Message}"); }

        return(null);
    }
Exemplo n.º 5
0
    /// <summary>
    /// Default entry into managed code.
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public async Task <object> Invoke(object input)
    {
        if (console == null)
        {
            console = await WebSharpJs.NodeJS.Console.Instance();
        }

        try
        {
            var document = await HtmlPage.GetDocument();

            area = await document.GetElementById("input");

            output = await document.GetElementById("output");

            spaces = await document.GetElementById("spaced");

            emojiPicker = await document.GetElementById("emoji");

            length = await document.GetElementById("length");

            copy = await document.GetElementById("copy");

            await area.AttachEvent("input", updateOutput);

            await spaces.AttachEvent("change", updateOutput);

            await emojiPicker.AttachEvent("change", updateOutput);

            await copy.AttachEvent("click", copyClicked);

            await console.Log($"Hello:  {input}");
        }
        catch (Exception exc) { await console.Log($"extension exception:  {exc.Message}"); }

        return(null);
    }
Exemplo n.º 6
0
    /// <summary>
    /// Default entry into managed code.
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public async Task <object> Invoke(object input)
    {
        if (console == null)
        {
            console = await WebSharpJs.NodeJS.Console.Instance();
        }

        try
        {
            // Get a reference to the DOM Document
            var document = await HtmlPage.GetDocument();

            // Get a reference to the "link" element
            var link = await document.GetElementById("link");

            // Attach an event listener to the "click" event
            await link.AttachEvent("click", onMouseClick);

            await console.Log($"Hello:  {input}");
        }
        catch (Exception exc) { await console.Log($"extension exception:  {exc.Message}"); }

        return(null);
    }
Exemplo n.º 7
0
    /// <summary>
    /// Default entry into managed code.
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public async Task <object> Invoke(object input)
    {
        if (console == null)
        {
            console = await WebSharpJs.NodeJS.Console.Instance();
        }

        try
        {
            var document = await HtmlPage.GetDocument();

            var findMe = await document.GetElementById("findMe");

            var map = await document.GetElementById("map");

            var location = await document.GetElementById("location");

            var error = false;

            await findMe.AttachEvent(HtmlEventNames.Click,
                                     new EventHandler(
                                         async(sender, evt) => {
                error = false;

                await location.SetProperty("innerText", "Locating ...");
                var geo = await GeoLocationAPI.Instance();
                await geo.GetCurrentPosition(
                    new ScriptObjectCallback <Position>(
                        async(cr) =>
                {
                    // Obtain our position from the CallbackState
                    var position = cr.CallbackState as Position;
                    // Reference the Coordinates class
                    var coords = position.Coordinates;
                    // Create our location information string
                    var posString = $"Your current position is:\nLatitude : {coords.Latitude}\nLongitude : {coords.Longitude}\nMore or less {coords.Accuracy} Meters.";
                    // Set the location status text
                    await location.SetProperty("innerText", posString);
                    // Retrieve the image of the location using the longitude and latitude
                    // properties of the Coordinates class.
                    var imageURL = $"https://maps.googleapis.com/maps/api/staticmap?center={coords.Latitude},{coords.Longitude}&zoom=13&size=300x300&sensor=false";
                    // Set the src property of the <image> tag
                    await map.SetProperty("src", imageURL);
                }
                        ),
                    new ScriptObjectCallback <PositionError>(
                        async(cr) =>
                {
                    // Obtain the error from CallbackState
                    var err = cr.CallbackState as PositionError;
                    // Format a string with the error
                    var errString = $"ERROR({err.ErrorCode}): {err.Message}";
                    // If we already have an error then we will want to append
                    // the error to the already existing error(s) that exist.
                    if (error)
                    {
                        var errorText = await location.GetProperty <string>("innerText");
                        errString = $"{errorText}\n{errString}";
                    }
                    error = true;
                    // Set the status area text for feedback to the user
                    await location.SetProperty("innerText", errString);
                }
                        ),
                    new PositionOptions()
                {
                    EnableHighAccuracy = true, Timeout = 5000, MaximumAge = 0
                }
                    );
            }
                                         )
                                     );

            await console.Log($"Hello:  {input}");
        }
        catch (Exception exc) { await console.Log($"extension exception:  {exc.Message}"); }

        return(null);
    }
Exemplo n.º 8
0
    /// <summary>
    /// Default entry into managed code.
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public async Task <object> Invoke(object input)
    {
        if (console == null)
        {
            console = await WebSharpJs.NodeJS.Console.Instance();
        }

        try
        {
            // Since we are executing from the Renderer process we have to use
            // dialog remote process.
            dialog = await Dialog.Instance();

            var page = new HtmlPage();
            document = await page.GetDocument();

            // Get the HtmlElement with the id of "openFile"
            var openFile = await document.GetElementById("openFile");

            // Attach a "click" event handler to the openFile HtmlElement
            await openFile.AttachEvent("click", new EventHandler(async(sender, evt) =>
            {
                // Create an OpenDialogOptions reference with custom FileFilters
                var openOptions = new OpenDialogOptions()
                {
                    Filters = new FileFilter[]
                    {
                        new FileFilter()
                        {
                            Name = "text", Extensions = new string[] { "txt" }
                        },
                        new FileFilter()
                        {
                            Name = "All Files", Extensions = new string[] { "*" }
                        }
                    }
                };

                // Now show the open dialog passing in the options created previously
                // and a call back function when a file is selected.
                // If a call back function is not specified then the ShowOpenDialog function
                // will return an array of the selected file(s) or an empty array if no
                // files are selected.
                await dialog.ShowOpenDialog(
                    openOptions,
                    openFileCallback
                    );
            }
                                                                 ));

            // Get the HtmlElement with the id of "saveFile"
            var saveFile = await document.GetElementById("saveFile");

            // Attach a "click" event handler to the saveFile HtmlElement
            await saveFile.AttachEvent("click", new EventHandler(async(sender, evt) =>
            {
                // Create an OpenDialogOptions reference with custom FileFilters
                var saveOptions = new SaveDialogOptions()
                {
                    Filters = new FileFilter[]
                    {
                        new FileFilter()
                        {
                            Name = "text", Extensions = new string[] { "txt" }
                        },
                        new FileFilter()
                        {
                            Name = "All Files", Extensions = new string[] { "*" }
                        }
                    }
                };

                // Now show the save dialog passing in the options created previously
                // and a call back function to be called when the save button is clicked.
                // If a call back function is not specified then the ShowSaveDialog function
                // will return a string or an empty string if no file was specified.
                await dialog.ShowSaveDialog(
                    saveOptions,
                    saveFileCallback
                    );
            }
                                                                 ));
        }
        catch (Exception exc) { await dialog.ShowErrorBox("There was an error: ", exc.Message); }

        return(null);
    }
Exemplo n.º 9
0
    /// <summary>
    /// Default entry into managed code.
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public async Task <object> Invoke(object input)
    {
        if (console == null)
        {
            console = await WebSharpJs.NodeJS.Console.Instance();
        }

        try
        {
            var clipboard = await Clipboard.Instance();

            await console.Log("Available Formats");

            var formats = await clipboard.AvailableFormats();

            for (int f = 0; f < formats.Length; f++)
            {
                await console.Log(formats[f]);
            }

            // if we have an image format on the clipboard the we need to readit and set the image's
            // source element.
            if (formats.Length == 1 && formats[0] == "image/png")
            {
                // Read the clipboard Image
                var image = await clipboard.ReadImage();

                // If we have the image
                if (image != null)
                {
                    // Get access to the DOM
                    var page     = new HtmlPage();
                    var document = await page.GetDocument();

                    // Get a reference to the img element
                    var imageElement = await document.GetElementById("image");

                    if (imageElement != null)
                    {
                        // set the src property to the data string of the image/
                        await imageElement.SetProperty("src", await image.ToDataURL());
                    }
                }
            }

            await clipboard.WriteText("Example String copied to clipboard");

            await console.Log($"Clipboard text read: {await clipboard.ReadText()}");

            await console.Log("Clearing clipboard");

            await clipboard.Clear();

            await console.Log("Available Formats");

            formats = await clipboard.AvailableFormats(ClipboardType.Selection);

            for (int f = 0; f < formats.Length; f++)
            {
                await console.Log(formats[f]);
            }

            await console.Log("Writing data to the clipboard");

            await clipboard.Write(new ClipboardData()
            {
                Text = "test", HTML = "<b>test</b>"
            });

            await console.Log("Available Formats");

            formats = await clipboard.AvailableFormats(ClipboardType.Selection);

            for (int f = 0; f < formats.Length; f++)
            {
                await console.Log(formats[f]);
            }

            await console.Log($"Reading Clipboard Text data: {await clipboard.ReadText()}");

            await console.Log($"Reading Clipboard HTML data: {await clipboard.ReadHTML()}");

            await console.Log($"Reading Clipboard RTF data: {await clipboard.ReadRTF()}");

            await console.Log($"Has {await clipboard.Has("<p>selection</p>")}");

            await console.Log("Writing bookmark to the clipboard");

            await clipboard.WriteBookmark("Electron Homepage", @"https://electron.atom.io");

            await console.Log(await clipboard.ReadBookmark());

            await console.Log("Available Formats");

            formats = await clipboard.AvailableFormats(ClipboardType.Selection);

            for (int f = 0; f < formats.Length; f++)
            {
                await console.Log(formats[f]);
            }

            await console.Log($"Hello:  {input}");
        }
        catch (Exception exc) { await console.Log($"extension exception:  {exc.Message}"); }

        return(null);
    }
Exemplo n.º 10
0
    /// <summary>
    /// Default entry into managed code.
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public async Task <object> Invoke(object input)
    {
        if (console == null)
        {
            console = await WebSharpJs.NodeJS.Console.Instance();
        }

        try
        {
            var document = await HtmlPage.GetDocument();

            HtmlElement dragged = null;

            // events fired on the draggable target */
            await document.AttachEvent(HtmlEventNames.Drag,
                                       new EventHandler <HtmlEventArgs> (
                                           async(sender, evt) =>
            {
            }
                                           )

                                       );

            await document.AttachEvent(HtmlEventNames.DragStart,
                                       new EventHandler <HtmlEventArgs> (
                                           async(sender, evt) =>
            {
                // store a ref. on the dragged element
                dragged = evt.Target as HtmlElement;

                // make it half transparent
                await dragged.SetStyleAttribute("opacity", ".5");
            }
                                           )
                                       );

            await document.AttachEvent(HtmlEventNames.DragEnd,
                                       new EventHandler <HtmlEventArgs> (
                                           async(sender, evt) =>
            {
                // reset the transparency
                await evt.Target.SetStyleAttribute("opacity", "");
            }
                                           )
                                       );

            await document.AttachEvent(HtmlEventNames.DragExit,
                                       new EventHandler <HtmlEventArgs> (
                                           async(sender, evt) =>
            {
                // reset the transparency
                await evt.Target.SetStyleAttribute("opacity", "");
            }
                                           )
                                       );

            // Events fired on the drop targets
            await document.AttachEvent(HtmlEventNames.DragOver,
                                       new EventHandler <HtmlEventArgs> (
                                           async(sender, evt) =>
            {
                // prevent default to allow drop
                evt.PreventDefault();
                evt.StopPropagation();

                // A DropEffect must be set
                evt.DataTransfer.DropEffect = DropEffect.Link;
            }
                                           )

                                       );

            //Events fired on the drop targets
            await document.AttachEvent(HtmlEventNames.DragEnter,
                                       new EventHandler <HtmlEventArgs> (
                                           async(sender, evt) =>
            {
                // highlight potential drop target when the draggable element enters it
                if (await evt.Target.GetCssClass() == "dropzone")
                {
                    await evt.Target.SetStyleAttribute("background", "purple");
                }
            }
                                           )

                                       );

            await document.AttachEvent(HtmlEventNames.DragLeave,
                                       new EventHandler <HtmlEventArgs> (
                                           async(sender, evt) =>
            {
                // highlight potential drop target when the draggable element enters it
                if (await evt.Target.GetCssClass() == "dropzone")
                {
                    await evt.Target.SetStyleAttribute("background", "");
                }
            }
                                           )

                                       );

            await document.AttachEvent(HtmlEventNames.Drop,
                                       new EventHandler <HtmlEventArgs> (
                                           async(sender, evt) =>
            {
                // prevent default to allow drop
                evt.PreventDefault();
                evt.StopPropagation();

                // move dragged elem to the selected drop target
                if (await evt.Target.GetCssClass() == "dropzone")
                {
                    await evt.Target.SetStyleAttribute("background", "");
                    await dragged.GetParent().ContinueWith(
                        (t) => { t.Result?.RemoveChild(dragged); }

                        );
                    //dragged.parentNode.removeChild( dragged );
                    await evt.Target.AppendChild(dragged);
                }
            }
                                           )

                                       );

            await console.Log($"Hello:  {input}");
        }
        catch (Exception exc) { await console.Log($"extension exception:  {exc.Message}"); }

        return(null);
    }
Exemplo n.º 11
0
    /// <summary>
    /// Default entry into managed code.
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public async Task <object> Invoke(object input)
    {
        if (console == null)
        {
            console = await WebSharpJs.NodeJS.Console.Instance();
        }

        try
        {
            var document = await HtmlPage.GetDocument();

            var findMe = await document.GetElementById("findMe");

            var map = await document.GetElementById("map");

            var location = await document.GetElementById("location");

            var error = false;

            await findMe.AttachEvent("click",
                                     new EventHandler(
                                         async(sender, evt) => {
                error = false;

                await location.SetProperty("innerText", "Locating ...");
                var geo = await GeoLocationAPI.Instance();
                await geo.GetCurrentPosition(
                    new ScriptObjectCallback <GeoPosition>(
                        async(cr) =>
                {
                    var position = cr.CallbackState as GeoPosition;
                    var coords = position.Coordinates;
                    var posString = $"Your current position is:\nLatitude : {coords.Latitude}\nLongitude : {coords.Longitude}\nMore or less {coords.Accuracy} Meters.";
                    await location.SetProperty("innerText", posString);
                    var imageURL = $"https://maps.googleapis.com/maps/api/staticmap?center={coords.Latitude},{coords.Longitude}&zoom=13&size=300x300&sensor=false";
                    await map.SetProperty("src", imageURL);
                }
                        ),
                    new ScriptObjectCallback <PositionError>(
                        async(cr) =>
                {
                    var err = cr.CallbackState as PositionError;
                    var errString = $"ERROR({err.ErrorCode}): {err.Message}";
                    if (error)
                    {
                        var errorText = await location.GetProperty <string>("innerText");
                        errString = $"{errorText}\n{errString}";
                    }
                    error = true;
                    await location.SetProperty("innerText", errString);
                }
                        ),
                    new PositionOptions()
                {
                    EnableHighAccuracy = true, Timeout = 5000, MaximumAge = 0
                }
                    );
            }
                                         )
                                     );

            await console.Log($"Hello:  {input}");
        }
        catch (Exception exc) { await console.Log($"extension exception:  {exc.Message}"); }

        return(null);
    }
Exemplo n.º 12
0
    /// <summary>
    /// Default entry into managed code.
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public async Task <object> Invoke(object input)
    {
        if (console == null)
        {
            console = await WebSharpJs.NodeJS.Console.Instance();
        }

        try
        {
            ipcRenderer = await IpcRenderer.Create();

            document = await HtmlPage.GetDocument();

            var form = await document.QuerySelector("form");

            // Input fields
            source = await form.QuerySelector("input[name=\"source\"]");

            destination = await form.QuerySelector("input[name=\"destination\"]");

            name = await form.QuerySelector("input[name=\"name\"]");

            // Buttons
            btnSource = await document.GetElementById("chooseSource");

            btnDestination = await document.GetElementById("chooseDestination");

            btnSubmit = await form.QuerySelector("button[type=\"submit\"]");

            // Handle input fields
            await source.AttachEvent(HtmlEventNames.Input, updateUI);

            await source.AttachEvent(HtmlEventNames.Change, updateUI);

            await destination.AttachEvent(HtmlEventNames.Input, updateUI);

            await destination.AttachEvent(HtmlEventNames.Change, updateUI);

            await name.AttachEvent(HtmlEventNames.Input, updateUI);

            // Handle buttons
            await btnSource.AttachEvent(HtmlEventNames.Click, handleSource);

            await btnDestination.AttachEvent(HtmlEventNames.Click, handleDestination);

            // Handle form Submit
            await form.AttachEvent(HtmlEventNames.Submit,
                                   async (s, e) => {
                e.PreventDefault();

                await ToggleUI(true);

                // Send off the convert request
                await ipcRenderer.Send("submitform",
                                       await source.GetProperty <string>("value"),
                                       await destination.GetProperty <string>("value"),
                                       await name.GetProperty <string>("value")
                                       );
            }
                                   );

            await ipcRenderer.AddListener("gotMetaData",
                                          new IpcRendererEventListener(
                                              async(result) =>
            {
                var state = result.CallbackState as object[];
                var ipcMainEvent = (IpcRendererEvent)state[0];
                var parms = state[1] as object[];

                var audio = ScriptObjectHelper.AnonymousObjectToScriptableType <Audio>(parms[0]);
                var video = ScriptObjectHelper.AnonymousObjectToScriptableType <Video>(parms[1]);
                var duration = TimeSpan.Parse(parms[2].ToString());

                await updateInfo(audio, video, duration);
            }

                                              )

                                          );

            await ipcRenderer.AddListener("completed",
                                          new IpcRendererEventListener(
                                              async(result) =>
            {
                await ToggleUI(false);
            }

                                              )

                                          );

            await console.Log($"Hello:  {input}");
        }
        catch (Exception exc) { await console.Log($"extension exception:  {exc.Message}"); }

        return(null);
    }
Exemplo n.º 13
0
    /// <summary>
    /// Default entry into managed code.
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public async Task <object> Invoke(object input)
    {
        if (console == null)
        {
            console = await WebSharpJs.NodeJS.Console.Instance();
        }

        try
        {
            var document = await HtmlPage.GetDocument();

            window = await HtmlPage.GetWindow();

            canvas = await document.QuerySelector("canvas");

            canvasWidth = await canvas.GetProperty <int>("width");

            canvasHeight = await canvas.GetProperty <int>("height");

            ctx = await canvas.Invoke <HtmlObject> ("getContext", "2d");

            animationCallback = new ScriptObjectCallback(
                async(ar) =>
            {
                await CanvasDraw().ContinueWith(
                    (t) => { animation = null; }
                    );
            }

                );

            await CanvasDraw();

            await canvas.AttachEvent("click", new EventHandler(
                                         async(sender, e) =>
            {
                if ((await document.GetProperty <HtmlObject>("pointerLockElement"))?.Handle == canvas.Handle)
                {
                    await document.Invoke <object>("exitPointerLock");
                }
                else
                {
                    await canvas.Invoke <object>("requestPointerLock");
                }
            })
                                     );

            // Hook pointer lock state change events
            await document.AttachEvent("pointerlockchange", new EventHandler(
                                           async(sender, e) =>
            {
                if ((await document.GetProperty <HtmlObject>("pointerLockElement"))?.Handle == canvas.Handle)
                {
                    await console.Log("The pointer lock status is now locked");
                    await document.AttachEvent("mousemove", UpdatePosition);
                }
                else
                {
                    await console.Log("The pointer lock status is now unlocked");
                    await document.DetachEvent("mousemove", UpdatePosition);
                }
            })
                                       );

            tracker = await document.GetElementById("tracker");

            await console.Log($"Hello:  {input}");
        }
        catch (Exception exc) { await console.Log($"extension exception:  {exc.Message}"); }

        return(null);
    }