question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

X11: System.Exception: Unable to initialize GTK on separate thread

See original GitHub issue

Describe the bug The exception in the title is thrown when opening a file dialog.

To Reproduce Create a new project using the Avalonia .NET Core App template. (NOT THE MVVM ONE). Here’s the relevant code that triggers the exception:

<!-- MainWindow.axaml -->
<Window xmlns="https://github.com/avaloniaui"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d" d:DesignWidth="800" d:DesignHeight="450"
        x:Class="JGCodes.AvaloniaTest.MainWindow"
        Title="Avalonia Test">
    <Button Name="SpecialButton" Click="OnButtonClick">Open, sesame!</Button>
</Window>
// MainWindow.axaml.cs
using Avalonia.Controls;
using Avalonia.Interactivity;

namespace JGCodes.AvaloniaTest
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        public async void OnButtonClick(object sender, RoutedEventArgs e)
        {
            OpenFileDialog ofd = new();
            await ofd.ShowAsync(this);
        }
    }
}

Run the project, click the button, and receive the above exception.

Expected behavior A file dialog should appear.

Desktop (please complete the following information):

  • OS: Linux (ArcoLinux, KDE, XWayland)
  • Version 0.10.17

Additional context N/A

Issue Analytics

  • State:closed
  • Created a year ago
  • Comments:9 (6 by maintainers)

github_iconTop GitHub Comments

1reaction
maxkatz6commented, Jan 12, 2023

Should be fixed with 11.0 previews, as we use FreeDesktop dialogs instead, when available. Also, GTK initialization was changed, which might also solve old issue, if FreeDesktop is not available.

Please let us know if it’s still a problem in 11.0 previews.

0reactions
brunzefbcommented, Dec 27, 2022

FWIW, my workaround. below the ViewModel code, use binding to the view model. You do need kdialog installed on KDE systems for this to work.

     <Button 
                Command="{Binding OpenFileCommand}"
                Margin="0,0,10,0"
                VerticalAlignment="Center" 
                HorizontalAlignment="Right"
                Height="26"
                FontSize="11"
                Content="_Open..." />

Here the ViewModel code


    public void OpenFileCommand()
    {
        var helper = new OpenDlgHelper();
        var result = helper.GetFileName();
        HexFile = string.IsNullOrEmpty(result) ? _prompt : result;
    }

And here the helper class

using System.Diagnostics;
using System.IO;
using System.Text;
using System.Threading.Tasks;

namespace QMK_Toolbox;

public class OpenDlgHelper
{
    public StringBuilder sb { get; set; }
    
    public string GetFileName()
    {
        RunProcessAsync("/usr/bin/kdialog", "--getopenfilename /home/").Wait();
        return sb.ToString();
    }

    private async Task<int> RunProcessAsync(string command, string args)
    {
        sb = new StringBuilder();
        using (var process = new Process
               {
                   StartInfo =
                   {
                       FileName = command,
                       Arguments = args,
                       WorkingDirectory = Path.GetDirectoryName(command),
                       UseShellExecute = false,
                       CreateNoWindow = true,
                       RedirectStandardOutput = true,
                       RedirectStandardError = true
                   },
                   EnableRaisingEvents = true
               })
        {
            return await RunProcessAsync(process).ConfigureAwait(false);
        }
    }

    private Task<int> RunProcessAsync(Process process)
    {
        var tcs = new TaskCompletionSource<int>();

        process.Exited += (sender, e) =>
        {
            process.WaitForExit();
            tcs.SetResult(process.ExitCode);
        };

        process.OutputDataReceived += ProcessOutput;
        process.ErrorDataReceived += ProcessErrorOutput;

        bool started = process.Start();
        if (!started)
        {
            Debug.WriteLine($"Could not start process: {process}");
        }

        process.BeginOutputReadLine();
        process.BeginErrorReadLine();

        return tcs.Task;
    }

    private void ProcessOutput(object sender, DataReceivedEventArgs e)
    {
        if (e.Data != null)
        {
            sb.Append(e.Data);
        }
    }

    private void ProcessErrorOutput(object sender, DataReceivedEventArgs e)
    {
        if (e.Data != null)
        {
            Debug.WriteLine(e.Data);
        }
    }
}
Read more comments on GitHub >

github_iconTop Results From Across the Web

SSH X11 forwarding with sudo and missing magic cookies
After doing this, X11 forwarding works, but it's a non-optimal solution since the cookie ... RuntimeError: Unable to initialize GTK: could not open...
Read more >
MessageDialog in separate thread - c++
I can't open that MessageDialog in the main thread, because then it is blocked and I can't do my calculations, so I wanted...
Read more >
EM Server automatically going down - BMC Community
Exception in thread "main" java.lang.InternalError: Can't connect to X11 window server using ':0.0' as the value of the DISPLAY variable. at sun.awt.
Read more >
Lunacy Linux version crashes when Saving
mrmikel@Debian:~$ lunacy Unhandled exception. System.Exception: Unable to initialize GTK on separate thread at Avalonia.X11.NativeDialogs.
Read more >
How do I fix a "cannot open display" error when ...
8), opening an terminal in X11 and running xhost + , I then ssh -Y to my Ubuntu 10.04 VM (running on VMware...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found