#include <gio/gio.h>
#include <glib.h>
#include <gtk/gtk.h>

int main(int argc, char *argv[])
{
    gtk_init(&argc, &argv);

    GMenu *menu = g_menu_new ();
    g_menu_insert (menu, 0, "Test", NULL);

    GtkWidget *menu_button = gtk_menu_button_new ();
    gtk_menu_button_set_use_popover (GTK_MENU_BUTTON(menu_button), TRUE);

    GtkWidget *scrolled_window = gtk_scrolled_window_new (NULL, NULL);
    gtk_container_add (GTK_CONTAINER(scrolled_window), menu_button);

    // Set the model after the menu button has a GtkScrollable
    // ancestor, so the popover that the button constructs has a
    // non-null priv->parent_scrollable
    gtk_menu_button_set_menu_model (GTK_MENU_BUTTON(menu_button), G_MENU_MODEL(menu));

    GtkWidget *window_1 = gtk_window_new(GTK_WINDOW_TOPLEVEL);
    gtk_window_set_title (GTK_WINDOW(window_1), "Window 1");
    gtk_container_add (GTK_CONTAINER(window_1), scrolled_window);
    gtk_widget_show_all (window_1);

    // Don't lose the button when we remove it
    g_object_ref (menu_button);

    // Now, reparent the menu button. First, remove it from its parent.
    GtkWidget *parent = gtk_widget_get_parent (menu_button);
    gtk_container_remove (GTK_CONTAINER(parent), menu_button);

    // Then add it to a new window
    GtkWidget *window_2 = window_2 = gtk_window_new (GTK_WINDOW_TOPLEVEL);
    gtk_window_set_title (GTK_WINDOW(window_2), "Window 2");
    gtk_container_add (GTK_CONTAINER(window_2), menu_button);
    gtk_widget_show (window_2);

    // Null out the parent of the popover's priv->parent_scrollable
    gtk_widget_destroy (scrolled_window);

    // Crash when the new window is checked for needing a resize, since in
    // _gtk_popover_update_child_visible, `gtk_widget_get_parent
    // (GTK_WIDGET (priv->parent_scrollable))` now returns null.
    gtk_main();

    return 0;
}
