Esempio n. 1
0
        private void RefreshSource()
        {
            if (Source != null)
            {
                Loaded += Image_Loaded;
                if (Source is BitmapImage)
                {
                    BitmapImage sourceAsBitmapImage = (BitmapImage)Source;
                    if (sourceAsBitmapImage.UriSource != null)
                    {
                        Uri sourceUri = null;
                        sourceUri = ((BitmapImage)Source).UriSource;

                        string html5Path = INTERNAL_UriHelper.ConvertToHtml5Path(sourceUri.OriginalString, this);

                        INTERNAL_HtmlDomManager.SetDomElementAttribute(_imageDiv, "src", html5Path);
                    }
                    else if (sourceAsBitmapImage.INTERNAL_StreamSource != null)
                    {
                        string dataUrl = "data:image/png;base64," + sourceAsBitmapImage.INTERNAL_StreamAsBase64String;
                        INTERNAL_HtmlDomManager.SetDomElementAttribute(_imageDiv, "src", dataUrl);
                    }
                    else if (!string.IsNullOrEmpty(sourceAsBitmapImage.INTERNAL_DataURL))
                    {
                        string dataUrl = sourceAsBitmapImage.INTERNAL_DataURL;
                        INTERNAL_HtmlDomManager.SetDomElementAttribute(_imageDiv, "src", dataUrl);
                    }
                }
            }
            else
            {
                INTERNAL_HtmlDomManager.SetDomElementAttribute(_imageDiv, "src", "");
            }
            INTERNAL_HtmlDomManager.SetDomElementAttribute(_imageDiv, "alt", " "); //the text displayed when the image cannot be found. We set it as an empty string since there is nothing in Xaml
        }
        internal static void LoadCssFile(string url, Action callback)
        {
            // Get the assembly name of the calling method: //IMPORTANT: the call to the "GetCallingAssembly" method must be done in the method that is executed immediately after the one where the URI is defined! Be careful when moving the following line of code.
#if !BRIDGE
            string callerAssemblyName = Interop.IsRunningInTheSimulator ? Assembly.GetCallingAssembly().GetName().Name : INTERNAL_UriHelper.GetJavaScriptCallingAssembly();
#else
            string callerAssemblyName = INTERNAL_UriHelper.GetJavaScriptCallingAssembly();
#endif

            string html5Path = INTERNAL_UriHelper.ConvertToHtml5Path(url);

            CSHTML5.Interop.ExecuteJavaScript(
                @"// Add the link tag to the head
var head = document.getElementsByTagName('head')[0];
var link = document.createElement('link');
link.rel  = 'stylesheet';
link.type = 'text/css';
link.href = $0;
link.media = 'all';

// Fire the loading
head.appendChild(link);

// Some browsers do not support the 'onload' event of the 'link' element,
// therefore we use the 'onerror' event of the 'img' tag instead, which is always triggered:
var img = document.createElement('img');
img.onerror = $1;
img.src = $0;", html5Path, callback);
        }
Esempio n. 3
0
        internal List <object> INTERNAL_ToHtmlString(DependencyObject parent)
        {
            List <object> returnValues = new List <object>();

            if (ImageSource != null)
            {
                if (ImageSource is BitmapImage)
                {
                    BitmapImage sourceAsBitmapImage = (BitmapImage)ImageSource;
                    if (sourceAsBitmapImage.UriSource != null)
                    {
                        Uri sourceUri = null;
                        sourceUri = ((BitmapImage)ImageSource).UriSource;
                        string html5Path = INTERNAL_UriHelper.ConvertToHtml5Path(sourceUri.OriginalString, parent as UIElement);
                        returnValues.Add("url('" + html5Path + "')");
                    }
                    else if (sourceAsBitmapImage.INTERNAL_StreamSource != null)
                    {
                        string dataUrl = "data:image/png;base64," + sourceAsBitmapImage.INTERNAL_StreamAsBase64String;
                        returnValues.Add("url(" + dataUrl + ")");
                    }
                    else if (!string.IsNullOrEmpty(sourceAsBitmapImage.INTERNAL_DataURL))
                    {
                        string dataUrl = sourceAsBitmapImage.INTERNAL_DataURL;
                        returnValues.Add("url(" + dataUrl + ")");
                    }
                }
            }
            return(returnValues);
        }
Esempio n. 4
0
        static HashSet2 <string> _jsScriptFileKeys = new HashSet2 <string>(); //todo: This is probably redundant with the _pendingJSFile and _loadedFiles in INTERNAL_InteropImplementation so remove this?
        public static Task <object> LoadJavaScriptFile(ResourceFile resourceFile)
        {
            if (!_jsScriptFileKeys.Contains(resourceFile.Key))
            {
                // Get the assembly name of the calling method: //IMPORTANT: the call to the "GetCallingAssembly" method must be done in the method that is executed immediately after the one where the URI is defined! Be careful when moving the following line of code.
#if !BRIDGE
                string callerAssemblyName = Interop.IsRunningInTheSimulator ? Assembly.GetCallingAssembly().GetName().Name : INTERNAL_UriHelper.GetJavaScriptCallingAssembly();
#else
                string callerAssemblyName = INTERNAL_UriHelper.GetJavaScriptCallingAssembly();
#endif

                var t = new TaskCompletionSource <object>();
                INTERNAL_InteropImplementation.LoadJavaScriptFile(resourceFile.Url, callerAssemblyName,
                                                                  () =>
                {
                    t.SetResult(null);
                    _jsScriptFileKeys.Add(resourceFile.Key);     //we only set this when it successfully loaded so that the next time we try to load a file with the same key, finding the key in the HashSet means that it was already SUCCESSFULLY loaded.
                },
                                                                  () => t.SetException(new Exception("Could not load file: \"" + resourceFile.Url + "\".")));

                return(t.Task);
            }

            var task = new TaskCompletionSource <object>();
            task.SetResult(null);
            return(task.Task);
        }
Esempio n. 5
0
        private static void Source_Changed(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
#if MIGRATION
            WebBrowser webView = (WebBrowser)d;
#else
            WebView webView = (WebView)d;
#endif

            if (webView._isLoaded) // Note: if not loaded, we will set the source later when adding the control to the visual tree.
            {
#if MIGRATION
                var source = webView.SourceUri;
#else
                var source = webView.Source;
#endif
                if (source != null && !string.IsNullOrEmpty(source.OriginalString))
                {
                    string uri = INTERNAL_UriHelper.ConvertToHtml5Path(source.OriginalString, null);
                    CSHTML5.Interop.ExecuteJavaScriptAsync("$0.src = $1", webView._iFrame, uri);
                }
                else
                {
                    CSHTML5.Interop.ExecuteJavaScriptAsync("$0.src = 'about:blank'", webView._iFrame);
                }
            }
        }
        string GetHtmlString(string filePath)
        {
            var embedJs =
                INTERNAL_UriHelper.ConvertToHtml5Path("ms-appx:/Other/embed.js");

            return(string.Format(
                       "<script src=\"{0}?target={1}&style=github&showBorder=on&showLineNumbers=on&showCopy=on\"></script>",
                       embedJs, HttpUtility.UrlEncode("https://github.com" + filePath.Substring(6))));
        }
Esempio n. 7
0
        /// <summary>
        /// Loads a list of JavaScript files from either an online location (http/https) or the local project. Note: This method will stop at the first script it cannot load, meaning that all subsequent scripts will not be loaded.
        /// </summary>
        /// <param name="urls">The URLs of the JavaScript files, with the syntax ms-appx:///AssemblyName/Folder/FileName.js or /AssemblyName;component/Folder/FileName.js or https://someAddress/FileName.js
        /// </param>
        /// <param name="callback">The method that is called when all the files have successfully finished loading.</param>
        /// <param name="callbackOnError">The method that is called when one of the files could not be loaded.</param>
        public static void LoadJavaScriptFilesAsync(IEnumerable <string> urls, Action callback, Action callbackOnError = null)
        {
            // Get the assembly name of the calling method: //IMPORTANT: the call to the "GetCallingAssembly" method must be done in the method that is executed immediately after the one where the URI is defined! Be careful when moving the following line of code.
#if !BRIDGE
            string callerAssemblyName = Interop.IsRunningInTheSimulator ? Assembly.GetCallingAssembly().GetName().Name : INTERNAL_UriHelper.GetJavaScriptCallingAssembly();
#else
            string callerAssemblyName = INTERNAL_UriHelper.GetJavaScriptCallingAssembly();
#endif
            List <string> urlsAsList = (urls is List <string>?(List <string>)urls : new List <string>(urls));
            INTERNAL_InteropImplementation.LoadJavaScriptFiles(urlsAsList, callerAssemblyName, callback, callbackOnError);
        }
Esempio n. 8
0
        /// <summary>
        /// Adds a 'script' tag to the HTML page and waits for the script to finish loading.
        /// </summary>
        /// <param name="url">The URL of the JavaScript file, with the syntax ms-appx:///AssemblyName/Folder/FileName.js or /AssemblyName;component/Folder/FileName.js</param>
        /// <returns>Nothing.</returns>
        public static Task <object> LoadJavaScriptFile(string url)
        {
            // Get the assembly name of the calling method: //IMPORTANT: the call to the "GetCallingAssembly" method must be done in the method that is executed immediately after the one where the URI is defined! Be careful when moving the following line of code.
#if !BRIDGE
            string callerAssemblyName = Interop.IsRunningInTheSimulator ? Assembly.GetCallingAssembly().GetName().Name : INTERNAL_UriHelper.GetJavaScriptCallingAssembly();
#else
            string callerAssemblyName = INTERNAL_UriHelper.GetJavaScriptCallingAssembly();
#endif

            var t = new TaskCompletionSource <object>();
            INTERNAL_InteropImplementation.LoadJavaScriptFile(url, callerAssemblyName, () => t.SetResult(null), () => t.SetException(new Exception("Could not load file: \"" + url + "\".")));
            return(t.Task);
        }
Esempio n. 9
0
        public static void LoadJavaScriptFilesAsync(IEnumerable <ResourceFile> resourceFiles, Action callback, Action callbackOnError = null)
        {
            // Get the assembly name of the calling method: //IMPORTANT: the call to the "GetCallingAssembly" method must be done in the method that is executed immediately after the one where the URI is defined! Be careful when moving the following line of code.
#if !BRIDGE
            string callerAssemblyName = Interop.IsRunningInTheSimulator ? Assembly.GetCallingAssembly().GetName().Name : INTERNAL_UriHelper.GetJavaScriptCallingAssembly();
#else
            string callerAssemblyName = INTERNAL_UriHelper.GetJavaScriptCallingAssembly();
#endif
            List <string> urlsAsList = new List <string>();
            foreach (var resourceFile in resourceFiles)
            {
                //add the key to the dictionary and add the url to the list:
                if (!_jsScriptFileKeys.Contains(resourceFile.Key))
                {
                    _jsScriptFileKeys.Add(resourceFile.Key);
                    urlsAsList.Add(resourceFile.Url);
                }
            }
            INTERNAL_InteropImplementation.LoadJavaScriptFiles(urlsAsList, callerAssemblyName, callback, callbackOnError);
        }
Esempio n. 10
0
        private void RefreshSource()
        {
            if (Source != null)
            {
                Loaded += Image_Loaded;
                if (Source is BitmapImage)
                {
                    BitmapImage sourceAsBitmapImage = (BitmapImage)Source;
                    if (sourceAsBitmapImage.UriSource != null)
                    {
                        Uri sourceUri = null;
                        sourceUri = ((BitmapImage)Source).UriSource;

                        string html5Path = INTERNAL_UriHelper.ConvertToHtml5Path(sourceUri.OriginalString, this);

                        INTERNAL_HtmlDomManager.SetDomElementAttribute(_imageDiv, "src", html5Path);
                    }
                    else if (sourceAsBitmapImage.INTERNAL_StreamSource != null)
                    {
                        string dataUrl = "data:image/png;base64," + sourceAsBitmapImage.INTERNAL_StreamAsBase64String;
                        INTERNAL_HtmlDomManager.SetDomElementAttribute(_imageDiv, "src", dataUrl);
                    }
                    else if (!string.IsNullOrEmpty(sourceAsBitmapImage.INTERNAL_DataURL))
                    {
                        string dataUrl = sourceAsBitmapImage.INTERNAL_DataURL;
                        INTERNAL_HtmlDomManager.SetDomElementAttribute(_imageDiv, "src", dataUrl);
                    }
                    //set the width and height to "inherit" so the image takes up the size defined for it (and applied to _imageDiv's parent):
                    CSHTML5.Interop.ExecuteJavaScript("$0.style.width = 'inherit'; $0.style.height = 'inherit'", _imageDiv);
                }
            }
            else
            {
                //If Source == null we show empty image to prevent broken image icon
                INTERNAL_HtmlDomManager.SetDomElementAttribute(_imageDiv, "src", TransparentGifOnePixel);

                //Set css width and height values to 0 so we don't use space for an image that should not take any. Note: if the size is specifically set in the Xaml, it will still apply on a parent dom element so it won't change the appearance.
                CSHTML5.Interop.ExecuteJavaScript("$0.style.width = ''; $0.style.height = ''", _imageDiv);
            }
            INTERNAL_HtmlDomManager.SetDomElementAttribute(_imageDiv, "alt", " "); //the text displayed when the image cannot be found. We set it as an empty string since there is nothing in Xaml
        }
        internal static void LoadJavaScriptFile(string url, string callerAssemblyName, Action callbackOnSuccess, Action callbackOnFailure = null)
        {
            string html5Path = INTERNAL_UriHelper.ConvertToHtml5Path(url);

            CSHTML5.Interop.ExecuteJavaScript(
                @"// Add the script tag to the head
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = $0;

// Then bind the event to the callback function
// There are several events for cross browser compatibility.
if(script.onreadystatechange != undefined) {
script.onreadystatechange = $1;
} else {
script.onload = $1;
script.onerror = $2;
}

// Fire the loading
head.appendChild(script);", html5Path, callbackOnSuccess, callbackOnFailure);
        }
Esempio n. 12
0
        static HashSet <string> _loadedFiles = new HashSet <string>();                                                                           //To know which files have already been successfully loaded so can we simply call the OnSuccess callback.

        internal static void LoadJavaScriptFile(string url, string callerAssemblyName, Action callbackOnSuccess, Action callbackOnFailure = null)
        {
            string html5Path = INTERNAL_UriHelper.ConvertToHtml5Path(url);

            if (_loadedFiles.Contains(html5Path)) //Note: using html5Path so we consider different ways of writing the same path as one and only path.
            {
                callbackOnSuccess();
            }
            else if (_pendingJSFile.ContainsKey(html5Path))
            {
                _pendingJSFile[html5Path].Add(new Tuple <Action, Action>(callbackOnSuccess, callbackOnFailure));
            }
            else
            {
                _pendingJSFile.Add(html5Path, new List <Tuple <Action, Action> > {
                    new Tuple <Action, Action>(callbackOnSuccess, callbackOnFailure)
                });
                CSHTML5.Interop.ExecuteJavaScript(
                    @"// Add the script tag to the head
var filePath = $0;
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = filePath;
// Then bind the event to the callback function
// There are several events for cross browser compatibility.
if(script.onreadystatechange != undefined) {
script.onreadystatechange = $1;
} else {
script.onload = function () { $1(filePath) };
script.onerror = function () { $2(filePath) };
}

// Fire the loading
head.appendChild(script);", html5Path, (Action <object>)LoadJavaScriptFileSuccess, (Action <object>)LoadJavaScriptFileFailure);
            }
        }
Esempio n. 13
0
        private static void Source_Changed(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var control  = (MediaElement)d;
            var newValue = (Uri)e.NewValue;

            // Always check that the control is in the Visual Tree before modifying its HTML representation
            if (INTERNAL_VisualTreeManager.IsElementInVisualTree(control))
            {
                string newUri = newValue.ToString();

                // If the new Source is an empty string, we avoid the error messages:
                if (!string.IsNullOrWhiteSpace(newUri))
                {
                    string tagString = "none";

                    string valueForHtml5SourceProperty = INTERNAL_UriHelper.ConvertToHtml5Path(newValue.ToString(), control);

                    string newExtensionLowercase = GetExtension(newUri).ToLower();

                    if (SupportedVideoTypes.Contains(newExtensionLowercase))
                    {
                        if (control.IsAudioOnly || control._mediaElement == null) //note: I chose to use IsAudioOnly here because using e.oldValue would make it recreate the video tag when it was already a video tag.
                        {
                            tagString           = "video";
                            control.IsAudioOnly = false;
                        }
                    }
                    else if (SupportedAudioTypes.Contains(newExtensionLowercase))
                    {
                        if (!control.IsAudioOnly || control._mediaElement == null) //note: I chose to use IsAudioOnly here because using e.oldValue would make it recreate the audio tag when it was already a audio tag.
                        {
                            tagString           = "audio";
                            control.IsAudioOnly = true;
                        }
                    }
                    else
                    {
                        throw new NotSupportedException("ERROR: The MediaElement control only supports files of the following types: VIDEO: mp4, ogv, webm, 3gp - AUDIO: mp3, ogg - Note: for best browser compatibility, it is recommended to use only MP3 and MP4 files.");
                    }
                    if (tagString != "none") //tagString != "none" means that the new Uri has a different type (audio VS video) than the old one, so we need to (re)create the dom tag.
                    {
                        if (control._mediaElement != null)
                        {
                            INTERNAL_HtmlDomManager.RemoveFromDom(control._mediaElement); //note: there can be only one child element.
                        }
#if OPENSILVER
                        if (!INTERNAL_InteropImplementation.IsRunningInTheSimulator_WorkAround() || tagString == "video")
#else
                        if (CSharpXamlForHtml5.Environment.IsRunningInJavaScript || tagString == "video")
#endif
                        {
                            object element      = null;
                            object outerDiv     = control.INTERNAL_OuterDomElement;
                            var    elementStyle = INTERNAL_HtmlDomManager.CreateDomElementAppendItAndGetStyle(tagString, outerDiv, control, out element);

                            control._mediaElement_ForAudioOnly_ForSimulatorOnly = null;

                            control._mediaElement = element;

                            if (tagString == "video")
                            {
                                elementStyle.width  = "100%";
                                elementStyle.height = "100%";
                            }

                            control.Refresh(); //we refresh all the values of the element in the visual tree
                        }
                        else //when we are in the simulator, we don't want to use the <audio> tag, we will use a wpf one instead (because awesomium doesn't support .mp3 for example)
                        {
#if !CSHTML5NETSTANDARD
                            if (control._mediaElement_ForAudioOnly_ForSimulatorOnly == null)
                            {
                                control._mediaElement_ForAudioOnly_ForSimulatorOnly = INTERNAL_Simulator.WpfMediaElementFactory.Create((Action)control.SimulatorMediaElement_Loaded, (Action)control.SimulatorMediaElement_MediaEnded);
                            }
                            control._mediaElement_ForAudioOnly_ForSimulatorOnly.Source = new Uri(valueForHtml5SourceProperty);
                            control.Refresh_SimulatorOnly();
#endif
                            return;
                        }
                    }

                    // Update the "src" property of the <video> or <audio> tag
                    INTERNAL_HtmlDomManager.SetDomElementAttribute(control._mediaElement, "src", valueForHtml5SourceProperty, forceSimulatorExecuteImmediately: true);
                }
                else
                {
                    if (control._mediaElement != null)
                    {
                        // Remove previous video/audio if any:
                        INTERNAL_HtmlDomManager.SetDomElementAttribute(control._mediaElement, "src", "", forceSimulatorExecuteImmediately: true);
                    }
                }
            }
        }
Esempio n. 14
0
 /// <summary>
 /// Converts a XAML-style URI (such as "ms-appx///") into a path that can be used in HTML.
 /// </summary>
 /// <param name="uri">A XAML-style URI such as ms-appx:///AssemblyName/Folder/Image.png or /AssemblyName;component/Folder/Image.png</param>
 /// <returns>A path that can be used in HTML</returns>
 public static string ConvertToHtmlPath(string uri)
 {
     return(INTERNAL_UriHelper.ConvertToHtml5Path(uri, null));
 }