pub fn write_pointer_button_events_system(
    egui_global_settings: Res<EguiGlobalSettings>,
    mut commands: Commands,
    hovered_non_window_egui_context: Option<Res<HoveredNonWindowEguiContext>>,
    modifier_keys_state: Res<ModifierKeysState>,
    mut mouse_button_input_reader: EventReader<MouseButtonInput>,
    mut egui_input_event_writer: EventWriter<EguiInputEvent>,
    egui_contexts: Query<(&EguiContextSettings, &EguiContextPointerPosition), With<EguiContext>>,
) {
    let modifiers = modifier_keys_state.to_egui_modifiers();
    for event in mouse_button_input_reader.read() {
        let hovered_context = hovered_non_window_egui_context
            .as_deref()
            .map_or(event.window, |hovered| hovered.0);

        let Some((context_settings, context_pointer_position)) =
            egui_contexts.get_some(hovered_context)
        else {
            continue;
        };

        if !context_settings
            .input_system_settings
            .run_write_pointer_button_events_system
        {
            continue;
        }

        let button = match event.button {
            MouseButton::Left => Some(egui::PointerButton::Primary),
            MouseButton::Right => Some(egui::PointerButton::Secondary),
            MouseButton::Middle => Some(egui::PointerButton::Middle),
            MouseButton::Back => Some(egui::PointerButton::Extra1),
            MouseButton::Forward => Some(egui::PointerButton::Extra2),
            _ => None,
        };
        let Some(button) = button else {
            continue;
        };
        let pressed = match event.state {
            ButtonState::Pressed => true,
            ButtonState::Released => false,
        };
        egui_input_event_writer.write(EguiInputEvent {
            context: hovered_context,
            event: egui::Event::PointerButton {
                pos: context_pointer_position.position,
                button,
                pressed,
                modifiers,
            },
        });

        // If we are hovering over some UI in world space, we want to mark it as focused on mouse click.
        if egui_global_settings.enable_focused_non_window_context_updates && pressed {
            if let Some(hovered_non_window_egui_context) = &hovered_non_window_egui_context {
                commands.insert_resource(FocusedNonWindowEguiContext(
                    hovered_non_window_egui_context.0,
                ));
            } else {
                commands.remove_resource::<FocusedNonWindowEguiContext>();
            }
        }
    }
}
Reads [`MouseButtonInput`] events and wraps them into [`EguiInputEvent`], can redirect events to [`HoveredNonWindowEguiContext`],
inserts, updates or removes the [`FocusedNonWindowEguiContext`] resource based on a hovered context.
src/input.rs