/*
	main.c
	13.3.99 tn
*/

#ifdef HAVE_CONFIG_H
# include <config.h>
#endif

#include "largefile.h"

#if HAVE_LOCALE_H
#include <locale.h>
#else
# define setlocale(Category, Locale) 
#endif
#include "gettext.h"

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/stat.h>

#if ENABLE_NLS
# define _(String) gettext (String)
# define N_(String) gettext_noop (String)
#else
# define _(String) (String)
# define N_(String) (String)
#endif

#include <gtk/gtk.h>
#include <gdk/gdk.h>
#include <gdk-pixbuf/gdk-pixbuf.h>
#include <gdk/gdkprivate.h>
#include "xcdrdata.h"
#include "xcdroast.h"
#include "main.h"
#include "../xpms/xcdricon.xpm"

GtkWidget *toplevel;
GtkWidget *splitspace;
GtkWidget *sidespace;
GtkWidget *workspace;
setup_data_t setupdata;
current_set_t curset;

gint debug;
gint submenu;
gint bigfonts;
gint oldfontcode;
gint altdevscan;
gint no_versioncheck;

static gint lastxsize, lastysize;

extern gchar sharedir[MAXLINE];
extern gchar rootconfig[MAXLINE];
extern gchar xcdroast_version_loaded[MAXLINE];



/* exit-button handler */

static void menu_exit(GtkWidget *widget, gpointer data) {
gint ret;

	ret = show_dialog(ICO_QUEST,_("Really quit X-CD-Roast?"),
		T_YES,T_NO,NULL,0);
	
	if (ret == 0) {
		dolog(1,"Exiting...\n");
		remove_tmp_xcdr_files();
		gtk_main_quit();
	}
}

static void menu_exit_now(GtkWidget *widget, gpointer data) {

	dolog(1,"Exiting...\n");
	gtk_main_quit();

}


/* replacement of gtk_exit with more cleanups */

static void my_do_gtk_exit(gint code, gint textonly) {

#if (defined(__MACH__) && defined(__APPLE__)) 
	show_restart_autodiskmount(textonly);
#endif

	gtk_exit(code);
}


/* set the width of the sidebar - relative to width of toplevel */

void set_sidebar_width() {
gint x, y;
gint val;

	/* check if we are already realized */
	if (GTK_WIDGET(toplevel)->window == NULL) {
		val = 150;
	} else {
		/* set relative to new size */
		gdk_window_get_size(GTK_WIDGET(toplevel)->window,&x,&y);

		/* workaround for a little gtk bug - in some chases 
 		   the current window size is reported wrongly as 200x200 */
		if (x == 200 && y == 200) {
			if (bigfonts == 0) 
				x = XCDR_TOPLEVEL_X0;
			else 
				x = XCDR_TOPLEVEL_X1;
		}
		val = (x*150)/790;
	}

	gtk_widget_set_usize(sidespace,val,0);
}


/* called everytime some window resizes - we check if the toplevel
   changed and set the sidebar to the value we want. This way
   we can dynamically resize and the layout does not change */

static void resize_handler(GtkWidget *widget, gpointer data) {
gint x, y;

	/* check if we are already realized */
	if (GTK_WIDGET(toplevel)->window == NULL) 
		return;

	gdk_window_get_size(GTK_WIDGET(toplevel)->window,&x,&y);

	/* size of toplevel changed? */
	if (x != lastxsize || y != lastysize) {
		/* remember new size */
		lastxsize = x;
		lastysize = y;

		/* set sidebar width to new value */
		set_sidebar_width();
	}
}


/* setup-button handler */

static void menu_setup(GtkWidget *widget, gpointer data) {

	dolog(2,"Entering setup\n");
	create_setup();
}


/* duplicate-button handler */

static void menu_duplicate(GtkWidget *widget, gpointer data) {

	dolog(2,"Entering duplicate cd\n");
	create_duplicate();
}


/* create-button handler */

static void menu_create(GtkWidget *widget, gpointer data) {

	dolog(2,"Entering create cd\n");
	create_create();
}


/* set the pixmap icon */

static void set_wm_icon() {
GtkStyle *style;
GdkBitmap *bitmap;
GdkPixmap *pixmap;
GdkColormap *colormap;
GdkColor wait_color={0,0,0,0};

	style=gtk_widget_get_style(GTK_WIDGET(toplevel));
	pixmap=gdk_pixmap_create_from_xpm_d(GTK_WIDGET(toplevel)->window,
		&bitmap, &style->bg[GTK_STATE_NORMAL], xcdricon_xpm);
	colormap = gtk_widget_get_colormap(GTK_WIDGET(toplevel));
	gdk_color_alloc (colormap, &wait_color);
	gdk_window_set_icon(GTK_WIDGET(toplevel)->window, (GdkWindow *)NULL,  pixmap, bitmap);
}


/* draw the main-menu */

void create_main(gint confignotloaded) {
GtkWidget *side_t;
GtkWidget *side_t_btn1;
GtkWidget *side_t_btn2;
GtkWidget *side_t_btn3;
GtkWidget *side_t_btn4;
GtkWidget *work_t;
GtkWidget *work_t_l1;
GtkWidget *work_t_l2;
GdkPixmap *p;
GdkBitmap *m;
GdkPixbuf *im;
GtkWidget *xcdroast_logo;
/* 
GtkWidget *burnproof_logo; 
GtkWidget *logoalign;
*/
gchar tmp[MAXLINE];


	submenu = 0;
        clear_sidespace();
        clear_workspace();

	side_t = gtk_table_new(10,1, TRUE);
	gtk_table_set_row_spacings(GTK_TABLE(side_t),10);
	gtk_box_pack_start(GTK_BOX(sidespace), side_t,TRUE,TRUE,0);

	side_t_btn1 = gtk_button_new_with_label (_("Setup"));
	if (!curset.isProDVD) {
		side_t_btn2 = gtk_button_new_with_label (_("Duplicate CD"));
		side_t_btn3 = gtk_button_new_with_label (_("Create CD"));
	} else {
		side_t_btn2 = gtk_button_new_with_label (_("Duplicate CD/DVD"));
		side_t_btn3 = gtk_button_new_with_label (_("Create CD/DVD"));
	}
	side_t_btn4 = gtk_button_new_with_label (_("Exit"));

	gtk_signal_connect (GTK_OBJECT (side_t_btn1), "clicked",
		GTK_SIGNAL_FUNC(menu_setup),NULL);
	gtk_signal_connect (GTK_OBJECT (side_t_btn2), "clicked",
		GTK_SIGNAL_FUNC(menu_duplicate),NULL);
	gtk_signal_connect (GTK_OBJECT (side_t_btn3), "clicked",
		GTK_SIGNAL_FUNC(menu_create),NULL);
	gtk_signal_connect (GTK_OBJECT (side_t_btn4), "clicked",
		GTK_SIGNAL_FUNC(menu_exit_now),NULL);

	gtk_table_attach_defaults(GTK_TABLE(side_t), side_t_btn1, 0,1,4,5);
	gtk_widget_show(side_t_btn1);
 	define_tooltip(side_t_btn1,_("Setup your hardware and system defaults"));

	gtk_table_attach_defaults(GTK_TABLE(side_t), side_t_btn2, 0,1,5,6);
	gtk_widget_show(side_t_btn2);
 	define_tooltip(side_t_btn2,_("Make an exact copy of a CD (data and audio)"));

	gtk_table_attach_defaults(GTK_TABLE(side_t), side_t_btn3, 0,1,6,7);
	gtk_widget_show(side_t_btn3);
 	define_tooltip(side_t_btn3,_("Create and arrange your own CD (data and audio)"));

	gtk_table_attach_defaults(GTK_TABLE(side_t), side_t_btn4, 0,1,8,9);
	gtk_widget_show(side_t_btn4);
 	define_tooltip(side_t_btn4,_("Quit X-CD-Roast"));

	gtk_widget_show(side_t);
	gtk_widget_show(sidespace);


	/* draw the workspace */

	work_t = gtk_table_new(10,10, TRUE);
	gtk_box_pack_start(GTK_BOX(workspace), work_t,TRUE,FALSE,0);

        /* load a gif-image and put into a pixmap */
	g_snprintf(tmp,MAXLINE,"%s/%s", sharedir, XCDRLOGO);
#if GTK_MAJOR_VERSION < 2
        im=gdk_pixbuf_new_from_file(tmp);
#else
	im=gdk_pixbuf_new_from_file(tmp,NULL);
#endif
	if (im) {
		gdk_pixbuf_render_pixmap_and_mask(im, &p, &m, 128);
        	xcdroast_logo = gtk_pixmap_new(p,m);
		gdk_pixbuf_unref(im);
	} else {
		xcdroast_logo = gtk_label_new("[LOGO]");
	}
	gtk_table_attach_defaults(GTK_TABLE(work_t), xcdroast_logo, 0,10,0,4);
	gtk_misc_set_alignment(GTK_MISC(xcdroast_logo),0.5f, 0.5f);
	gtk_widget_show(xcdroast_logo);

        /* load a gif-image and put into a pixmap */
/*
	g_snprintf(tmp,MAXLINE,"%s/%s", sharedir, BURNPROOFLOGO);
        im=gdk_pixbuf_new_from_file(tmp);
	if (im) {
		gdk_pixbuf_render_pixmap_and_mask(im, &p, &m, 128);
        	burnproof_logo = gtk_pixmap_new(p,m);
		gdk_pixbuf_unref(im);
	} else {
		burnproof_logo = gtk_label_new("[BURNPROOF]");
	}
	logoalign = gtk_alignment_new(1.0,1.0,0,0);
	gtk_container_add(GTK_CONTAINER(logoalign), burnproof_logo);
	gtk_table_attach_defaults(GTK_TABLE(work_t), logoalign, 0,10,9,10);
	gtk_widget_show(burnproof_logo);
	gtk_widget_show(logoalign);
*/
	g_snprintf(tmp,MAXLINE,_("Version %s"),XCDROAST_VERSION);
	work_t_l1=gtk_label_new(tmp);
	gtk_label_set_justify(GTK_LABEL(work_t_l1),GTK_JUSTIFY_CENTER);
	gtk_table_attach_defaults(GTK_TABLE(work_t), work_t_l1, 0,10,4,5);
	set_font_and_color(work_t_l1,BIGFONT,"red");

	work_t_l2=gtk_label_new(_("(c) 1996-2008 by T. Niederreiter\n\nhttp://www.xcdroast.org"));
	gtk_label_set_justify(GTK_LABEL(work_t_l2),GTK_JUSTIFY_CENTER);
	gtk_table_attach_defaults(GTK_TABLE(work_t), work_t_l2, 0,10,5,6);

	gtk_widget_show(work_t_l1);
	gtk_widget_show(work_t_l2);

	gtk_widget_show(work_t);	
	gtk_widget_show(workspace);

	if (confignotloaded) {
		gtk_widget_set_sensitive(side_t_btn2, FALSE);
		gtk_widget_set_sensitive(side_t_btn3, FALSE);
	}
}


/* signal handler to gracefully exit on ctrl-c */

static void my_signal_exit(gint isignal) {

	g_print("Caught SIGINT, exiting...\n");
	remove_tmp_xcdr_files();
	my_do_gtk_exit(isignal, 1);
}


/* main */

gint main(gint argc, gchar *argv[]) {
GtkWidget *w;
gint confignotloaded, nrm;
#if 0
gchar *keyenv;
#endif
gchar tmp[MAXLINE];
gchar tmp2[MAXLINE];
#if GTK_MAJOR_VERSION < 2
GtkStyle *style;
#else
PangoRectangle ink_rect;
PangoLayout *layout;
#endif
#if (defined(__MACH__) && defined(__APPLE__)) 
gint stat;
#endif

#if ENABLE_NLS
 #if GTK_MAJOR_VERSION < 2
	bindtextdomain (PACKAGE, LOCALEDIR);
	textdomain (PACKAGE);
 #else
	bindtextdomain (PACKAGE, LOCALEDIR);
	bind_textdomain_codeset (PACKAGE, "utf8");
	textdomain (PACKAGE);
 #endif
#endif
	gtk_set_locale();
	gtk_init(&argc,&argv);

#if (defined(__MACH__) && defined(__APPLE__)) 
	/* dont use xshm on darwin -> its broken */
	/* from gdk-private */
	gdk_use_xshm = FALSE;
#endif

	/* get rid of badmatch() errors */
        gdk_rgb_init();
        gtk_widget_set_default_visual(gdk_rgb_get_visual());
        gtk_widget_set_default_colormap(gdk_rgb_get_cmap());

	/* private init for xcdroast */
	confignotloaded = init(argc, argv, &nrm, &altdevscan);

	w = gtk_window_new(GTK_WINDOW_TOPLEVEL);
	/* save this pointer for future reference */
	toplevel = w;

	lastxsize = 0;
	lastysize = 0;

	/* check which font size we are running */
#if GTK_MAJOR_VERSION < 2

	style = gtk_widget_get_style(toplevel);
	if (gdk_char_height(style->font,'|') > 12) {
		/* our font is higher as 12 pixels */
		bigfonts = 1;
	} else {
		bigfonts = 0;
	}
#else

	/* create dummy layout just to measure the current font */
	layout = gtk_widget_create_pango_layout(toplevel, "|");
	pango_layout_get_extents(layout, NULL, &ink_rect);

	if (PANGO_PIXELS(ink_rect.height) > 16) 
		bigfonts = 1;
	else
		bigfonts = 0;
#endif

	gtk_widget_realize(toplevel);
	set_wm_icon();
	set_xcdr_title(w, NULL, -1);

#if (defined(__MACH__) && defined(__APPLE__)) 
	/* on Mac OS X interactively disable the autodiskmount daemon */

	/* use altdevscan variable to disable the daemon handling at all */
	while (1 && altdevscan == 1) {
		stat = create_autodiskmount_handler();

		if (stat == -1) 
			continue;

		if (stat == 1) {
			break;
		} else {
			gtk_exit(1);
		}
	}
#endif

	if (bigfonts == 0) {
		/* size for 75dpi fonts */
		gtk_widget_set_usize(GTK_WIDGET(w),
			XCDR_TOPLEVEL_X0,XCDR_TOPLEVEL_Y0);
	} else {
		/* size for 100dpi fonts */
		gtk_widget_set_usize(GTK_WIDGET(w),
			XCDR_TOPLEVEL_X1,XCDR_TOPLEVEL_Y1);
	}


	gtk_container_border_width(GTK_CONTAINER(w),10);

	gtk_signal_connect (GTK_OBJECT(w), "destroy",
		GTK_SIGNAL_FUNC (gtk_exit), NULL);

	gtk_signal_connect (GTK_OBJECT(w), "delete_event",
		GTK_SIGNAL_FUNC(menu_exit), NULL);

	gtk_signal_connect (GTK_OBJECT(w), "size_request",
		GTK_SIGNAL_FUNC(resize_handler), NULL);


	splitspace = gtk_hpaned_new();
	gtk_container_add(GTK_CONTAINER(w),splitspace);
#if GTK_MAJOR_VERSION < 2
	gtk_paned_handle_size(GTK_PANED(splitspace),0);
#endif
	gtk_paned_gutter_size(GTK_PANED(splitspace),20);

	/* left side */
	sidespace = gtk_vbox_new(FALSE,0);
	gtk_paned_add1(GTK_PANED(splitspace), sidespace);
	set_sidebar_width();

	/* right side */
	workspace = gtk_vbox_new(FALSE,0);
	gtk_paned_add2(GTK_PANED(splitspace), workspace);

        /* check if screen-size is big enough */
	if (check_screensize(bigfonts) && no_versioncheck == 0) { 
		strncpy(tmp2, _("You need at least a screen resolution of\n%dx%d to run X-CD-Roast.\n\nSee the man-page on how to override that requirement.\n\nExiting now..."), MAXLINE);

		if (bigfonts == 0) {
			g_snprintf(tmp,MAXLINE,tmp2, 800, 600);
		} else {
			g_snprintf(tmp,MAXLINE,tmp2, 1024, 768);
		}
		show_dialog(ICO_ERROR,tmp,T_OK,NULL,NULL,0);
		my_do_gtk_exit(1, 0);
	}

	if (confignotloaded) {
#if !(defined(__MACH__) && defined(__APPLE__)) && (USE_NONROOTMODE == 1)
		if (isroot()) {
			/* scan for devices */
			create_device_scanning(altdevscan, 0, 1, NULL);

			/* first start for user root - ask him about nrm */
			create_nonroot_configurator(nrm,0);
			/* now show that no configfile exists yet */
			show_dialog(ICO_INFO, _("No root configuration file found!\nPlease enter Setup and don't forget to add users\nwho may also use X-CD-Roast."), T_OK, NULL, NULL, 0);
		} else {
#endif
			/* scan for devices */
			create_device_scanning(altdevscan, 0, 1, NULL);
	
			show_dialog(ICO_INFO, _("No configuration file found!\nPlease enter Setup."), T_OK, NULL, NULL, 0);

#if !(defined(__MACH__) && defined(__APPLE__)) && (USE_NONROOTMODE == 1)
		}
#endif
	} else {
		/* check if the configfile is for current version of xcdroast */
		if (strcmp(XCDROAST_VERSION, xcdroast_version_loaded) != 0) {

			/* first start of new version for user root - ask him about nrm */
#if !(defined(__MACH__) && defined(__APPLE__)) && (USE_NONROOTMODE == 1)
			if (isroot()) {
				create_nonroot_configurator(nrm,0);
			}
#endif
			/* scan for devices */
			create_device_scanning(altdevscan, 0, 1, NULL);

			g_snprintf(tmp,MAXLINE,_("Configuration file for incorrect version %s found!\nPlease enter Setup and create an updated configuration."), xcdroast_version_loaded);
			show_dialog(ICO_INFO, tmp, T_OK, NULL, NULL, 0);
			strcpy(xcdroast_version_loaded,"");
			confignotloaded = 1;
			if (isroot()) {
				/* if config is from old version, we can
				   assume that it still got the wrong perms */
				/* fix them */
				chmod(rootconfig, 0644);
			}
		}

		/* now check if our config is matching the current hardware */
#if 0
		if (verify_loaded_config() == 1) {
			/* scsi-bus changed */
			show_dialog(ICO_WARN, _("Something on the SCSI-Bus has changed. Please check\nyour writer and reader configuration in Setup."), T_OK, NULL, NULL, 0);
			strcpy(xcdroast_version_loaded,"");
			confignotloaded = 1;
		}
#endif
		if (verify_loaded_config2() == 1) {
			/* image-dirs changed */
			show_dialog(ICO_WARN, _("The image-directories do not match the current system.\nPlease check their configuration in Setup."), T_OK, NULL, NULL, 0);
			strcpy(xcdroast_version_loaded,"");
			confignotloaded = 1;
		}

	}

	create_main(confignotloaded);

	gtk_widget_show(splitspace);
	gtk_widget_show(w);

	/* set new size from config? (only works after window is shown) */
	if (setupdata.option_savepos && 
	     setupdata.mainwindow.width != -1 && 
	     setupdata.mainwindow.height != -1 &&
	     setupdata.mainwindow.x != -1 &&
	     setupdata.mainwindow.y != -1) {

		gdk_window_move_resize(GTK_WIDGET(w)->window,
			setupdata.mainwindow.x,
			setupdata.mainwindow.y,
			setupdata.mainwindow.width,
			setupdata.mainwindow.height);
	}



	/* let the screen update now */
	while (gtk_events_pending())
		gtk_main_iteration();

	/* show disclaimer (old disclaimer nr 288) */
/*
	if (show_dialog(ICO_WARN, _("DISCLAIMER: This is just an unfinished version of the new X-CD-Roast 0.98.\nBut it is already more stable and offers more features as the current\nrelease 0.96ex. Please visit http://www.xcdroast.org for updates and\n more detailed information about this alpha-version.\n\nBut because there are still some of the important features missing,\nI do ask - do you really want to continue?"), T_YES, T_NO, NULL, 1) == 1) {
		my_do_gtk_exit(1, 0);
	}
*/

        /* warn about non-existing LFS support in dvd mode */
        if ((curset.isProDVD & 1) && sizeof(off_t) != 8) {
                show_dialog(ICO_WARN, _("Warning: Your system is not able to create files larger\nthan 2 GB. Writing DVDs will therefore not possible."), T_OK, NULL, NULL, 0);
        }

        /* if we are in DVD mode, check if the security-key is set */
#if 0
        if (curset.isProDVD == 1) {
                keyenv = getenv("CDR_SECURITY");
                if (keyenv == NULL) {
			show_dialog(ICO_WARN, _("Warning: You have not entered a cdrecord-ProDVD key in setup.\nPlease see the FAQ on how to obtain your free key.\nYou also have to renew the key every few months because it got an\nexpire date. You will not be able to properly write DVDs without it."), T_OK, NULL, NULL, 0); 
                }

	}
#endif

	dolog(1,"Starting X-CD-Roast\n");

	/* install a signal handler to catch CTRL-C */
	signal (SIGINT, my_signal_exit) ;

	gtk_main();
	
	my_do_gtk_exit(0, 0);
	return 0;
}
