/* Y o u r   D e s c r i p t i o n                       */
/*                            AppBuilder Photon Code Lib */
/*                                         Version 0.98B */

/* Standard headers */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <termios.h>

/* Toolkit headers */
#include <Ph.h>
#include <Pt.h>
#include <Ap.h>

/* Local headers */
#include "phterm.h"
#include "abimport.h"
#include "proto.h"

static char newproto;
static enum { OPEN, APPLY, CANCEL } dlgstate;

int ask_for_stty( int proto, PtWidget_t *wgt, PtCallbackInfo_t *cb ) {
	int modal, blocked;
	PtWidget_t *config;
	newproto = proto;

	dlgstate = OPEN;
	ApCreateModule( ABM_protochg, wgt, cb );

	blocked = getres( config = ABW_config, Pt_ARG_FLAGS );
	setres_len( ABW_config, Pt_ARG_FLAGS, Pt_BLOCKED, Pt_BLOCKED );
	modal = PtModalStart();
	while ( dlgstate == OPEN )
		PtProcessEvent();
	PtModalEnd( modal );
	setres_len( ABW_config, Pt_ARG_FLAGS, blocked, Pt_BLOCKED );

	return dlgstate == CANCEL ? -1 : 0;
	}



int
fillprotodlg( PtWidget_t *link_instance, ApInfo_t *apinfo, PtCallbackInfo_t *cbinfo )
	{
	PtWidget_t *const tty = ABW_tty;
	pid_t const shell = getres( tty, Pt_ARG_TTY_PID );
	char buf[ 20 ];
	const int shell_died = shell == 0 && shargs != NULL;

	strcat( strcpy( buf, "TERM=" ), PtTerminalName( newproto ) );
	setstring( ABW_stty_label, buf );

	if ( devopt != 'R' )
		but_able( 0, ABW_but_sttyYes );
	else
		if ( shell_died )
			but_able( 0, ABW_but_sttyWrite );

	if ( ! shell_died )
		PtContainerGiveFocus( ABW_but_sttyWrite, cbinfo->event );

	/* eliminate 'unreferenced' warnings */
	link_instance = link_instance, apinfo = apinfo, cbinfo = cbinfo;
	return Pt_CONTINUE;
	}

int
do_stty( PtWidget_t *widget, ApInfo_t *apinfo, PtCallbackInfo_t *cbinfo )
	{
	int fd = getres( ABW_tty, Pt_ARG_TTY_FD );
	struct termios buf;
	if ( tcgetattr( fd, &buf ) == 0 ) {
		PtTerminalGetKeys( newproto, &buf );
		tcsetattr( fd, TCSADRAIN, &buf );
		}


	dlgstate = APPLY;
	/* eliminate 'unreferenced' warnings */
	widget = widget, apinfo = apinfo, cbinfo = cbinfo;
	return Pt_CONTINUE;
	}

int
dont_stty( PtWidget_t *widget, ApInfo_t *apinfo, PtCallbackInfo_t *cbinfo )
	{
	dlgstate = APPLY;
	/* eliminate 'unreferenced' warnings */
	widget = widget, apinfo = apinfo, cbinfo = cbinfo;
	return Pt_CONTINUE;
	}

int
do_write_stty( PtWidget_t *widget, ApInfo_t *apinfo, PtCallbackInfo_t *cbinfo )
	{
	char buf[ 50 ];
	write( getres( ABW_tty, Pt_ARG_TTY_MFD ), buf,
		sprintf( buf, "%s\rstty load\r", getstring( ABW_stty_label ) )
		);

	dlgstate = APPLY;
	/* eliminate 'unreferenced' warnings */
	widget = widget, apinfo = apinfo, cbinfo = cbinfo;
	return Pt_CONTINUE;
	}

int
proto_done( PtWidget_t *widget, ApInfo_t *apinfo, PtCallbackInfo_t *cbinfo )
	{
	if ( dlgstate == OPEN )
		dlgstate = CANCEL;

	/* eliminate 'unreferenced' warnings */
	widget = widget, apinfo = apinfo, cbinfo = cbinfo;
	return Pt_CONTINUE;
	}


