Focus changed in Mouse event handling logic?

I am having an issue with focus change and mouse events. This is the gist of the events:

When ComponentA looses focus, ComponentB is destroyed and rebuilt with some new state.

The crux of the issue is this:

  • ComponentB is clicked.
  • ComponentB::internalMouseDown causes a focus change.
  • ComponentA::focusLost destroys and replaces ComponentB.
  • Returns to ComponentB’s scope with an invalid this pointer to complete the Mouse event.

I assumed that focus events were processed separate, placed in the event queue along with mouse events. This would allow the focus event to destroy and rebuild Component B, then a mouse event to be posted to the actual component under the mouse at time of sending or to realize that the component it was posted to is no longer valid. Or vice versa with mouse event first.

I have a fix for this in my code that avoids it in this one particular case, but its not a very strong guarantee that it won’t happen again.

Should I be coding as if focus changes are not allowed to change program state outside of the component they apply to?

Many thanks to the hard working developers, I am finding JUCE very usable. :slight_smile:

As you’ve discovered, the focus events are dispatched synchronously while processing the mouse event, so it’s possible that the component processing the mouse event may be destroyed while processing that event.

JUCE should be robust against this case. In the mouse handling code, we use a bail-out checker to detect whether the component is destroyed, and early-exit from the mouse handler in this case. Were you seeing crashes in internalMouseDown, or were you just failing to receive the mouse event in the new instance of componentB? If you were getting crashes, that might be a JUCE bug, and I’d be interested to see a minimal code example that demonstrates the problem so that we can fix the problem.