void on_tray_icon_activate(GtkStatusIcon* icon, gpointer user_data)
{
	if(GTK_WIDGET_VISIBLE(mainwin))
	{
		gtk_widget_hide(mainwin);
	}
	else
	{
		gtk_widget_show(mainwin);
	}
}
gboolean on_exit_program(GtkWidget *widget, gpointer user_data)
{
	if(states.stoped)
	{
		save_config();
		gtk_main_quit();
		return FALSE;
	}
	else
	{
		popup("An operation is still in progress.");
		return TRUE;
	}
}
void on_convert_btn_clicked(GtkWidget *widget, gpointer user_data)
{
	GTimer* timer=g_timer_new();
	
	char* v_fps = gtk_combo_box_get_active_text(GTK_COMBO_BOX(v_fps_combo));
	char* v_aspect = gtk_combo_box_get_active_text(GTK_COMBO_BOX(v_aspect_combo));
	char* a_sr = gtk_combo_box_get_active_text(GTK_COMBO_BOX(a_sr_combo));
	char* a_channel = gtk_combo_box_get_active_text(GTK_COMBO_BOX(a_channel_combo));
	
	unsigned int video_bitrate = gtk_spin_button_get_value_as_int( GTK_SPIN_BUTTON(v_bitrate_spin) ) * 1000;
	char v_bitrate[ count_int(video_bitrate) + 1 ];
	sprintf(v_bitrate,"%d",video_bitrate);
		
	unsigned int audio_bitrate = gtk_spin_button_get_value_as_int( GTK_SPIN_BUTTON(a_bitrate_spin) ) * 1000;
	char a_bitrate[ count_int(audio_bitrate) + 1 ];
	sprintf(a_bitrate,"%d",audio_bitrate);
	
	unsigned short video_width = gtk_spin_button_get_value_as_int( GTK_SPIN_BUTTON(v_width_spin) );
	char v_width[ count_int(video_width) + 1 ];
	sprintf(v_width,"%d",video_width);
	
	unsigned short video_height = gtk_spin_button_get_value_as_int( GTK_SPIN_BUTTON(v_height_spin) );
	char v_height[ count_int(video_height) + 1 ];
	sprintf(v_height,"%d",video_height);
	
	char width_x_height[ strlen(v_width) + 1 + strlen(v_height) + 1 ];
	strcpy(width_x_height,v_width);
	strcat(width_x_height,"x");
	strcat(width_x_height,v_height);
	
	
	unsigned short arr_size=18;
	if(!gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(v_width_height_check)))
	{
		arr_size+=2;
	}
	if(gtk_combo_box_get_active(GTK_COMBO_BOX(v_fps_combo))!=0)
	{
		arr_size+=2;
	}
	if(gtk_combo_box_get_active(GTK_COMBO_BOX(a_sr_combo))!=0)
	{
		arr_size+=2;
	}
	if(gtk_combo_box_get_active(GTK_COMBO_BOX(a_channel_combo))!=0)
	{
		arr_size+=2;
	}
	
	unsigned short arr_index=0;
	char * args[arr_size];
	
	args[arr_index]=C_FFMPEG_PATH;
		arr_index++;
	args[arr_index]="-i";
		arr_index++;
	//args[2]="";//input file name
		arr_index++;
	args[arr_index]="-f";
		arr_index++;
	args[arr_index]=vformats[gtk_combo_box_get_active(GTK_COMBO_BOX(v_format_combo))].format_name;
		arr_index++;
	if(gtk_combo_box_get_active(GTK_COMBO_BOX(v_fps_combo))!=0)
	{
		args[arr_index] = "-r";
			arr_index++;
		args[arr_index] = v_fps;
			arr_index++;
	}
	args[arr_index]="-vcodec";
		arr_index++;
	args[arr_index]=vcodecs[gtk_combo_box_get_active(GTK_COMBO_BOX(v_codec_combo))].codec_name;
		arr_index++;
	if(!gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(v_width_height_check)))
	{
		args[arr_index]="-s";
			arr_index++;
		args[arr_index]=width_x_height;
			arr_index++;
	}
	args[arr_index]="-aspect";
		arr_index++;
	args[arr_index]=v_aspect;
		arr_index++;
	args[arr_index]="-vb";
		arr_index++;
	args[arr_index]=v_bitrate;
		arr_index++;
	args[arr_index]="-acodec";
		arr_index++;
	args[arr_index]=acodecs[gtk_combo_box_get_active(GTK_COMBO_BOX(a_codec_combo))].codec_name;
		arr_index++;
	if(gtk_combo_box_get_active(GTK_COMBO_BOX(a_sr_combo))!=0)
	{
		args[arr_index]="-ar";
			arr_index++;
		args[arr_index]=a_sr;
			arr_index++;
	}
	args[arr_index]="-ab";
		arr_index++;
	args[arr_index]=a_bitrate;
		arr_index++;
	if(gtk_combo_box_get_active(GTK_COMBO_BOX(a_channel_combo))!=0)
	{
		args[arr_index]="-ac";
			arr_index++;
		args[arr_index]=a_channel;
			arr_index++;
	}
	args[arr_index]="-y";
		arr_index++;
	//args[arr_index-1]="";//output file name
		arr_index++;
	args[arr_index]=NULL;
	
	GtkTreeSelection* selection=gtk_tree_view_get_selection(GTK_TREE_VIEW(list));
	
	GtkTreeModel* model=gtk_tree_view_get_model(GTK_TREE_VIEW(list));
	GtkTreeIter iter;
	gboolean valid = gtk_tree_model_get_iter_first(model,&iter);
	
	if(valid)
	{
		states.stoped=0;
		enable_disable_widgets();
	}
	char * envp[]={"LD_LIBRARY_PATH=libs",NULL};
	while(valid && !states.stoped)
	{
		GtkTreePath* t_path=gtk_tree_model_get_path(GTK_TREE_MODEL(model),&iter);
		if(t_path)
		{
			gtk_tree_view_scroll_to_cell(GTK_TREE_VIEW(list), t_path, NULL, FALSE, 0.0, 0.0 );
			gtk_tree_path_free(t_path);
		}
		gtk_tree_selection_select_iter(selection,&iter);
		
		gboolean done = FALSE;//if the job is done
		
		gtk_tree_model_get(model, &iter,COLUMN_PATH, &args[2],-1);
		
		char* out_folder = get_out_path();
		char* base_name = get_base_name(args[2]);
		
		args[arr_index-1]=calloc( strlen(out_folder) + 1 + strlen(base_name) + 5 + 1,sizeof(char) );
		strcpy(args[arr_index-1],out_folder);
		strcat(args[arr_index-1],"/");
		strcat(args[arr_index-1],base_name);
		strcat(args[arr_index-1],vformats[gtk_combo_box_get_active(GTK_COMBO_BOX(v_format_combo))].extension);
		
		print_str_arr(args);//printing command for debug
		
		gint fd_err;//file descriptor
		GError *err = NULL;
		
		g_spawn_async_with_pipes(NULL,args,envp,G_SPAWN_DO_NOT_REAP_CHILD | G_SPAWN_SEARCH_PATH,NULL,NULL,&states.pid,NULL,NULL,&fd_err,&err);
		
		if(err!=NULL)
		{
			fprintf(stderr,"%s\n",err->message);
			g_error_free(err);
		}
		
		if(states.paused)
		{
			setpriority(PRIO_PROCESS,states.pid,PRIO_MAX);
		}
		
		GIOChannel *io_err=g_io_channel_unix_new(fd_err);//channel for encoder's output
		
		GString *errstr = g_string_new("");//string for encoders's error
		
		gboolean show_stat=FALSE;//we are not ready for stats
		
		g_timer_start(timer);
		
		unsigned short iter_number = 0;
		
		while( waitpid(states.pid,NULL,WNOHANG)==0 && !states.stoped)
		{		
			usleep(1000);
			
			if(!show_stat)
			{
				g_io_channel_read_line_string(io_err,errstr,NULL,NULL);
				g_print(errstr->str);
				
				if(sscanf(errstr->str," Duration: %d:%d:%g",&stats.total_hours,&stats.total_minutes,&stats.total_seconds)==3)
				{
					show_stat=TRUE;
					stats.total_time=stats.total_hours*3600+stats.total_minutes*60+stats.total_seconds;
				}
			}
			else
			{
				if(done)
				{
					iter_number++;
					if(iter_number==500)
					{
						iter_number = 0;//reset
						
						g_io_channel_read_line_string(io_err,errstr,NULL,NULL);
						g_print(errstr->str);
						
						done = proceed_stat(errstr->str,&iter,timer);
					}
				}
				else
				{
					g_io_channel_read_line_string(io_err,errstr,NULL,NULL);
					g_print(errstr->str);
					
					done = proceed_stat(errstr->str,&iter,timer);
				}
			}
			
			while(gtk_events_pending()) 
			{
				gtk_main_iteration();
			}
		}
		
		if(states.stoped && waitpid(states.pid,NULL,WNOHANG)!=0)
		{
			GString *command=g_string_new("kill ");
			g_string_append_printf(command,"%i",states.pid);//result kill pid
			g_spawn_command_line_sync(command->str,NULL,NULL,NULL,NULL);//waiting for encoder to be killed
			g_string_free(command, TRUE);
			states.pid=0;
		}
		
		g_io_channel_shutdown(io_err,TRUE,&err);
		g_string_free(errstr, TRUE);
		
		free(out_folder);
		free(base_name);
		
		free(args[2]);
		free(args[arr_index-1]);
		
		if(done)
		{
			gtk_list_store_set(store,&iter,COLUMN_STATUS,"Done",-1);
		}
		else
		{
			gtk_list_store_set(store,&iter,COLUMN_STATUS,"Fail",-1);
		}
		
		valid = gtk_tree_model_iter_next(model, &iter);
	}
	
	free(v_fps);
	free(v_aspect);
	free(a_sr);
	free(a_channel);
	
	g_timer_destroy(timer);
	
	states.pid=0;
	states.stoped=1;
	enable_disable_widgets();
	gtk_progress_bar_set_text(GTK_PROGRESS_BAR(progress_bar),"");
	gtk_progress_bar_set_fraction(GTK_PROGRESS_BAR(progress_bar),(gdouble)0);
	gtk_status_icon_set_tooltip(trayicon, "Transcoder");
	
	printf("\nEnd\n");
}
void on_stop_btn_clicked(GtkWidget *widget, gpointer user_data)
{
	states.stoped=1;
}
void on_pause_continue_btn_clicked(GtkWidget *widget, gpointer user_data)
{
	if(states.pid)
	{
		if(!states.paused)
		{
			gtk_button_set_label(GTK_BUTTON(pause_continue),"Faster");
			gtk_widget_set_tooltip_text(GTK_WIDGET(pause_continue),"Increase resource usage");
			states.paused=1;
			setpriority(PRIO_PROCESS,states.pid,PRIO_MAX);
		}
		else
		{
			gtk_button_set_label(GTK_BUTTON(pause_continue),"Slower");
			gtk_widget_set_tooltip_text(GTK_WIDGET(pause_continue),"Decrease resource usage");
			states.paused=0;
			setpriority(PRIO_PROCESS,states.pid,PRIO_USER);
		}
	}
}
void on_list_drag_data_received(GtkWidget *widget,GdkDragContext *drag_ctx,gint x,gint y,GtkSelectionData  *data,guint32 info,guint32 time)
{
	char** uris;
	g_signal_stop_emission_by_name(widget, "drag-data-received");
	if(uris = gtk_selection_data_get_uris(data))
	{
		char** uri;
		for(uri = uris; *uri; ++uri)
		{
			char* fn = g_filename_from_uri(*uri, NULL, NULL);
			add_to_list(list,fn);
			free(fn);
		}
		g_strfreev(uris);
	}
}
void on_item_del(GtkWidget *widget, gpointer user_data)
{
	if(states.stoped)
	{
		GtkTreeIter iter;
		GtkTreeModel *model;
		GtkTreeSelection* selection=gtk_tree_view_get_selection(GTK_TREE_VIEW(list));
		if(gtk_tree_selection_get_selected(GTK_TREE_SELECTION(selection),&model, &iter))
		{
			if(gtk_tree_model_iter_next(model,&iter))
			{
				gtk_tree_selection_get_selected(GTK_TREE_SELECTION(selection),&model, &iter);
				gtk_list_store_remove(GTK_LIST_STORE(store),&iter);
				gtk_tree_selection_select_iter(selection,&iter);
			}
			else
			{
				gtk_tree_selection_get_selected(GTK_TREE_SELECTION(selection),&model, &iter);
				gtk_list_store_remove(GTK_LIST_STORE(store),&iter);
			}
		}
	}
}
void on_list_clear(GtkWidget *widget, gpointer user_data)
{
	if(states.stoped)
	{
		gtk_list_store_clear(GTK_LIST_STORE(store));
	}
}
void on_about(GtkWidget* widget, gpointer user_data)
{
	const gchar* authors[] = {"Arman Poghosyan (chelovek84) <chelovek84@yahoo.com>",NULL};
	const gchar* artists[] = {"Levon Ohanyan (Leo) <ohanyanlevon@gmail.com>",NULL};
	GtkWidget* about = gtk_about_dialog_new();
	gtk_about_dialog_set_name(GTK_ABOUT_DIALOG(about),"Transcoder");
	gtk_about_dialog_set_version(GTK_ABOUT_DIALOG(about),C_VERSION);
	gtk_about_dialog_set_authors(GTK_ABOUT_DIALOG(about),authors);
	gtk_about_dialog_set_artists(GTK_ABOUT_DIALOG(about),artists);
	gtk_about_dialog_set_license(GTK_ABOUT_DIALOG(about)," This program is free software; you can redistribute it and/or \n modify it under the terms of the GNU General Public License \n as published by the Free Software Foundation; either version 2 \n of the License, or any later version. \n This program is distributed in the hope that it will be useful, \n but WITHOUT ANY WARRANTY; without even the implied warranty of \n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the \n GNU General Public License for more details. \n You should have received a copy of the GNU General Public License \n along with this program; if not, write to the Free Software \n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.");
	gtk_window_set_transient_for(GTK_WINDOW(about),GTK_WINDOW(mainwin));
	gtk_dialog_run(GTK_DIALOG(about));
	gtk_widget_destroy(about);
}

void on_width_x_height_box(GtkWidget* checkbox, gpointer user_data)
{
	if(gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(checkbox)))
	{
		gtk_widget_set_sensitive(v_width_spin,FALSE);
		gtk_widget_set_sensitive(v_height_spin,FALSE);
	}
	else
	{
		gtk_widget_set_sensitive(v_width_spin,TRUE);
		gtk_widget_set_sensitive(v_height_spin,TRUE);
	}
}
