/*
 *	main.c
 *	13.3.99 tn
 *
 *
 *  Copyright (C) 1995, 1996, 1997 Free Software Foundation, Inc.
 *
 *  This file is part of xcdroast.
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

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

#include "largefile.h"

#include <locale.h>
#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/gdkprivate.h>
#include "xcdrdata.h"
#include "xcdroast.h"
#include "main.h"

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

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

img_logo_t img;

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) {

	gtk_exit(code);
}


/*
 * paint a logo image, centered 
 */
void logo_do_draw(cairo_t *cr, cairo_surface_t *img, GtkWidget *widget) {
gint width, height;
gint imgwidth, imgheight;

	/* target drawing area size */
        height = gdk_window_get_height(GTK_WIDGET(widget)->window);
        width = gdk_window_get_width(GTK_WIDGET(widget)->window);

	/* size of our image */
        imgwidth = cairo_image_surface_get_width(img);
        imgheight = cairo_image_surface_get_height(img);

	/* center image in drawing area */
	cairo_set_source_surface(cr, img, width/2 - imgwidth/2,
		height/2 - imgheight/2);
	cairo_paint(cr);
}


/*
 * trigger the drawing of a logo 
 */
gboolean logo_on_expose(GtkWidget *widget, GdkEventExpose *event, 
	cairo_surface_t *img) {
cairo_t *cr;

	cr = gdk_cairo_create(gtk_widget_get_window(widget));
	logo_do_draw(cr, img, widget);

	return FALSE;
}


/*
 * return logo widget, or textlabel if image is not available
*/
GtkWidget *display_logo(cairo_surface_t *logo, gchar *logo_text) {
GtkWidget *xcdroast_logo;
gint xsize, ysize;

       if (cairo_surface_status(logo) == CAIRO_STATUS_SUCCESS) {
                xcdroast_logo = gtk_drawing_area_new();
		xsize = cairo_image_surface_get_width(logo);
        	ysize = cairo_image_surface_get_height(logo);	
		gtk_widget_set_size_request(xcdroast_logo, xsize, ysize);

                g_signal_connect(G_OBJECT(xcdroast_logo), "expose-event",
                        G_CALLBACK(logo_on_expose), logo);
        } else {
                xcdroast_logo = gtk_label_new(logo_text);
        }
	return xcdroast_logo;
}

/*
 * 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 */
		x = gdk_window_get_width(GTK_WIDGET(toplevel)->window);
		y = gdk_window_get_height(GTK_WIDGET(toplevel)->window);

		/*
		 * 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_size_request(sidespace, val, -1);
}


/*
 * 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;

	x = gdk_window_get_width(GTK_WIDGET(toplevel)->window);
	y = gdk_window_get_height(GTK_WIDGET(toplevel)->window);

	/* 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();
	}
}


/*
 * about-button handler
 */
static void about_dialog(GtkWidget *widget, gpointer data) {

	dolog(2,"Entering About X-CD-Roast\n");
	show_about_dialog();
}


/*
 * 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 Disc\n");
	create_duplicate();
}


/*
 * create-button handler
 */
static void menu_create(GtkWidget *widget, gpointer data) {

	dolog(2,"Entering Create Disc\n");
	create_create();
}


/*
 * set the desktop icon
 */
void set_wm_icon() {
GError *err = NULL;
GdkPixbuf *icon;
gchar tmp[MAXLINE];

	g_snprintf(tmp, MAXLINE, "%s/%s", sharedir, XCDRLOGO_ICON);
        icon = gdk_pixbuf_new_from_file(tmp, &err);
        if (!icon)
	{
		fprintf(stderr, "Error: Failed loading desktop icon: %s\n", err->message);
		return;
	}

	gtk_window_set_icon(GTK_WINDOW(toplevel), icon);
	gtk_window_set_default_icon(icon);
}


/*
 * draw the main-menu
 */
void create_main(gint confignotloaded) {
GtkWidget *side_t;
GtkWidget *side_t_btn0;
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;
GtkWidget *xcdroast_logo;
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_btn0 = gtk_button_new_with_label (_("About"));
	side_t_btn1 = gtk_button_new_with_label (_("Setup"));
	if (!curset.isProDVD) {
		side_t_btn2 = gtk_button_new_with_label (_("Duplicate Disc"));
		side_t_btn3 = gtk_button_new_with_label (_("Create Disc"));
	} 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_btn0), "clicked",
		GTK_SIGNAL_FUNC(about_dialog), NULL);
	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_btn0, 0,1,3,4);
	gtk_widget_show(side_t_btn0);
	define_tooltip(side_t_btn0,_("Shows information about X-CD-Roast"));

	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 Disc (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 Disc (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);

        /* display logo */
	xcdroast_logo = display_logo(img.xcdrlogo, "[LOGO]");
	gtk_table_attach_defaults(GTK_TABLE(work_t), xcdroast_logo, 0,10,0,4);
	gtk_widget_show(xcdroast_logo);

	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,PANGO_BIG,"red");

	work_t_l2=gtk_label_new(_("(c) 1996-2018 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;
gchar tmp[MAXLINE];
gchar tmp2[MAXLINE];
PangoRectangle ink_rect;
PangoLayout *layout;
gint ret;

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

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

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

	lastxsize = 0;
	lastysize = 0;

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

	dodebug(10, "Detected Fontsize: %d\n", PANGO_PIXELS(ink_rect.height));
	if (PANGO_PIXELS(ink_rect.height) > 16) 
		bigfonts = 1;
	else
		bigfonts = 0;

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

	if (bigfonts == 0) {
		/* size for 75dpi fonts */
		gtk_widget_set_size_request(GTK_WIDGET(w),
			XCDR_TOPLEVEL_X0, XCDR_TOPLEVEL_Y0);
	} else {
		/* size for 100dpi fonts */
		gtk_widget_set_size_request(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);
	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
	 * (see xcdroast.h & init.c)
	 */
	if (check_screensize(bigfonts) && no_versioncheck == 0) { 
		strncpy(tmp2, _("We recommend a screen resolution of at least\n%d x %d to run X-CD-Roast.\n\n"), MAXLINE);

		if (bigfonts == 0) {
			g_snprintf(tmp,MAXLINE,tmp2, 800, 600);
		} else {
			g_snprintf(tmp,MAXLINE,tmp2, 1024, 720);
		}
 		ret = show_dialog(ICO_WARN, tmp, T_ANYWAY, T_EXIT, NULL, 1);
                if (ret == 1)
			my_do_gtk_exit(1, 0);

	}

	if (confignotloaded) {
#if (USER_HOST_MODE == 1)
		if (isroot()) {
			/* scan for devices */
			create_device_scanning(altdevscan, 0, 1, NULL);

			/* first start for user root - 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 (USER_HOST_MODE == 1)
		}
#endif
	} else {
		/* check if the configfile is for current version of xcdroast */
		if (strcmp(XCDROAST_VERSION, xcdroast_version_loaded) != 0) {

			/* 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);
			}
		}

		if (verify_loaded_config() == 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();


        /* 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 GiB. Writing DVDs will therefore not be possible."), T_OK, NULL, NULL, 0);
        }
	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;
}
