private void UpdateTitle(string title)
 {
     using (var buffer = new Utf8Buffer(string.IsNullOrWhiteSpace(title) ? "" : title))
     {
         Title = buffer.DangerousGetHandle();
     }
 }
        void GtkThread(TaskCompletionSource <bool> tcs)
        {
            try
            {
                X11.XInitThreads();
            }catch {}
            Resolver.Resolve();
            if (Native.GdkWindowForeignNewForDisplay == null)
            {
                throw new Exception("gdk_x11_window_foreign_new_for_display is not found in your libgdk-3.so");
            }
            using (var backends = new Utf8Buffer("x11"))
                Native.GdkSetAllowedBackends?.Invoke(backends);
            if (!Native.GtkInitCheck(0, IntPtr.Zero))
            {
                tcs.SetResult(false);
                return;
            }

            using (var utf = new Utf8Buffer($"avalonia.app.a{Guid.NewGuid().ToString("N")}"))
                App = Native.GtkApplicationNew(utf, 0);
            if (App == IntPtr.Zero)
            {
                tcs.SetResult(false);
                return;
            }
            GdkDisplay = Native.GdkGetDefaultDisplay();
            tcs.SetResult(true);
            while (true)
            {
                Native.GtkMainIteration();
            }
        }
Beispiel #3
0
 public void SetTitle(string title)
 {
     using (var buffer = new Utf8Buffer(title))
     {
         _native.SetTitle(buffer.DangerousGetHandle());
     }
 }
Beispiel #4
0
        public static void Initialize()
        {
            if (!s_gtkInitialized)
            {
                try
                {
                    X11.XInitThreads();
                }catch {}
                Resolver.Resolve();
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
                {
                    using (var backends = new Utf8Buffer("x11"))
                        Native.GdkSetAllowedBackends?.Invoke(backends);
                }
                Native.GtkInit(0, IntPtr.Zero);
                var disp = Native.GdkGetDefaultDisplay();
                DisplayClassName =
                    Utf8Buffer.StringFromPtr(Native.GTypeName(Marshal.ReadIntPtr(Marshal.ReadIntPtr(disp))));

                using (var utf = new Utf8Buffer("avalonia.app." + Guid.NewGuid()))
                    App = Native.GtkApplicationNew(utf, 0);
                //Mark current thread as UI thread
                s_tlsMarker      = true;
                s_gtkInitialized = true;
            }
            AvaloniaLocator.CurrentMutable.Bind <IWindowingPlatform>().ToConstant(Instance)
            .Bind <IClipboard>().ToSingleton <ClipboardImpl>()
            .Bind <IStandardCursorFactory>().ToConstant(new CursorFactory())
            .Bind <IKeyboardDevice>().ToConstant(Keyboard)
            .Bind <IPlatformSettings>().ToConstant(Instance)
            .Bind <IPlatformThreadingInterface>().ToConstant(Instance)
            .Bind <ISystemDialogImpl>().ToSingleton <SystemDialog>()
            .Bind <IRenderLoop>().ToConstant(new DefaultRenderLoop(60))
            .Bind <IPlatformIconLoader>().ToConstant(new PlatformIconLoader());
        }
Beispiel #5
0
        static void OnText(IntPtr clipboard, IntPtr utf8string, IntPtr userdata)
        {
            var handle = GCHandle.FromIntPtr(userdata);

            ((TaskCompletionSource <string>)handle.Target)
            .TrySetResult(Utf8Buffer.StringFromPtr(utf8string));
            handle.Free();
        }
 public void ShaderSourceString(int shader, string source)
 {
     using (var b = new Utf8Buffer(source))
     {
         var ptr = b.DangerousGetHandle();
         var len = new IntPtr(b.ByteLen);
         ShaderSource(shader, 1, new IntPtr(&ptr), new IntPtr(&len));
     }
 }
 private void UpdateGesture(Input.KeyGesture gesture)
 {
     // todo ensure backend can cope with setting null gesture.
     using (var buffer = new Utf8Buffer(gesture == null ? "" : OsxUnicodeKeys.ConvertOSXSpecialKeyCodes(gesture.Key)))
     {
         var modifiers = gesture == null ? AvnInputModifiers.AvnInputModifiersNone : (AvnInputModifiers)gesture.KeyModifiers;
         SetGesture(buffer.DangerousGetHandle(), modifiers);
     }
 }
Beispiel #8
0
 public void SetupApplicationName()
 {
     if (!string.IsNullOrWhiteSpace(Application.Current.Name))
     {
         using (var buffer = new Utf8Buffer(Application.Current.Name))
         {
             _factory.MacOptions.SetApplicationTitle(buffer.DangerousGetHandle());
         }
     }
 }
Beispiel #9
0
        private void AddItemsToMenu(IAvnAppMenu menu, ICollection <NativeMenuItemBase> items, bool isMainMenu = false)
        {
            foreach (var i in items)
            {
                if (i is NativeMenuItem item)
                {
                    var menuItem = _factory.CreateMenuItem();

                    AddMenuItem(item);

                    menuItem.SetAction(new PredicateCallback(() =>
                    {
                        if (item.Command != null || item.HasClickHandlers)
                        {
                            return(item.Enabled);
                        }

                        return(false);
                    }), new MenuActionCallback(() => { item.RaiseClick(); }));

                    if (item.Menu?.Items.Count > 0 || isMainMenu)
                    {
                        var subMenu = CreateSubmenu(item.Menu?.Items);

                        menuItem.SetSubMenu(subMenu);

                        using (var buffer = new Utf8Buffer(item.Header))
                        {
                            subMenu.Title = buffer.DangerousGetHandle();
                        }
                    }
                    else
                    {
                        using (var buffer = new Utf8Buffer(item.Header))
                        {
                            menuItem.Title = buffer.DangerousGetHandle();
                        }

                        if (item.Gesture != null)
                        {
                            using (var buffer = new Utf8Buffer(item.Gesture.Key.ToString().ToLower()))
                            {
                                menuItem.SetGesture(buffer.DangerousGetHandle(), (AvnInputModifiers)item.Gesture.KeyModifiers);
                            }
                        }
                    }

                    menu.AddItem(menuItem);
                }
                else if (i is NativeMenuItemSeperator seperator)
                {
                    menu.AddItem(_factory.CreateMenuItemSeperator());
                }
            }
        }
Beispiel #10
0
        private void SetChildren(IAvnAppMenu menu, ICollection <NativeMenuItemBase> children)
        {
            foreach (var i in children)
            {
                if (i is NativeMenuItem item)
                {
                    AddMenuItem(item);

                    var menuItem = _factory.CreateMenuItem();

                    using (var buffer = new Utf8Buffer(item.Header))
                    {
                        menuItem.Title = buffer.DangerousGetHandle();
                    }

                    if (item.Gesture != null)
                    {
                        using (var buffer = new Utf8Buffer(ConvertOSXSpecialKeyCodes(item.Gesture.Key)))
                        {
                            menuItem.SetGesture(buffer.DangerousGetHandle(), (AvnInputModifiers)item.Gesture.KeyModifiers);
                        }
                    }

                    menuItem.SetAction(new PredicateCallback(() =>
                    {
                        if (item.Command != null || item.HasClickHandlers)
                        {
                            return(item.Enabled);
                        }

                        return(false);
                    }), new MenuActionCallback(() => { item.RaiseClick(); }));
                    menu.AddItem(menuItem);

                    if (item.Menu?.Items?.Count > 0)
                    {
                        var submenu = _factory.CreateMenu();

                        using (var buffer = new Utf8Buffer(item.Header))
                        {
                            submenu.Title = buffer.DangerousGetHandle();
                        }

                        menuItem.SetSubMenu(submenu);

                        AddItemsToMenu(submenu, item.Menu?.Items);
                    }
                }
                else if (i is NativeMenuItemSeperator seperator)
                {
                    menu.AddItem(_factory.CreateMenuItemSeperator());
                }
            }
        }
 protected static Func <string, bool, IntPtr> ConvertNative(Func <Utf8Buffer, IntPtr> func) =>
 (proc, optional) =>
 {
     using (var u = new Utf8Buffer(proc))
     {
         var rv = func(u);
         if (rv == IntPtr.Zero && !optional)
         {
             throw new OpenGlException("Missing function " + proc);
         }
         return(rv);
     }
 };
Beispiel #12
0
 public static GlInterface FromNativeUtf8GetProcAddress(Func <Utf8Buffer, IntPtr> getProcAddress) =>
 new GlInterface((proc, optional) =>
 {
     using (var u = new Utf8Buffer(proc))
     {
         var rv = getProcAddress(u);
         if (rv == IntPtr.Zero && !optional)
         {
             throw new OpenGlException("Missing function " + proc);
         }
         return(rv);
     }
 });
Beispiel #13
0
        /// <summary>
        /// Connects the signal.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj">The object.</param>
        /// <param name="name">The name.</param>
        /// <param name="handler">The handler.</param>
        /// <returns>IDisposable.</returns>
        /// <exception cref="ArgumentException">Unable to connect to signal " + name</exception>
        public static IDisposable ConnectSignal <T>(IntPtr obj, string name, T handler)
        {
            var handle = GCHandle.Alloc(handler);
            var ptr    = Marshal.GetFunctionPointerForDelegate((Delegate)(object)handler);

            using var utf = new Utf8Buffer(name);
            var id = g_signal_connect_object(obj, utf, ptr, IntPtr.Zero, 0);

            if (id == 0)
            {
                throw new ArgumentException("Unable to connect to signal " + name);
            }
            return(new ConnectedSignal(obj, handle, id));
        }
Beispiel #14
0
        public Task SetTextAsync(string text)
        {
            _native.Clear();

            if (text != null)
            {
                using (var buffer = new Utf8Buffer(text))
                {
                    _native.SetText(buffer.DangerousGetHandle());
                }
            }

            return(Task.CompletedTask);
        }
Beispiel #15
0
        internal void Initialise(AvaloniaNativeMenuExporter exporter, NativeMenu managedMenu, string title)
        {
            _exporter   = exporter;
            ManagedMenu = managedMenu;

            ((INotifyCollectionChanged)ManagedMenu.Items).CollectionChanged += OnMenuItemsChanged;

            if (!string.IsNullOrWhiteSpace(title))
            {
                using (var buffer = new Utf8Buffer(title))
                {
                    Title = buffer.DangerousGetHandle();
                }
            }
        }
Beispiel #16
0
 public static INativeControlHostDestroyableControlHandle CreateGtkFileChooser(IntPtr parentXid)
 {
     return(GtkInteropHelper.RunOnGlibThread(() =>
     {
         using (var title = new Utf8Buffer("Embedded"))
         {
             var widget = gtk_file_chooser_dialog_new(title, IntPtr.Zero, GtkFileChooserAction.SelectFolder,
                                                      IntPtr.Zero);
             gtk_widget_realize(widget);
             var xid = gdk_x11_window_get_xid(gtk_widget_get_window(widget));
             gtk_window_present(widget);
             return new FileChooser(widget, xid);
         }
     }).Result);
 }
Beispiel #17
0
        public static Task <bool> StartGtk()
        {
            var tcs = new TaskCompletionSource <bool>();

            new Thread(() =>
            {
                try
                {
                    using (var backends = new Utf8Buffer("x11"))
                        gdk_set_allowed_backends(backends);
                }
                catch
                {
                    //Ignore
                }

                Environment.SetEnvironmentVariable("WAYLAND_DISPLAY",
                                                   "/proc/fake-display-to-prevent-wayland-initialization-by-gtk3");

                if (!gtk_init_check(0, IntPtr.Zero))
                {
                    tcs.SetResult(false);
                    return;
                }

                IntPtr app;
                using (var utf = new Utf8Buffer($"avalonia.app.a{Guid.NewGuid():N}"))
                    app = gtk_application_new(utf, 0);
                if (app == IntPtr.Zero)
                {
                    tcs.SetResult(false);
                    return;
                }

                s_display = gdk_display_get_default();
                tcs.SetResult(true);
                while (true)
                {
                    gtk_main_iteration();
                }
            })
            {
                Name = "GTK3THREAD", IsBackground = true
            }.Start();
            return(tcs.Task);
        }
 public unsafe Task SetDataObjectAsync(IDataObject data)
 {
     _native.Clear();
     foreach (var fmt in data.GetDataFormats())
     {
         var o = data.Get(fmt);
         if (o is string s)
         {
             using (var b = new Utf8Buffer(s))
                 _native.SetText(fmt, b.DangerousGetHandle());
         }
         else if (o is byte[] bytes)
             fixed(byte *pbytes = bytes)
             _native.SetBytes(fmt, new IntPtr(pbytes), bytes.Length);
     }
     return(Task.CompletedTask);
 }
Beispiel #19
0
        public static void Initialize(Gtk3PlatformOptions options)
        {
            Resolver.Custom      = options.CustomResolver;
            UseDeferredRendering = EnvOption("USE_DEFERRED_RENDERING", true, options.UseDeferredRendering);
            var useGpu = EnvOption("USE_GPU", false, options.UseGpuAcceleration);

            if (!s_gtkInitialized)
            {
                try
                {
                    X11.XInitThreads();
                }catch {}
                Resolver.Resolve();
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
                {
                    using (var backends = new Utf8Buffer("x11"))
                        Native.GdkSetAllowedBackends?.Invoke(backends);
                }
                Native.GtkInit(0, IntPtr.Zero);
                var disp = Native.GdkGetDefaultDisplay();
                DisplayClassName =
                    Utf8Buffer.StringFromPtr(Native.GTypeName(Marshal.ReadIntPtr(Marshal.ReadIntPtr(disp))));

                using (var utf = new Utf8Buffer("avalonia.app." + Guid.NewGuid()))
                    App = Native.GtkApplicationNew(utf, 0);
                //Mark current thread as UI thread
                s_tlsMarker      = true;
                s_gtkInitialized = true;
            }
            AvaloniaLocator.CurrentMutable.Bind <IWindowingPlatform>().ToConstant(Instance)
            .Bind <IClipboard>().ToSingleton <ClipboardImpl>()
            .Bind <IStandardCursorFactory>().ToConstant(new CursorFactory())
            .Bind <IKeyboardDevice>().ToConstant(Keyboard)
            .Bind <IPlatformSettings>().ToConstant(Instance)
            .Bind <IPlatformThreadingInterface>().ToConstant(Instance)
            .Bind <ISystemDialogImpl>().ToSingleton <SystemDialog>()
            .Bind <IRenderLoop>().ToConstant(new RenderLoop())
            .Bind <IRenderTimer>().ToConstant(new DefaultRenderTimer(60))
            .Bind <PlatformHotkeyConfiguration>().ToSingleton <PlatformHotkeyConfiguration>()
            .Bind <IPlatformIconLoader>().ToConstant(new PlatformIconLoader());
            if (useGpu)
            {
                EglGlPlatformFeature.TryInitialize();
            }
        }
Beispiel #20
0
        public static void Initialize()
        {
            Resolver.Resolve();
            Native.GtkInit(0, IntPtr.Zero);
            using (var utf = new Utf8Buffer("avalonia.app." + Guid.NewGuid()))
                App = Native.GtkApplicationNew(utf, 0);
            //Mark current thread as UI thread
            s_tlsMarker = true;

            AvaloniaLocator.CurrentMutable.Bind <IWindowingPlatform>().ToConstant(Instance)
            .Bind <IClipboard>().ToSingleton <ClipboardImpl>()
            .Bind <IStandardCursorFactory>().ToConstant(new CursorFactory())
            .Bind <IKeyboardDevice>().ToConstant(Keyboard)
            .Bind <IPlatformSettings>().ToConstant(Instance)
            .Bind <IPlatformThreadingInterface>().ToConstant(Instance)
            .Bind <ISystemDialogImpl>().ToSingleton <SystemDialog>()
            .Bind <IRenderLoop>().ToConstant(new DefaultRenderLoop(60))
            .Bind <IPlatformIconLoader>().ToConstant(new PlatformIconLoader());
        }
Beispiel #21
0
            public GLShader(GlInterface gl, int shaderType, string source)
            {
                if (source == null)
                {
                    throw new ArgumentNullException(nameof(source));
                }

                this.gl = gl;

                ShaderId = gl.CreateShader(shaderType);
                using (var b = new Utf8Buffer(source))
                {
                    void *[] pstr = new void *[2];
                    long[]   len  = new long[2];
                    pstr[0] = (void *)b.DangerousGetHandle();
                    len[0]  = b.ByteLen;

                    fixed(void **ppstr = pstr)
                    fixed(long *plen = len)
                    gl.ShaderSource(ShaderId, 1, (IntPtr)ppstr, (IntPtr)plen);
                }
                gl.CompileShader(ShaderId);
                int compile_succeeded;

                gl.GetShaderiv(ShaderId, GL_COMPILE_STATUS, &compile_succeeded);

                if (compile_succeeded == 0)
                {
                    byte[] buf = new byte[MaxErrorLength];
                    string log;
                    fixed(byte *pbuf = buf)
                    {
                        gl.GetShaderInfoLog(ShaderId, MaxErrorLength, out int log_length, pbuf);
                        log = Encoding.UTF8.GetString(pbuf, log_length);
                    }

                    throw new InvalidOperationException($"Failed to compile shader : {log}");
                }
            }
Beispiel #22
0
        private IntPtr GetCursor(object desc)
        {
            IntPtr rv;
            var    name = desc as string;

            if (name != null)
            {
                var    theme = Native.GtkIconThemeGetDefault();
                IntPtr icon, error;
                using (var u = new Utf8Buffer(name))
                    icon = Native.GtkIconThemeLoadIcon(theme, u, 32, 0, out error);
                rv = icon == IntPtr.Zero
                    ? Native.GdkCursorNew(GdkCursorType.XCursor)
                    : Native.GdkCursorNewFromPixbuf(Native.GdkGetDefaultDisplay(), icon, 0, 0);
            }
            else
            {
                rv = Native.GdkCursorNew((CursorType)desc);
            }


            return(rv);
        }
Beispiel #23
0
 public static IPlatformHandle CreateGtkFileChooser(IntPtr parentXid)
 {
     if (s_gtkTask == null)
     {
         s_gtkTask = StartGtk();
     }
     if (!s_gtkTask.Result)
     {
         return(null);
     }
     return(RunOnGlibThread(() =>
     {
         using (var title = new Utf8Buffer("Embedded"))
         {
             var widget = gtk_file_chooser_dialog_new(title, IntPtr.Zero, GtkFileChooserAction.SelectFolder,
                                                      IntPtr.Zero);
             gtk_widget_realize(widget);
             var xid = gdk_x11_window_get_xid(gtk_widget_get_window(widget));
             gtk_window_present(widget);
             return new FileChooser(widget, xid);
         }
     }).Result);
 }
            public void SetCursorRect(Rect rect)
            {
                var needEnqueue = _queuedCursorRect == null;

                _queuedCursorRect = rect;
                if (needEnqueue)
                {
                    Dispatcher.UIThread.Post(() =>
                    {
                        if (_queuedCursorRect == null)
                        {
                            return;
                        }
                        var rc            = _queuedCursorRect.Value;
                        _queuedCursorRect = null;

                        if (_parent._xic == IntPtr.Zero)
                        {
                            return;
                        }

                        rect *= _parent._scaling;

                        var pt = new XPoint
                        {
                            X = (short)Math.Min(Math.Max(rect.X, short.MinValue), short.MaxValue),
                            Y = (short)Math.Min(Math.Max(rect.Y + rect.Height, short.MinValue), short.MaxValue)
                        };

                        using var spotLoc = new Utf8Buffer(XNames.XNSpotLocation);
                        var list          = XVaCreateNestedList(0, spotLoc, ref pt, IntPtr.Zero);
                        XSetICValues(_parent._xic, XNames.XNPreeditAttributes, list, IntPtr.Zero);
                        XFree(list);
                    }, DispatcherPriority.Background);
                }
            }
Beispiel #25
0
        public unsafe static Task <string[]> ShowDialog(string title, GtkWindow parent, GtkFileChooserAction action,
                                                        bool multiselect, string initialFileName, Action <GtkFileChooser> modify)
        {
            GtkFileChooser dlg;

            parent = parent ?? GtkWindow.Null;
            using (var name = new Utf8Buffer(title))
                dlg = Native.GtkFileChooserDialogNew(name, parent, action, IntPtr.Zero);
            modify?.Invoke(dlg);
            if (multiselect)
            {
                Native.GtkFileChooserSetSelectMultiple(dlg, true);
            }

            Native.GtkWindowSetModal(dlg, true);
            var tcs = new TaskCompletionSource <string[]>();
            List <IDisposable> disposables = null;
            Action             dispose     = () =>
            {
                // ReSharper disable once PossibleNullReferenceException
                foreach (var d in disposables)
                {
                    d.Dispose();
                }
                disposables.Clear();
            };

            disposables = new List <IDisposable>
            {
                Signal.Connect <Native.D.signal_generic>(dlg, "close", delegate
                {
                    tcs.TrySetResult(null);
                    dispose();
                    return(false);
                }),
                Signal.Connect <Native.D.signal_dialog_response>(dlg, "response", (_, resp, __) =>
                {
                    string[] result = null;
                    if (resp == GtkResponseType.Accept)
                    {
                        var rlst = new List <string>();
                        var gs   = Native.GtkFileChooserGetFilenames(dlg);
                        var cgs  = gs;
                        while (cgs != null)
                        {
                            if (cgs->Data != IntPtr.Zero)
                            {
                                rlst.Add(Utf8Buffer.StringFromPtr(cgs->Data));
                            }
                            cgs = cgs->Next;
                        }

                        Native.GSlistFree(gs);
                        result = rlst.ToArray();
                    }

                    Native.GtkWidgetHide(dlg);
                    dispose();
                    tcs.TrySetResult(result);
                    return(false);
                }),
                dlg
            };
            using (var open = new Utf8Buffer("Open"))
                Native.GtkDialogAddButton(dlg, open, GtkResponseType.Accept);
            using (var open = new Utf8Buffer("Cancel"))
                Native.GtkDialogAddButton(dlg, open, GtkResponseType.Cancel);
            if (initialFileName != null)
            {
                using (var fn = new Utf8Buffer(initialFileName))
                    Native.GtkFileChooserSetFilename(dlg, fn);
            }
            Native.GtkWindowPresent(dlg);
            return(tcs.Task);
        }
Beispiel #26
0
 private unsafe bool OnCommit(IntPtr gtkwidget, IntPtr utf8string, IntPtr userdata)
 {
     Input(new RawTextInputEventArgs(Gtk3Platform.Keyboard, _lastKbdEvent, Utf8Buffer.StringFromPtr(utf8string)));
     return(true);
 }
Beispiel #27
0
 static extern IntPtr eglGetProcAddress(Utf8Buffer proc);
Beispiel #28
0
 public void SetTitle(string title)
 {
     using (var t = new Utf8Buffer(title))
         Native.GtkWindowSetTitle(GtkWidget, t);
 }
Beispiel #29
0
 public static extern IntPtr XVaCreateNestedList(int unused,
                                                 Utf8Buffer xnSpotLocation, XPoint *value2, Utf8Buffer xnFontSet, IntPtr fs, IntPtr zero);
Beispiel #30
0
 public static extern IntPtr XVaCreateNestedList(int unused, Utf8Buffer name, ref XPoint point, IntPtr terminator);