コード例 #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);
        }
コード例 #2
0
        public void Dispose()
        {
            _currentCompletionSource?.SetCanceled();
            var removeInstanceCommand = $"{JsType}.removeInstance('{_instanceId}')";

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

            WebAssemblyRuntime.InvokeJS(command);
            _instances.GetOrAdd(_instanceId.ToString(), this);
        }
コード例 #4
0
ファイル: CachedFileManager.wasm.cs プロジェクト: jokm1/uno-2
        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)}');");
            }
        }
コード例 #6
0
ファイル: Clipboard.wasm.cs プロジェクト: propellingbits/Uno
        public static void SetContent(DataPackage content)
        {
            var text    = WebAssemblyRuntime.EscapeJs(content.Text);
            var command = $"Uno.Utils.Clipboard.setText(\"{text}\");";

            WebAssemblyRuntime.InvokeJS(command);
        }
コード例 #7
0
ファイル: ApplicationView.wasm.cs プロジェクト: jokm1/uno-2
        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);
        }
コード例 #8
0
        private static void SetClipboardText(string text)
        {
            var escapedText = WebAssemblyRuntime.EscapeJs(text);
            var command     = $"{JsType}.setText(\"{escapedText}\");";

            WebAssemblyRuntime.InvokeJS(command);
        }
コード例 #9
0
ファイル: Launcher.wasm.cs プロジェクト: jokm1/uno-2
        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");
        }
コード例 #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);
        }
コード例 #11
0
        partial void StartOrientationChanged()
        {
            _lastKnownOrientation = CurrentOrientation;
            var command = $"{JsType}.startOrientationChanged()";

            WebAssemblyRuntime.InvokeJS(command);
        }
コード例 #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);
        }
コード例 #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);
            }
        }
コード例 #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));
            }
        }
コード例 #15
0
ファイル: FocusManager.wasm.cs プロジェクト: wiltonlazary/uno
        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);
        }
コード例 #16
0
ファイル: UIElement.wasm.cs プロジェクト: alexeystrakh/Uno
        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])));
        }
コード例 #17
0
        partial void StartMessageReceived()
        {
            _instanceSubscriptions.TryAdd(_managedId, this);
            var addListenerCommand = $"{JsType}.startMessageListener('{_managedId}')";

            WebAssemblyRuntime.InvokeJS(addListenerCommand);
        }
コード例 #18
0
        private string[] GetCustomSchemes()
        {
            var js     = $@"Windows.Security.Authentication.Web.WebAuthenticationBroker.getReturnUrl();";
            var origin = WebAssemblyRuntime.InvokeJS(js);

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

            WebAssemblyRuntime.InvokeJS(command);
        }
コード例 #20
0
        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));
            }
        }
コード例 #21
0
        partial void StopMessageReceived()
        {
            _instanceSubscriptions.TryRemove(_managedId, out _);
            var removeListenerCommand = $"{JsType}.stopMessageListener('{_managedId}')";

            WebAssemblyRuntime.InvokeJS(removeListenerCommand);
        }
コード例 #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);
            }
        }
コード例 #23
0
ファイル: Window.wasm.cs プロジェクト: dpisanu/Uno
        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();");
            }
        }
コード例 #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);
            }
コード例 #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);
            }
コード例 #26
0
        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));
        }
コード例 #27
0
ファイル: Window.wasm.cs プロジェクト: nepronen/Uno
        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();
        }
コード例 #28
0
        static partial void InnerReportPageView(string pageName, string arguments)
        {
            var command = string.Concat(
                "Uno.UI.Demo.Analytics.reportPageView(\"",
                WebAssemblyRuntime.EscapeJs(pageName),
                "\");");

            WebAssemblyRuntime.InvokeJS(command);
        }
コード例 #29
0
ファイル: Window.wasm.cs プロジェクト: masums/Uno
        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();
        }
コード例 #30
0
    partial void AttachVisualPartial()
    {
        if (FocusedElement == null)
        {
            return;
        }

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