Any idea why VST plugins on Linux immediately lose focus?

I’m using Raspbain 10. I compiled latest audio plugin host and my plugin. I click in a TextEditor, it gets focus and the caret appears and then the caret immediately disappears. Can’t type. Any ideas?

Here is a video, you can see when I click, the focus won’t change. The new control gets focus for a second and then it jumps back to first control.

Here is the code: https://github.com/FigBug/juce_bugs/tree/master/Linux_Focus

diff --git a/modules/juce_gui_basics/components/juce_Component.cpp b/modules/juce_gui_basics/components/juce_Component.cpp
index 1a2106a4c..23c890996 100644
--- a/modules/juce_gui_basics/components/juce_Component.cpp
+++ b/modules/juce_gui_basics/components/juce_Component.cpp
@@ -2720,6 +2720,7 @@ void Component::takeKeyboardFocus (FocusChangeType cause)
         if (auto* peer = getPeer())
         {
             const WeakReference<Component> safePointer (this);
+            peer->setLastFocusedComponent (this);
             peer->grabFocus();
 
             if (peer->isFocused() && currentlyFocusedComponent != this)
diff --git a/modules/juce_gui_basics/windows/juce_ComponentPeer.h b/modules/juce_gui_basics/windows/juce_ComponentPeer.h
index 28748ef8f..0fd8efa36 100644
--- a/modules/juce_gui_basics/windows/juce_ComponentPeer.h
+++ b/modules/juce_gui_basics/windows/juce_ComponentPeer.h
@@ -265,6 +265,8 @@ public:
     void handleFocusLoss();
 
     Component* getLastFocusedSubcomponent() const noexcept;
+
+    void setLastFocusedComponent (Component* c) { lastFocusedComponent = c; }
 
     /** Called when a key is pressed.
         For keycode info, see the KeyPress class.

Here is a fix. It’s a bit of a hack, but I don’t know my way around inside the Linux windowing code very well. The issue is that the ComponentPeer for a plugin window on Linux doesn’t consider itself to have the focus. So when you click on a Component, it tells the peer to grab focus, which it does. Once it gets focus it resets the focus to the last Component that had focus, instead of the focus I just switched to.

This seems to be a Raspbian issue, I can’t reproduce on Ubuntu or Debian. Can you set a breakpoint in the handleFocusInEvent() method in juce_linux_X11_Windowing.cpp and see if it’s called when you click on the plugin window?

Yes, the issue is that it’s called for every click, even when the window already has focus. handleFocusInEvent then sets the focus back to the last Component that had it. Taking it away from the Component the click just set it to.

When I click on the plugin and it already has focus, handleFocusOutEvent is called twice and then handleFocusInEvent is called once.

What I can’t figure out is why the Peer is losing focus. Doesn’t appear to be anything the JUCE code is doing.