#include <iostream>
#include <gtk/gtk.h>
#include <gtk/gtkprintunixdialog.h>

static const char* gPrinterName = "Print to File";

static const char* gFilenamesToTry[] = {
  "file:///tmp/path_with_colon3slash.ps",
  "file://tmp/path_with_colon2slash.ps",
  "file:/tmp/path_with_colon1slash.ps",
  "file:tmp/path_with_colon0slash.ps",
  "foo:///tmp/nonfile_path_with_colon.ps",
  "file///tmp/path_without_colon.ps",
  "simple_filename.ps",
  ":fileStartingWithColon",
};
static const int gNumFilenames = sizeof(gFilenamesToTry) / sizeof(char*);

// Array of buttons -- one for each filename in gFilenamesToTry
static GtkWidget **gButtons = new GtkWidget*[gNumFilenames];

void
ClickCallback(GtkWidget *widget, GdkEventButton *event, gpointer callback_data)
{
  // Identify which button was pressed, and use that to look up our filename
  const char* fileUriToTest = NULL;
  for (int i = 0; i < gNumFilenames; i++) {
    if (widget == gButtons[i]) {
      fileUriToTest = gFilenamesToTry[i];
      break;
    }
  }
  if (!fileUriToTest) {
    printf("Error identifying button pushed.");
    return;
  }
 
  // Set up a print settings object for print-to-file with our file URI
  GtkPrintSettings* printSettings = gtk_print_settings_new();
  gtk_print_settings_set_printer(printSettings, gPrinterName);
  gtk_print_settings_set(printSettings, GTK_PRINT_SETTINGS_OUTPUT_FILE_FORMAT,
                         "ps");
  gtk_print_settings_set(printSettings, GTK_PRINT_SETTINGS_OUTPUT_URI, fileUriToTest);

  // Set up & show a print dialog with our settings
  GtkWidget* dialog = gtk_print_unix_dialog_new("My Dialog", NULL);
  gtk_print_unix_dialog_set_settings(GTK_PRINT_UNIX_DIALOG(dialog), printSettings);
  gtk_dialog_run(GTK_DIALOG(dialog));
  gtk_widget_hide(dialog);
}

static gboolean
QuitCallback(GtkWidget *window, gpointer data)
{
  gtk_main_quit();
  return FALSE;
}

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

  // Create a window with a button for each entry in gFilenamesToTry.
  GtkWidget *window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
  GtkWidget *vbox =  gtk_vbox_new(FALSE, 0);

  for (int i = 0; i < gNumFilenames; i++) {
    gButtons[i] = gtk_button_new_with_label(gFilenamesToTry[i]);
    g_signal_connect(G_OBJECT(gButtons[i]), "button_press_event",
                     G_CALLBACK(ClickCallback), NULL);
    gtk_container_add(GTK_CONTAINER(vbox), gButtons[i]);
  }
  gtk_container_add(GTK_CONTAINER(window), vbox);

  // Quit when our window closes
  g_signal_connect(G_OBJECT(window), "delete-event", 
		   G_CALLBACK(QuitCallback), NULL);

  gtk_widget_show_all(window);
  gtk_main();
  return 0;
}
