Example #1
0
        private async Task <SpeechRecognitionResult> RecognizeTaskAsync()
        {
            var existingTask = _currentCompletionSource?.Task;

            if (existingTask != null)
            {
                return(await existingTask);
            }

            _currentCompletionSource = new TaskCompletionSource <SpeechRecognitionResult>();

            var command         = $"{JsType}.recognize('{_instanceId}')";
            var recognizeResult = WebAssemblyRuntime.InvokeJS(command);

            if (!bool.TryParse(recognizeResult, out var canRecognize) || !canRecognize)
            {
                throw new InvalidOperationException(
                          "Speech recognizer is not available on this device.");
            }

            var result = await _currentCompletionSource.Task;

            _currentCompletionSource = null;
            return(result);
        }
Example #2
0
        public void Dispose()
        {
            _currentCompletionSource?.SetCanceled();
            var removeInstanceCommand = $"{JsType}.removeInstance('{_instanceId}')";

            WebAssemblyRuntime.InvokeJS(removeInstanceCommand);
        }
Example #3
0
        private void InitializeSpeechRecognizer()
        {
            var command = $"{JsType}.initialize('{_instanceId}','{CurrentLanguage.LanguageTag}')";

            WebAssemblyRuntime.InvokeJS(command);
            _instances.GetOrAdd(_instanceId.ToString(), this);
        }
Example #4
0
        private async static Task <FileUpdateStatus> DownloadFile(IStorageFile file)
        {
            var stream = await file.OpenStreamForReadAsync();

            byte[] data;

            using (var reader = new BinaryReader(stream))
            {
                data = reader.ReadBytes((int)stream.Length);
            }

            var gch        = GCHandle.Alloc(data, GCHandleType.Pinned);
            var pinnedData = gch.AddrOfPinnedObject();

            try
            {
                WebAssemblyRuntime.InvokeJS($"Windows.Storage.Pickers.FileSavePicker.SaveAs('{file.Name}', {pinnedData}, {data.Length})");
            }
            finally
            {
                gch.Free();
            }

            return(FileUpdateStatus.Complete);
        }
        /// <summary>
        /// Tries to get the relevant permissions and show toast notifications.
        /// </summary>
        /// <param name="toast"></param>
        /// <returns></returns>
        public static async Task Show(this ToastNotification toast)
        {
            // Mono seems to optimize away unsued functions..
            if (await DummyFalseStuff().ConfigureAwait(false))
            {
                Report(null);
            }

            _permission = _permission ?? await QueryPermissionAsync().ConfigureAwait(false);

            if ((bool)_permission)
            {
                WebAssemblyRuntime.InvokeJS($@"
                    var n = new Notification(
                        '{WebAssemblyRuntime.EscapeJs(toast.Title)}',
                        {{
                            body: '{WebAssemblyRuntime.EscapeJs(toast.Message)}',
                            {await SetIconIfOveriddenAsync(toast.AppLogoOverride).ConfigureAwait(false)}
                        }}
                    );
                ");
            }
            else
            {
                // Fall back to simple alert pop-up.
                WebAssemblyRuntime.InvokeJS($@"alert('{WebAssemblyRuntime.EscapeJs(toast.Message)}');");
            }
        }
Example #6
0
        public static void SetContent(DataPackage content)
        {
            var text    = WebAssemblyRuntime.EscapeJs(content.Text);
            var command = $"Uno.Utils.Clipboard.setText(\"{text}\");";

            WebAssemblyRuntime.InvokeJS(command);
        }
Example #7
0
        private bool SetFullScreenMode(bool turnOn)
        {
            var jsEval = $"{ApplicationViewTsType}.setFullScreenMode({turnOn.ToString(CultureInfo.InvariantCulture).ToLowerInvariant()})";
            var result = WebAssemblyRuntime.InvokeJS(jsEval);

            return(bool.TryParse(result, out var modeSwitchSuccessful) && modeSwitchSuccessful);
        }
Example #8
0
        private static void SetClipboardText(string text)
        {
            var escapedText = WebAssemblyRuntime.EscapeJs(text);
            var command     = $"{JsType}.setText(\"{escapedText}\");";

            WebAssemblyRuntime.InvokeJS(command);
        }
Example #9
0
        public static async Task <bool> LaunchUriPlatformAsync(Uri uri)
        {
            var command = $"Uno.UI.WindowManager.current.open(\"{uri.OriginalString}\");";
            var result  = WebAssemblyRuntime.InvokeJS(command);

            return(result == "True");
        }
Example #10
0
        public UIElement(string htmlTag = "div", bool isSvg = false)
        {
            _gcHandle    = GCHandle.Alloc(this, GCHandleType.Weak);
            HtmlTag      = htmlTag;
            HtmlTagIsSvg = isSvg;

            var type = GetType();

            Handle = GCHandle.ToIntPtr(_gcHandle);
            HtmlId = type.Name + "-" + Handle;

            var          isSvgStr = HtmlTagIsSvg ? "true" : "false";
            var          isFrameworkElementStr = this is FrameworkElement ? "true" : "false";
            const string isFocusable           = "false";   // by default all control are not focusable, it has to be change latter by the control itself
            var          classes = ClassNames.GetForType(type);

            WebAssemblyRuntime.InvokeJS(
                "Uno.UI.WindowManager.current.createContent({" +
                "id:\"" + HtmlId + "\"," +
                "tagName:\"" + HtmlTag + "\", " +
                "handle:" + Handle + ", " +
                "type:\"" + type.FullName + "\", " +
                "isSvg:" + isSvgStr + ", " +
                "isFrameworkElement:" + isFrameworkElementStr + ", " +
                "isFocusable:" + isFocusable + ", " +
                "classes:[" + classes + "]" +
                "});");

            UpdateHitTest();

            FocusManager.Track(this);
        }
Example #11
0
        partial void StartOrientationChanged()
        {
            _lastKnownOrientation = CurrentOrientation;
            var command = $"{JsType}.startOrientationChanged()";

            WebAssemblyRuntime.InvokeJS(command);
        }
Example #12
0
        private static SystemTheme GetSystemTheme()
        {
            var serializedTheme = WebAssemblyRuntime.InvokeJS("Windows.UI.Xaml.Application.getDefaultSystemTheme()");

            if (serializedTheme != null)
            {
                if (Enum.TryParse(serializedTheme, out SystemTheme theme))
                {
                    if (typeof(SystemThemeHelper).Log().IsEnabled(Microsoft.Extensions.Logging.LogLevel.Information))
                    {
                        typeof(SystemThemeHelper).Log().Info("Setting OS preferred theme: " + theme);
                    }
                    return(theme);
                }
                else
                {
                    throw new InvalidOperationException($"{serializedTheme} theme is not a supported OS theme");
                }
            }
            //OS has no preference or API not implemented, use light as default
            if (typeof(SystemThemeHelper).Log().IsEnabled(Microsoft.Extensions.Logging.LogLevel.Information))
            {
                typeof(SystemThemeHelper).Log().Info("No preferred theme, using Light instead");
            }
            return(SystemTheme.Light);
        }
Example #13
0
        internal static void CreateContent(IntPtr htmlId, string htmlTag, IntPtr handle, int uiElementRegistrationId, bool htmlTagIsSvg, bool isFocusable)
        {
            if (UseJavascriptEval)
            {
                var isSvgStr       = htmlTagIsSvg ? "true" : "false";
                var isFocusableStr = isFocusable ? "true" : "false";                 // by default all control are not focusable, it has to be change latter by the control itself

                WebAssemblyRuntime.InvokeJS(
                    "Uno.UI.WindowManager.current.createContent({" +
                    "id:\"" + htmlId + "\"," +
                    "tagName:\"" + htmlTag + "\", " +
                    "handle:" + handle + ", " +
                    "uiElementRegistrationId: " + uiElementRegistrationId + ", " +
                    "isSvg:" + isSvgStr + ", " +
                    "isFocusable:" + isFocusableStr +
                    "});");
            }
            else
            {
                var parms = new WindowManagerCreateContentParams
                {
                    HtmlId  = htmlId,
                    TagName = htmlTag,
                    Handle  = handle,
                    UIElementRegistrationId = uiElementRegistrationId,
                    IsSvg       = htmlTagIsSvg,
                    IsFocusable = isFocusable
                };

                TSInteropMarshaller.InvokeJS <WindowManagerCreateContentParams, bool>("Uno:createContentNative", parms);
            }
        }
Example #14
0
        private void Initialize()
        {
            using (WritePhaseEventTrace(TraceProvider.LauchedStart, TraceProvider.LauchedStop))
            {
                // Force init
                Window.Current.ToString();

                var arguments = WebAssemblyRuntime.InvokeJS("Uno.UI.WindowManager.findLaunchArguments()");

                if (this.Log().IsEnabled(Microsoft.Extensions.Logging.LogLevel.Debug))
                {
                    this.Log().Debug("Launch arguments: " + arguments);
                }
                InitializationCompleted();

                if (!string.IsNullOrEmpty(arguments))
                {
                    if (ProtocolActivation.TryParseActivationUri(arguments, out var activationUri))
                    {
                        OnActivated(new ProtocolActivatedEventArgs(activationUri, ApplicationExecutionState.NotRunning));
                        return;
                    }
                }

                OnLaunched(new LaunchActivatedEventArgs(ActivationKind.Launch, arguments));
            }
        }
Example #15
0
        internal static bool FocusNative(UIElement element)
        {
            if (_log.Value.IsEnabled(LogLevel.Debug))
            {
                _log.Value.LogDebug($"{nameof(FocusNative)}(element: {element})");
            }

            if (element == null)
            {
                return(false);
            }

            if (element is TextBox textBox)
            {
                return(textBox.FocusTextView());
            }

            _isCallingFocusNative = true;
            var command = $"Uno.UI.WindowManager.current.focusView({element.HtmlId});";

            WebAssemblyRuntime.InvokeJS(command);
            _isCallingFocusNative = false;

            return(true);
        }
Example #16
0
        private Rect GetBoundingClientRect()
        {
            var sizeString = WebAssemblyRuntime.InvokeJS("Uno.UI.WindowManager.current.getBoundingClientRect(\"" + HtmlId + "\");");
            var sizeParts  = sizeString.Split(';');

            return(new Rect(double.Parse(sizeParts[0]), double.Parse(sizeParts[1]), double.Parse(sizeParts[2]), double.Parse(sizeParts[3])));
        }
Example #17
0
        partial void StartMessageReceived()
        {
            _instanceSubscriptions.TryAdd(_managedId, this);
            var addListenerCommand = $"{JsType}.startMessageListener('{_managedId}')";

            WebAssemblyRuntime.InvokeJS(addListenerCommand);
        }
        private string[] GetCustomSchemes()
        {
            var js     = $@"Windows.Security.Authentication.Web.WebAuthenticationBroker.getReturnUrl();";
            var origin = WebAssemblyRuntime.InvokeJS(js);

            return(new[] { origin });
        }
Example #19
0
        partial void StartDpiChanged()
        {
            _lastKnownDpi = LogicalDpi;
            var command = $"{JsType}.startDpiChanged()";

            WebAssemblyRuntime.InvokeJS(command);
        }
        internal static Size MeasureView(IntPtr htmlId, Size availableSize)
        {
            if (UseJavascriptEval)
            {
                var w = double.IsInfinity(availableSize.Width) ? "null" : availableSize.Width.ToStringInvariant();
                var h = double.IsInfinity(availableSize.Height) ? "null" : availableSize.Height.ToStringInvariant();

                var command = "Uno.UI.WindowManager.current.measureView(\"" + htmlId + "\", \"" + w + "\", \"" + h + "\");";
                var result  = WebAssemblyRuntime.InvokeJS(command);

                var parts = result.Split(';');

                return(new Size(
                           double.Parse(parts[0], CultureInfo.InvariantCulture),
                           double.Parse(parts[1], CultureInfo.InvariantCulture)));
            }
            else
            {
                var parms = new WindowManagerMeasureViewParams
                {
                    HtmlId          = htmlId,
                    AvailableWidth  = availableSize.Width,
                    AvailableHeight = availableSize.Height
                };

                var ret = TSInteropMarshaller.InvokeJS <WindowManagerMeasureViewParams, WindowManagerMeasureViewReturn>("Uno:measureViewNative", parms);

                return(new Size(ret.DesiredWidth, ret.DesiredHeight));
            }
        }
Example #21
0
        partial void StopMessageReceived()
        {
            _instanceSubscriptions.TryRemove(_managedId, out _);
            var removeListenerCommand = $"{JsType}.stopMessageListener('{_managedId}')";

            WebAssemblyRuntime.InvokeJS(removeListenerCommand);
        }
Example #22
0
        internal static int RegisterUIElement(string typeName, string[] classNames, bool isFrameworkElement)
        {
            if (UseJavascriptEval)
            {
                var isFrameworkElementStr = isFrameworkElement ? "true" : "false";
                var classesParam          = classNames.Select(c => $"\"{c}\"").JoinBy(",");

                var ret = WebAssemblyRuntime.InvokeJS(
                    "Uno.UI.WindowManager.current.registerUIElement({" +
                    "typeName:\"" + typeName + "\"," +
                    "isFrameworkElement:" + isFrameworkElementStr + ", " +
                    "classes:[" + classesParam + "]" +
                    "});");

                return(int.Parse(ret));
            }
            else
            {
                var parms = new WindowManagerRegisterUIElementParams
                {
                    TypeName           = typeName,
                    IsFrameworkElement = isFrameworkElement,
                    Classes_Length     = classNames.Length,
                    Classes            = classNames,
                };

                var ret = TSInteropMarshaller.InvokeJS <WindowManagerRegisterUIElementParams, WindowManagerRegisterUIElementReturn>("Uno:registerUIElementNative", parms);
                return(ret.RegistrationId);
            }
        }
Example #23
0
        private void InternalSetContent(UIElement content)
        {
            if (_window == null)
            {
                _rootBorder       = new Border();
                _rootScrollViewer = new ScrollViewer()
                {
                    VerticalScrollBarVisibility   = ScrollBarVisibility.Disabled,
                    HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled,
                    VerticalScrollMode            = ScrollMode.Disabled,
                    HorizontalScrollMode          = ScrollMode.Disabled,
                    Content = _rootBorder
                };
                _popupRoot = new PopupRoot();
                _window    = new Grid()
                {
                    Children =
                    {
                        _rootScrollViewer,
                        _popupRoot
                    }
                };
            }

            _rootBorder.Child = _content = content;
            if (content != null)
            {
                WebAssemblyRuntime.InvokeJS($"Uno.UI.WindowManager.current.setRootContent(\"{_window.HtmlId}\");");
            }
            else
            {
                WebAssemblyRuntime.InvokeJS($"Uno.UI.WindowManager.current.setRootContent();");
            }
        }
Example #24
0
            /// <inheritdoc />
            public long CreateNativeInstance(IntPtr managedHandle)
            {
                var id = RenderingLoopAnimatorMetadataIdProvider.Next();

                WebAssemblyRuntime.InvokeJS($"Windows.UI.Xaml.Media.Animation.RenderingLoopFloatAnimator.createInstance(\"{managedHandle}\", \"{id}\")");

                return(id);
            }
Example #25
0
            /// <inheritdoc />
            public long CreateNativeInstance(IntPtr managedHandle)
            {
                var id = Interlocked.Increment(ref _handles);

                WebAssemblyRuntime.InvokeJS($"Windows.UI.Xaml.Media.Animation.RenderingLoopFloatAnimator.createInstance(\"{managedHandle}\", \"{id}\")");

                return(id);
            }
        private static ulong ToTimeStamp(double timestamp)
        {
            if (!_bootTime.HasValue)
            {
                _bootTime = (ulong)(double.Parse(WebAssemblyRuntime.InvokeJS("Date.now() - performance.now()")) * TimeSpan.TicksPerMillisecond);
            }

            return(_bootTime.Value + (ulong)(timestamp * TimeSpan.TicksPerMillisecond));
        }
Example #27
0
        public void Init()
        {
            Dispatcher = CoreDispatcher.Main;

            bool isHostedMode = !WebAssemblyRuntime.IsWebAssembly;

            WebAssemblyRuntime.InvokeJS($"Uno.UI.WindowManager.init(\"{Windows.Storage.ApplicationData.Current.LocalFolder.Path}\", {isHostedMode.ToString().ToLowerInvariant()});");
            CoreWindow = new CoreWindow();
        }
        static partial void InnerReportPageView(string pageName, string arguments)
        {
            var command = string.Concat(
                "Uno.UI.Demo.Analytics.reportPageView(\"",
                WebAssemblyRuntime.EscapeJs(pageName),
                "\");");

            WebAssemblyRuntime.InvokeJS(command);
        }
Example #29
0
        public void Init()
        {
            Dispatcher = CoreDispatcher.Main;

            bool isHostedMode = !RuntimeInformation.IsOSPlatform(OSPlatform.Create("WEBASSEMBLY"));

            WebAssemblyRuntime.InvokeJS($"Uno.UI.WindowManager.init(\"{Windows.Storage.ApplicationData.Current.LocalFolder.Path}\", {isHostedMode.ToString().ToLowerInvariant()});");
            CoreWindow = new CoreWindow();
        }
Example #30
0
    partial void AttachVisualPartial()
    {
        if (FocusedElement == null)
        {
            return;
        }

        WebAssemblyRuntime.InvokeJS($"{JsType}.attachVisual({HtmlId}, {FocusedElement.HtmlId})");
    }