A Dialog Example

Here's a piece of code from the Gnome plot and chart component, Guppi. This is used for an "Open file" dialog. Future versions of Gnome will have a GnomeFileSelection widget, which would be more appropriate for this particular task than a custom dialog; but the example is nonetheless instructive.


  GtkWidget * dialog;
  
  dialog = gnome_dialog_new(_("Guppi: Open"), 
                            GNOME_STOCK_BUTTON_OK,
                            GNOME_STOCK_BUTTON_CANCEL,
                            NULL);

  gnome_dialog_set_close(GNOME_DIALOG(dialog), TRUE);
  gnome_dialog_close_hides(GNOME_DIALOG(dialog), TRUE);

  guppi_setup_dialog(dialog);

  GtkWidget* fileentry = 
    gnome_file_entry_new("guppi:guppi_loadsave_history",
                         _("Guppi: Browse Files For Open"));

  gnome_dialog_editable_enters(GNOME_DIALOG(dialog), 
                               GTK_EDITABLE(gnome_file_entry_gtk_entry(GNOME_FILE_ENTRY(fileentry))));
  gnome_dialog_set_default(GNOME_DIALOG(dialog), GNOME_OK);

  gtk_box_pack_start(GTK_BOX(GNOME_DIALOG(dialog)->vbox),
                     fileentry,
                     TRUE, TRUE, GNOME_PAD);
  

  gtk_widget_show_all(dialog);

  int reply = gnome_dialog_run(GNOME_DIALOG(dialog));
  
  if (reply == GNOME_OK)
    {      
      gchar* s = 
        gnome_file_entry_get_full_path(GNOME_FILE_ENTRY(fileentry),
                                       TRUE);

      /* Application-specific details of actually 
       * loading the file omitted. 
       */                                       
    }
  
  gtk_widget_destroy(dialog);  
    

gnome_dialog_set_close() is called, so this dialog will close if any of its buttons are clicked. However, closing the dialog only calls gtk_widget_hide(), rather than destroying it; gnome_dialog_close_hides() configures this behavior. guppi_setup_dialog() is a wrapper function that calls gnome_dialog_set_parent() to set the main application window as the dialog's parent.

Since the purpose of the dialog is to get a filename, it will be convenient to have the Enter key press the "OK" button; thus the "OK" button should be the default. However, the text entry box would normally steal the Enter key press; gnome_dialog_editable_enters() fixes the problem. gnome_dialog_run() waits for the user to take some action; if "OK" is clicked, we fetch the contents of the text entry and load the file. Note that the dialog is not destroyed after gnome_dialog_run() returns, because we called gnome_dialog_close_hides(). However, the dialog is closed after gnome_dialog_run() returns, because the code ensures that all user actions will close it (using gnome_dialog_set_close() and relying on the default behavior for the window manager's close button). Finally, gtk_widget_destroy() is necessary, since the dialog was not destroyed when it was closed.