/******************************************************************************
Copyright (C) 2005 Matteo Lucarelli

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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
******************************************************************************/

#include "UIshowexec.h"

UIshowexec::UIshowexec(int dimx,int dimy,const char* command,const char* label,unsigned char font,unsigned char fontsize)
{
	m_pid=-1;

	// build and set window
	m_wMain = new Fl_Double_Window (dimx,dimy);
	if (label) m_wMain->label(label);
	m_wMain->callback(cb_wMain_link, this);
	m_buffer = new Fl_Text_Buffer();
	m_display = new Fl_Text_Display( 5,5,(dimx-10),(dimy-10) );
	m_display->buffer(m_buffer);
	m_display->textfont(font);
	m_display->textsize(fontsize);
 	m_wMain->end();
 	
	// start child command
	pipe(m_pipe);
	m_pid=fork();
	if (m_pid==0){
		close(m_pipe[0]);
		dup2(m_pipe[1], 2);
		close(m_pipe[1]);
		char cmd[1024];
		snprintf(cmd,1024,"(%s) 1>&2",command);
		execlp("/bin/sh", "sh", "-c", cmd, 0);
	}
	close(m_pipe[1]);
	Fl::add_fd(m_pipe[0], cb_Data_link, this);
	
	m_wMain->resizable(m_wMain);
	m_wMain->show();
}

UIshowexec::~UIshowexec()
{
	delete m_display;
	delete m_buffer;
	delete m_wMain;
}

void UIshowexec::cb_wMain()
{
	if ( m_pid != -1 ) kill(m_pid, 9);
	m_wMain->hide();
}

void UIshowexec::cb_Data(int fd) 
{
	char s[4096];
	int bytes = read(fd, s, 4096-1);
	
	if ( bytes == 0 ) {    // EOF
		waitpid(m_pid,NULL,WNOHANG);
		close(fd);
		Fl::remove_fd(fd);
		m_pid = -1;
	} else {             // DATA
		s[bytes] = 0;
		m_buffer->append(s);
	}
}