/* Copyright (c) 1990 by Sun Microsystems, Inc. */
#ident	"@(#)gaintool_xv.c	1.2	90/09/20 SMI"

#ifndef lint
static  char sccsid[] = "@(#)gaintool_xv.c 1.1 90/09/21 Copyr 1989 Sun Micro";
#endif

/*
 * Copyright (c) 1989 by Sun Microsystems, Inc.
 */



#include <stdio.h>
#include <fcntl.h>
#include <strings.h>
#include <sys/ioctl.h>
#include <sys/file.h>
#include <stropts.h>

#include <sun/audioio.h>

#include <xview/xview.h>
#include <xview/panel.h>
#include <xview/canvas.h>
#include <xview/seln.h>

/* 
 * Generated by Guide
 */
#include "gaintool_ui.h"


#define	AUDIO_IODEV	"/dev/audio"
#define	AUDIO_CTLDEV	"/dev/audioctl"

#define	MAX_GAIN	100

#define	FPRINTF (void) fprintf
#define	SPRINTF (void) sprintf
#define	STRCPY  (void) strcpy

/* 
 * More Guide Stuff...
 *	This was moved up from below.
 */
/*
 * Instance XV_KEY_DATA key.  An instance is a set of related
 * user interface objects.  A pointer to an object's instance
 * is stored under this key in every object.  This must be a
 * global variable.
 */
Attr_attribute	INSTANCE;

gaintool_BaseFrame_objects	*gaintool_BaseFrame;
gaintool_PropSheet_objects	*gaintool_PropSheet;

/*
 *	Guide Interface to window system handles
 */
#define		Base_frame		gaintool_BaseFrame->BaseFrame
#define		Main_panel		gaintool_BaseFrame->GainPanel
#define		play_volume_item	gaintool_BaseFrame->PlaySlider
#define		record_volume_item	gaintool_BaseFrame->RecordSlider
#define		monitor_volume_item	gaintool_BaseFrame->MonitorSlider
#define		speaker_item		gaintool_BaseFrame->OutputSwitch
#define		pause_item		gaintool_BaseFrame->Pause_button


#define		Status_frame		gaintool_PropSheet->PropSheet
#define		play_open_item		gaintool_PropSheet->Popen_flag
#define		play_active_item	gaintool_PropSheet->Pactive_flag
#define		play_pause_item		gaintool_PropSheet->Ppaused_flag
#define		play_error_item		gaintool_PropSheet->Puf_flag
#define		play_waiting_item	gaintool_PropSheet->Pow_flag
#define		play_eof_item		gaintool_PropSheet->Peof_value
#define		play_samples_item	gaintool_PropSheet->Psam_value
#define		play_sample_rate_item	gaintool_PropSheet->Psamr_value
#define		play_channels_item	gaintool_PropSheet->Pchan_value
#define		play_precision_item	gaintool_PropSheet->Pprec_value
#define		play_encoding_item	gaintool_PropSheet->Pencode_value
#define		record_open_item	gaintool_PropSheet->Ropen_flag
#define		record_active_item	gaintool_PropSheet->Ractive_flag
#define		record_pause_item	gaintool_PropSheet->Rpaused_flag
#define		record_error_item	gaintool_PropSheet->Rof_flag
#define		record_waiting_item	gaintool_PropSheet->Row_flag
#define		record_samples_item	gaintool_PropSheet->Rsam_value
#define		record_sample_rate_item	gaintool_PropSheet->Rsamr_value
#define		record_channels_item	gaintool_PropSheet->Rchan_value
#define		record_precision_item	gaintool_PropSheet->Rprec_value
#define		record_encoding_item	gaintool_PropSheet->Rencode_value


int		Show_status;

char		*Pause_button = "Pause Play";
char		*Resume_button = "Resume Play";

Notify_value	sigpoll_handler();
Notify_value	timer_handler();
void		show_status();

int		Audio_pausefd = -1;
int		Audio_pauseflag = 0;
int		Audio_fd;
audio_info_t	Audio_info;
audio_info_t	Audio_new;

gaintool_init()
{
	/* Set up to catch SIGPOLL */
	(void) notify_set_signal_func(Base_frame,
	    (Notify_func)sigpoll_handler, SIGPOLL, NOTIFY_SYNC);

	audio_open();

	update_panels();
}


/*
 * Entered any time there is a change of state of the audio device.
 * However, the Notifier schedules this routine synchronously, so
 * we don't have to worry about stomping on gloabal data structures.
 */
/*ARGSUSED*/
Notify_value
sigpoll_handler(client, sig, when)
	Notify_client		client;
	int			sig;
	Notify_signal_mode	when;
{
	update_panels();
	return (NOTIFY_DONE);
}

/*
 * Get the latest device state and update the panels appropriately.
 */
update_panels()
{
	char	buf[128];

	/* Only change settings that changed, to avoid flashing */
#define	NEWVAL(X, Y)	{						\
			if (Audio_new.X != Audio_info.X)		\
				(void) xv_set(Y, PANEL_VALUE, Audio_new.X, NULL);	\
			}

#define	Set_Statuslight(item, on)	(void) panel_set((item),	\
					PANEL_VALUE, ((on) ? 1 : 0),	\
					0);

#define	NEWSTATE(X, Y)	{						\
			if (Audio_new.X != Audio_info.X)		\
				(void) Set_Statuslight(Y, Audio_new.X);	\
			}

#define	NEWSTRING(X, Y) {						\
			if (Audio_new.X != Audio_info.X) {		\
				SPRINTF(buf, "%u", Audio_new.X);	\
				(void) xv_set(Y, PANEL_LABEL_STRING, buf, NULL); \
			} }

	/* Get the current device state */
	getinfo(&Audio_new);

	/* Update main panel items */
	NEWVAL(play.gain, play_volume_item);
	NEWVAL(record.gain, record_volume_item);
	NEWVAL(monitor_gain, monitor_volume_item);
	NEWVAL(play.port, speaker_item);

	/*
	 * Pause is tricky, since we may be holding the device open.
	 * If 'resume', then release the device, if held.
	 */
	if (!Audio_new.play.pause && (Audio_pausefd >= 0)) {
		(void) close(Audio_pausefd);
		Audio_pausefd = -1;
	}

	if (Audio_new.play.pause != Audio_info.play.pause) {
		if (Audio_new.play.pause) {
			set_button(pause_item, Resume_button);
		} else {
			set_button(pause_item, Pause_button);
		}
	}


	/* Update status panel, if it is visible */
	if (Show_status) {
		NEWSTATE(play.open, play_open_item);
		NEWSTATE(play.pause, play_pause_item);
		NEWSTATE(play.active, play_active_item);
		NEWSTATE(play.error, play_error_item);
		NEWSTATE(play.waiting, play_waiting_item);
		NEWSTRING(play.eof, play_eof_item);
		NEWSTRING(play.sample_rate, play_sample_rate_item);
		NEWSTRING(play.channels, play_channels_item);
		NEWSTRING(play.precision, play_precision_item);

		/* Handle huge numbers 'gracefully' */
		if (Audio_new.play.samples != Audio_info.play.samples) {
			char	*pre;
			int	i;

			if (Audio_new.play.samples < 1000000) {
				pre = "       ";
				i = -6;		/* left-justified */
			} else {
				pre = "";
				i = 10;		/* right-justified */
			}
			SPRINTF(buf, "%s%*u", pre, i, Audio_new.play.samples);
			(void) 
			xv_set(play_samples_item, PANEL_LABEL_STRING, buf, NULL);
		}
		if (Audio_new.play.encoding != Audio_info.play.encoding) {
			encode_string(Audio_new.play.encoding, buf);
			(void) 
			xv_set(play_encoding_item, PANEL_LABEL_STRING, buf, NULL);
		}

		NEWSTATE(record.open, record_open_item);
		NEWSTATE(record.active, record_active_item);
		NEWSTATE(record.pause, record_pause_item);
		NEWSTATE(record.error, record_error_item);
		NEWSTATE(record.waiting, record_waiting_item);
		NEWSTRING(record.sample_rate, record_sample_rate_item);
		NEWSTRING(record.channels, record_channels_item);
		NEWSTRING(record.precision, record_precision_item);

		/* Handle huge numbers 'gracefully' */
		if (Audio_new.record.samples != Audio_info.record.samples) {
			char	*pre;
			int	i;

			if (Audio_new.record.samples < 1000000) {
				pre = "       ";
				i = -6;		/* left-justified */
			} else {
				pre = "";
				i = 10;		/* right-justified */
			}
			SPRINTF(buf, "%s%*u", pre, i, Audio_new.record.samples);
			(void) 
			xv_set(record_samples_item, PANEL_LABEL_STRING, buf, NULL);
		}
		if (Audio_new.record.encoding != Audio_info.record.encoding) {
			encode_string(Audio_new.record.encoding, buf);
			(void) 
			panel_set_value(record_encoding_item, buf);
		}
	}
	/* Save latest values */
	Audio_info = Audio_new;
}

encode_string(enc, bp)
	unsigned	enc;
	char		*bp;
{
	switch (enc) {
	case AUDIO_ENCODING_ULAW:
		STRCPY(bp, "u-law"); break;
	case AUDIO_ENCODING_ALAW:
		STRCPY(bp, "A-law"); break;
	default:
		SPRINTF(bp, "[%d]", enc); break;
	}
}

set_button(item, pr)
	Panel_item	item;
	char		*pr;
{
	(void) 
	xv_set(item, PANEL_LABEL_STRING, pr, 0);
}

/* Display the status panel when the PROPS key is hit */
/*ARGSUSED*/
void
show_status(win, event, arg)
	Xv_Window	win;
	Event	*event;
	caddr_t	arg;
{
	/* If already up, flash or bring to front */
	if (Show_status) {
		(void) xv_set(Status_frame, WIN_SHOW, FALSE, NULL);
	} else {
		Rect	*r;
		int	sb, fp,	fhw, phw;
		int	x, y;

		/* Put status under tool, unless tool is near screen bottom */
		r = (Rect *) xv_get(Base_frame, WIN_SCREEN_RECT);
		sb = r->r_height;
		fp = (int) xv_get(Base_frame, WIN_Y);
		fhw = (int) xv_get(Base_frame, XV_HEIGHT);
		phw = (int) xv_get(Status_frame, XV_HEIGHT);
		if ((fp + fhw + phw) > sb)
					/* move props above tool */
					/* 70 ... adjusts for xview bug */
			y = -(phw + 70);
		else
			y = fhw;

		/* Center status under tool, unless off-screen */
		fp = (int) xv_get(Base_frame, WIN_X);
		fhw = (int) xv_get(Base_frame, XV_WIDTH);
		phw = (int) xv_get(Status_frame, XV_WIDTH);
		x = (fhw - phw) / 2;
		if ((fp + x) < 0)
			x = 0;
		else if ((fp + x + phw) > r->r_width)
			x = r->r_width - fp - phw;

		(void) xv_set(Status_frame,
					/* adjust for xview bug */
		    WIN_X,		x -4,
		    WIN_Y,		y +11,
		    0);
	}

	/* Init info so that update_panels() resets everything */
	AUDIO_INITINFO(&Audio_info);
	Show_status = TRUE;
	update_panels();
	(void) xv_set(Status_frame,
	    WIN_SHOW, TRUE,
	    FRAME_CMD_PUSHPIN_IN, TRUE,
	    0);
}


/* Timer handler...entered periodically when the mouse is in the status panel */
/*ARGSUSED*/
Notify_value
timer_handler(client, which)
	Notify_client	client;
	int		which;
{
	update_panels();
	return (NOTIFY_DONE);
}

/* When the mouse enters the status panel, set a periodic timer */
/*ARGSUSED*/
void
status_loc_orig(win, event, arg)
	Xv_Window		win;
	Event			*event;
	caddr_t			arg;
{
	struct itimerval	timer;

	switch (event_action(event)) {
	case LOC_WINENTER:
		/* Set up to catch interval timer */
		timer.it_value.tv_usec = 1000000 / 4;		/* 1/4 second */
		timer.it_value.tv_sec = 0;
		timer.it_interval.tv_usec = 1000000 / 4;	/* 1/4 second */
		timer.it_interval.tv_sec = 0;

		(void) notify_set_itimer_func(Base_frame,
		    (Notify_func)timer_handler, ITIMER_REAL,
		    &timer, (struct itimerval *)0);
		break;

	case LOC_WINEXIT:
		/* Cancel timer */
		(void) notify_set_itimer_func(Base_frame,
		    (Notify_func)timer_handler, ITIMER_REAL,
		    (struct itimerval *)0, (struct itimerval *)0);
		break;
	}
}


/*ARGSUSED*/
done_status(frame)
	Frame	frame;
{
	if (Show_status) {
		Show_status = FALSE;
		(void) xv_set(Status_frame, WIN_SHOW, FALSE, 0);
	}
}


audio_open()
{
	if ((Audio_fd = open(AUDIO_CTLDEV, O_RDWR)) < 0) {
		perror(AUDIO_CTLDEV);
		exit(1);
	}

	/*
	 * Set the notify flag so that this program (and all others
	 * with this stream open) will be sent a SIGPOLL if changes
	 * are made to the parameters of audio device.
	 */
	if (ioctl(Audio_fd, I_SETSIG, S_MSG) < 0) {
		perror("I_SETSIG");
		exit(1);
	}

	/* Init the state structure so update_panels() will set everything */
	AUDIO_INITINFO(&Audio_info);
}

/* Convert local gain into device parameters */
unsigned
scale_gain(g)
	unsigned	g;
{
	return (AUDIO_MIN_GAIN + (unsigned)
	    irint(((double) (AUDIO_MAX_GAIN - AUDIO_MIN_GAIN)) *
	    ((double)g / (double)MAX_GAIN)));
}

/* Convert device gain into the local scaling factor */
unsigned
unscale_gain(g)
	unsigned	g;
{
	return ((unsigned) irint((double)MAX_GAIN *
	    (((double)(g - AUDIO_MIN_GAIN)) /
	    (double)(AUDIO_MAX_GAIN - AUDIO_MIN_GAIN))));
}


/* Get current audio state */
getinfo(ap)
	audio_info_t	*ap;
{
	if (ioctl(Audio_fd, AUDIO_GETINFO, ap) < 0) {
		perror("AUDIO_GETINFO");
	}

	/* Set the output port to a value we understand */
	ap->play.port = (ap->play.port == AUDIO_SPEAKER ? 0 : 1);

	ap->play.gain = unscale_gain(ap->play.gain);
	ap->record.gain = unscale_gain(ap->record.gain);
	ap->monitor_gain = unscale_gain(ap->monitor_gain);
}


/*
 * The skeleton of this code was created by guide.
 * Guide will NOT regenerate what is here, so don't remove it!
 */

/*
 * gaintool_stubs.c - Notify and event callback function stubs.
 * This file was generated by `gxv' from `gaintool.G'.
 * DO NOT EDIT BY HAND.
 */

#include <stdio.h>
#include <sys/param.h>
#include <sys/types.h>
#include <xview/xview.h>
#include <xview/panel.h>
#include <xview/textsw.h>
#include <xview/xv_xrect.h>
/*
 * #include "gaintool_ui.h" 
 * Moved to top of the file 
 */

void
main(argc, argv)
	int		argc;
	char		**argv;
{
	/* Move to the top...make it global 
	 *
	 * gaintool_BaseFrame_objects	*gaintool_BaseFrame;
	 * gaintool_PropSheet_objects	*gaintool_PropSheet;
	 */
	
	/*
	 * Initialize XView.
	 */
	xv_init(XV_INIT_ARGC_PTR_ARGV, &argc, argv, 0);
	INSTANCE = xv_unique_key();
	
	/*
	 * Initialize user interface components.
	 */
	gaintool_BaseFrame = gaintool_BaseFrame_objects_initialize(NULL, NULL);
	gaintool_PropSheet = gaintool_PropSheet_objects_initialize(NULL, gaintool_BaseFrame->BaseFrame);
	
	/* These attributes are not adjustable with Guide */
	xv_set(Base_frame, FRAME_SHOW_RESIZE_CORNER, FALSE, NULL);
	xv_set(Status_frame, FRAME_SHOW_RESIZE_CORNER, FALSE, NULL);

	xv_set(play_volume_item, PANEL_NOTIFY_LEVEL, PANEL_ALL, NULL);
	xv_set(record_volume_item, PANEL_NOTIFY_LEVEL, PANEL_ALL, NULL);
	xv_set(monitor_volume_item, PANEL_NOTIFY_LEVEL, PANEL_ALL, NULL);

	/* do initialiation original main used to do */
	gaintool_init();

	/*
	 * Turn control over to XView.
	 */
	xv_main_loop(gaintool_BaseFrame->BaseFrame);
	exit(0);
}


/*
 * Event callback function for `BaseFrame'.
 */
Notify_value
main_event_proc(win, event, arg, type)
	Xv_Window	win;
	Event		*event;
	Notify_arg	arg;
	Notify_event_type type;
{
	gaintool_BaseFrame_objects	*ip = (gaintool_BaseFrame_objects *) xv_get(win, XV_KEY_DATA, INSTANCE);
	
	if ((event_action(event) == ACTION_PROPS) && event_is_up(event)) {
		show_status(Status_frame, event, arg);
		return (NOTIFY_DONE);
	}
	return notify_next_event_func(win, event, arg, type);
}

/*
 * The following notify procedures only have to set the appropriate state.
 * Once set, a signal will be generated and the SIGPOLL handler will take
 * care of updating the panels.
 */

/*
 * Notify callback function for `PlaySlider'.
 */
void
play_volume_proc(item, value, event)
	Panel_item	item;
	int		value;
	Event		*event;
{
	gaintool_BaseFrame_objects	*ip = (gaintool_BaseFrame_objects *) xv_get(item, XV_KEY_DATA, INSTANCE);
	
	AUDIO_INITINFO(&Audio_new);
	Audio_new.play.gain = scale_gain(value);
	if (ioctl(Audio_fd, AUDIO_SETINFO, &Audio_new) < 0) {
		perror("Set play volume");
	}
	/* Since the return value is quantized, always update the display */
	Audio_info.play.gain = ~0;
}

/*
 * Notify callback function for `RecordSlider'.
 */
void
record_volume_proc(item, value, event)
	Panel_item	item;
	int		value;
	Event		*event;
{
	gaintool_BaseFrame_objects	*ip = (gaintool_BaseFrame_objects *) xv_get(item, XV_KEY_DATA, INSTANCE);
	

	AUDIO_INITINFO(&Audio_new);
	Audio_new.record.gain = scale_gain(value);
	if (ioctl(Audio_fd, AUDIO_SETINFO, &Audio_new) < 0) {
		perror("Set record volume");
	}
	/* Since the return value is quantized, always update the display */
	Audio_info.record.gain = ~0;
}

/*
 * Notify callback function for `MonitorSlider'.
 */
void
monitor_volume_proc(item, value, event)
	Panel_item	item;
	int		value;
	Event		*event;
{
	gaintool_BaseFrame_objects	*ip = (gaintool_BaseFrame_objects *) xv_get(item, XV_KEY_DATA, INSTANCE);
	

	AUDIO_INITINFO(&Audio_new);
	Audio_new.monitor_gain = scale_gain(value);
	if (ioctl(Audio_fd, AUDIO_SETINFO, &Audio_new) < 0) {
		perror("Set monitor volume");
	}
	/* Since the return value is quantized, always update the display */
	Audio_info.monitor_gain = ~0;
}

/*
 * Notify callback function for `OutputSwitch'.
 */
void
control_output_proc(item, value, event)
	Panel_item	item;
	int		value;
	Event		*event;
{
	gaintool_BaseFrame_objects	*ip = (gaintool_BaseFrame_objects *) xv_get(item, XV_KEY_DATA, INSTANCE);
	

	AUDIO_INITINFO(&Audio_new);
	Audio_new.play.port = (value == 0 ? AUDIO_SPEAKER : AUDIO_HEADPHONE);
	if (ioctl(Audio_fd, AUDIO_SETINFO, &Audio_new) < 0) {
		perror("Set output port");
	}
}

/*
 * The Pause button only affects output.
 * When pushed, it changes to a Resume button.
 *
 * Setting the pause bit on a device that is not open has no effect.
 * If the button is pressed when the play stream of /dev/audio is closed,
 * we open the device here in order to make sure no output occurs.
 *
 * If the resume button is pressed or any other process sets 'play.resume',
 * we let go of the device in update_panels().
 *
 * Since device open/close signals a state change, update_panels()
 * will take care of switching the button image.
 */
/*
 * Notify callback function for `Pause_button'.
 */
void
pause_proc(item, event)
	Panel_item	item;
	Event		*event;
{
	gaintool_BaseFrame_objects	*ip = (gaintool_BaseFrame_objects *) xv_get(item, XV_KEY_DATA, INSTANCE);
	
	/* If trying to pause, try to open /dev/audio first */
	if (!Audio_info.play.pause && (Audio_pausefd < 0)) {
		Audio_pausefd = open(AUDIO_IODEV, O_WRONLY | O_NDELAY);
	}

	/* Set up to set the pause bit */
	AUDIO_INITINFO(&Audio_new);
	Audio_new.play.pause = !Audio_info.play.pause;
	if (ioctl(Audio_fd, AUDIO_SETINFO, &Audio_new) < 0) {
		perror("pause/resume");
	}
}

/*
 * Done callback function for `PropSheet'.
 */
void
props_done_proc(frame)
	Frame		frame;
{
	xv_set(frame, XV_SHOW, FALSE, 0);
}

/*
 * Event callback function for `PlayPropsPanel'.
 */
Notify_value
props_play_event(win, event, arg, type)
	Xv_Window	win;
	Event		*event;
	Notify_arg	arg;
	Notify_event_type type;
{
	gaintool_PropSheet_objects	*ip = (gaintool_PropSheet_objects *) xv_get(win, XV_KEY_DATA, INSTANCE);
	
	
	if (event_action(event) == ACTION_MENU && event_is_down(event)) {
		Menu	menu = (Menu) xv_get(win, WIN_MENU);

		if (menu)
			menu_show(menu, win, event, 0);
	}
	return notify_next_event_func(win, event, arg, type);
}

/*
 * Event callback function for `RecPropsPanel'.
 */
Notify_value
props_rec(win, event, arg, type)
	Xv_Window	win;
	Event		*event;
	Notify_arg	arg;
	Notify_event_type type;
{
	gaintool_PropSheet_objects	*ip = (gaintool_PropSheet_objects *) xv_get(win, XV_KEY_DATA, INSTANCE);
	
	
	if (event_action(event) == ACTION_MENU && event_is_down(event)) {
		Menu	menu = (Menu) xv_get(win, WIN_MENU);

		if (menu)
			menu_show(menu, win, event, 0);
	}
	return notify_next_event_func(win, event, arg, type);
}

/*
 * Event callback function for `PropSheet'.
 */
Notify_value
status_loc(win, event, arg, type)
        Xv_Window       win;
        Event           *event;
        Notify_arg      arg;
        Notify_event_type type;
{
        gaintool_PropSheet_objects      *ip = (gaintool_PropSheet_objects *) xv_get(win, XV_KEY_DATA, INSTANCE);

	status_loc_orig(win, event, arg);

        return notify_next_event_func(win, event, arg, type);
}
