Search code examples
cgtkgtk3

C GTK3 - how to wait/sleep before destroying main window


I have a program involving a sshfs mount and when the user closes the main window, i want first to unmount sshfs, then make some tests about that sshfs mount, tell the user the results of the test and finally close the program.

So basically, i just want, after the tests, the main window to stay open for a while and then close.

I've tried just to put g_usleep(3000000); before gtk_main_quit(); but it doesn't work.

Digging a bit into the treads system of GTK, i've then tried this:

gboolean wait_func(gpointer data) {

    g_usleep(3000000);

    return FALSE;
}

void on_window_destroy(GtkWidget *object, app_widgets *app_wid)
{
    //close connection and verify state
    //....

    //updating label text
    gtk_label_set_text(GTK_LABEL(app_wid->lab_test),"connection closed. Exiting...");
    while(gtk_events_pending()) gtk_main_iteration();

    g_idle_add_full(G_PRIORITY_HIGH_IDLE,(GSourceFunc)wait_func,app_wid,(GDestroyNotify)gtk_main_quit);

}

But the main window closes immediately, the program sleeps for 3 seconds and ends. I'd like the window to stay open for that time. How could I do that ?


Solution

  • Use delete-event instead of destroy. Notice the event handler must return FALSE if you want to continue triggering destroy:

    #include <gtk/gtk.h>
    
    static gboolean delete_event(GtkWidget *w, GdkEvent *e, gpointer d) {
      g_print("Doing stuff\n");
      g_usleep(3000000);
      g_print("Stuff done\n");
    
      return FALSE;
    }
    
    int main(int argc, char *argv[]) {
      GtkWidget *w;
    
      gtk_init(&argc, &argv);
    
      w = gtk_window_new(GTK_WINDOW_TOPLEVEL);
      g_signal_connect(w, "delete-event", G_CALLBACK (delete_event), NULL);
      g_signal_connect(w, "destroy", G_CALLBACK (gtk_main_quit), NULL);
    
      gtk_widget_show(w);
      gtk_main();
    
      return 0;
    }