/*---------------------------------------------------------------------------------
Name               : amixer.c
Author             : Marvin Raaijmakers
Description        : Plugin for keyTouch that can change the volume (via ALSA).
Date of last change: 09-Dec-2006
History            : 09-Dec-2006 Muting is now also possible for channels without
                                 a playback switch
                     19-Oct-2006 This plugin now uses the ALSA library for setting
                                 and retrieving the volume, instead of a pipe to
                                 amixer. It now also uses the mixer_channel element
                                 of the KTPreferences structure.
                     24-Sep-2006 Added two new plugin functions:
                                 "Volume increase 10%" and "Volume decrease 10%"
                     05-Mar-2006 - clean_exit() will be used to exit the client
                                   process, that manages the volume bar, cleanly
                                 - update_window() now returns a boolean indicating
                                   if the function should be called again
                     29-Jan-2006 Added the GUI volume bar to the plugin

    Copyright (C) 2005-2007 Marvin Raaijmakers

    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 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.
-----------------------------------------------------------------------------------*/
#define _GNU_SOURCE
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
#include <gtk/gtk.h>
#include <time.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>
#include <errno.h>
#include <alsa/asoundlib.h>
#include <math.h>

#include <plugin.h>
#include <amixer-plugin.h>

void vol_increase (KTPreferences *preferences);
void vol_decrease (KTPreferences *preferences);
void vol_increase_10 (KTPreferences *preferences);
void vol_decrease_10 (KTPreferences *preferences);
void mute (KTPreferences *preferences);

static void create_window (VOLUMEBAR_INFO *volumebar_info);
static double get_current_volume (const char *mix_elem_name);
static void update_volume_bar (GtkWidget *volume_bar, const char *mix_elem_name);
static gboolean update_window (VOLUMEBAR_INFO *volumebar_info);
static void clean_exit (int sig);
static void start_window (const char *mix_elem_name);
static char *get_keytouch_user_dir (void);
static void change_volume (int vol_incr, const char *mix_elem_name);
static Boolean volume_is_muted (const char *mix_elem_name);


KeytouchPlugin plugin_struct = {
	{"Amixer", "Marvin Raaijmakers", "GPL 2", "3.0",
	 "This plugin allows you to change the volume. It also shows\n"
	 "the current volume when it changes."},
	"amixer.so",
	5,
	{{"Volume increase",     KTPluginFunctionType_Function, {.function = vol_increase}},
	 {"Volume decrease",     KTPluginFunctionType_Function, {.function = vol_decrease}},
	 {"Volume increase 10%", KTPluginFunctionType_Function, {.function = vol_increase_10}},
	 {"Volume decrease 10%", KTPluginFunctionType_Function, {.function = vol_decrease_10}},
	 {"Mute",                KTPluginFunctionType_Function, {.function = mute}},
	}
};


/******* Begin ALSA part *******/

snd_mixer_elem_t
*get_mixer_elem (const char *control_name)
/*
Input:
	control_name	- The name of the mixer element to get.
Returns:
	A pointer to the mixer element that is named 'control_name' or NULL if no
	such element exists. IMPORTANT: This pointer will be valid until this
	function is being called again (because then the related resources will be
	freed).
*/
{
	static snd_mixer_t *handle = NULL;
	static snd_mixer_selem_id_t *sid;
	snd_mixer_elem_t *elem;
	int err;
	
	if (handle != NULL)
	{
		snd_mixer_close (handle);
		handle = NULL;
	}
	snd_mixer_selem_id_alloca (&sid);
	snd_mixer_selem_id_set_index (sid, 0);
	snd_mixer_selem_id_set_name (sid, control_name);
	
	
	if ((err = snd_mixer_open(&handle, 0)) < 0)
	{
		fprintf (stderr, "Mixer %s open error: %s\n", "default", snd_strerror(err));
		return NULL;
	}
	if ((err = snd_mixer_attach(handle, "default")) < 0)
	{
		fprintf (stderr, "Mixer attach %s error: %s", "default", snd_strerror(err));
		snd_mixer_close (handle);
		handle = NULL;
		return NULL;
	}
	if ((err = snd_mixer_selem_register(handle, NULL, NULL)) < 0)
	{
		fprintf (stderr, "Mixer register error: %s", snd_strerror(err));
		snd_mixer_close (handle);
		handle = NULL;
		return NULL;
	}
	err = snd_mixer_load (handle);
	if (err < 0)
	{
		fprintf (stderr, "Mixer %s load error: %s", "default", snd_strerror(err));
		snd_mixer_close (handle);
		handle = NULL;
		return NULL;
	}
	
	
	elem = snd_mixer_find_selem (handle, sid);
	if (!elem)
	{
		fprintf (stderr, "Unable to find simple control '%s',%i\n", snd_mixer_selem_id_get_name(sid), snd_mixer_selem_id_get_index(sid));
		snd_mixer_close (handle);
		handle = NULL;
		return NULL;
	}
	
	return elem;
}

/******* End ALSA part *******/


void
create_window (VOLUMEBAR_INFO *volumebar_info)
/*
Input:
	-
Output:
	volumebar_info	- The window element points to the created window and the
			  volume_bar element points to the volume progressbar in the
			  window
Returns:
	-
Description:
	This function creates a window with a progressbar with the following
	properties:
	- It is positioned in the center ot the screen.
	- It has no window decorations and can not be resized by the user.
	- It will allways be above other windows.
	- It is visible on all desktops.
	- It will not be visible in the taskbar an pager.
	- It does not accept focus.
*/
{
	volumebar_info->window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
	gtk_window_set_position (GTK_WINDOW (volumebar_info->window), GTK_WIN_POS_CENTER);
	gtk_window_set_resizable (GTK_WINDOW (volumebar_info->window), FALSE);
	gtk_window_set_decorated (GTK_WINDOW (volumebar_info->window), FALSE);
	/* The window will allways be above others */
	gtk_window_set_keep_above (GTK_WINDOW (volumebar_info->window), TRUE);
	/* Let the window be visible on all desktops: */
	gtk_window_stick (GTK_WINDOW (volumebar_info->window));
	/* This window will not be visible in the taskbar: */
	gtk_window_set_skip_taskbar_hint (GTK_WINDOW (volumebar_info->window), TRUE);
	/* This window will not be visible in the pager: */
	gtk_window_set_skip_pager_hint (GTK_WINDOW (volumebar_info->window), TRUE);
	gtk_window_set_accept_focus (GTK_WINDOW (volumebar_info->window), FALSE);
	
	volumebar_info->volume_bar = gtk_progress_bar_new();
	gtk_widget_show (volumebar_info->volume_bar);
	gtk_container_add (GTK_CONTAINER (volumebar_info->window), volumebar_info->volume_bar);
	gtk_widget_set_size_request (volumebar_info->volume_bar, VOLUME_WINDOW_WIDTH, VOLUME_WINDOW_HEIGHT);
	gtk_progress_bar_set_fraction (GTK_PROGRESS_BAR (volumebar_info->volume_bar), 0.52);
	gtk_progress_bar_set_pulse_step (GTK_PROGRESS_BAR (volumebar_info->volume_bar), 0.02);
	gtk_progress_bar_set_text (GTK_PROGRESS_BAR (volumebar_info->volume_bar), "Volume");
}


double
get_current_volume (const char *mix_elem_name)
/*
Input:
	mix_elem_name	- The name of the mixer element that should be used for
			  retrieving the volume.
Returns:
	The current volume level (0.00 = lowest to 1.00 = highest) retrieved from
	amixer. -1.0 will be returned when retrieving the volume failed.
*/
{
	snd_mixer_elem_t *mix_elem;
	long vol_min, vol_max, cur_vol;
	double volume = -1.0;
	
	mix_elem = get_mixer_elem (mix_elem_name);
	if (mix_elem)
	{
		snd_mixer_selem_get_playback_volume_range (mix_elem, &vol_min, &vol_max);
		snd_mixer_selem_get_playback_volume (mix_elem, 0, &cur_vol); /* Take the first channel (= 0) */
		volume = (double)(cur_vol - vol_min) / ((double)(vol_max - vol_min));
	}
	return (volume);
}


Boolean
volume_is_muted (const char *mix_elem_name)
/*
Input:
	mix_elem_name	- The name of the mixer element that should be used for
			  retrieving the state of the mute switch.
Returns:
	TRUE if the first channel (= 0) of the mixer element named 'mix_elem_name'
	is muted, otherwise FALSE.
*/
{
	snd_mixer_elem_t *mix_elem;
	int not_muted = TRUE;
	
	mix_elem = get_mixer_elem (mix_elem_name);
	if (mix_elem)
	{
		snd_mixer_selem_get_playback_switch (mix_elem, 0, &not_muted); /* Take the first channel (= 0) */
	}
	
	return (Boolean) !not_muted;
}


void
update_volume_bar ( GtkWidget  *volume_bar,
                    const char *mix_elem_name )
/*
Input:
	mix_elem_name	- The name of the mixer element that should be used for
			  retrieving the volume.
Output:
	volume_bar	- Will show the percentage of the current volume. The text
			  on this progressbar will be equal to "Volume #%" where #
			  is the volume percentage, if the volume is not muted. If
			  the volume is muted then the text will be "Muted".
*/
{
	double volume;
	gchar *text;
	
	volume = get_current_volume (mix_elem_name);
	if (volume < .00)
	{
		volume = .00;
	}
	
	if (volume_is_muted (mix_elem_name))
	{
		gtk_progress_bar_set_text (GTK_PROGRESS_BAR(volume_bar), "Muted");
	}
	else
	{
		text = g_strdup_printf("Volume %d%%", (int)(volume*100));
		if (text)
		{
			gtk_progress_bar_set_text (GTK_PROGRESS_BAR(volume_bar), text);
			g_free (text);
		}
	}
	
	gtk_progress_set_percentage (GTK_PROGRESS(volume_bar), (gdouble)volume);
	/* Directly draw the progressbar: */
	while (g_main_context_iteration(NULL, FALSE))
		; /* NULL Statement */
}


gboolean
update_window (VOLUMEBAR_INFO *volumebar_info)

/*
Input:
	volumebar_info->close_time	- The time to close the window
	volumebar_info->mix_elem_name	- The name of the mixer element that should
					  be used for retrieving the volume.
Output:
	volumebar_info			- Will be updated
Returns:
	TRUE if this function should be called again after UPDATE_INTERVAL
	miliseconds, otherwise FALSE.
Description:
	This function destroys volumebar_info->window and escapes from the GTK main
	routine if the current time is later than volumebar_info->close_time. If not
	then the volume bar will be updated with the current volume.
*/
{
	MSGBUF msg;
	Boolean close_window;
	
	/* Check if there is a new message on the queue */
	if (msgrcv(volumebar_info->msgqid, &msg, sizeof(msg.time), 1, IPC_NOWAIT) != -1)
	{
		volumebar_info->close_time = msg.time + SHOW_WINDOW_TIME;
	}
	close_window = (time(NULL) > volumebar_info->close_time);
	if (!close_window)
	{
		update_volume_bar (volumebar_info->volume_bar, volumebar_info->mix_elem_name);
	}
	else
	{
		gtk_widget_destroy (volumebar_info->window);
		gtk_main_quit();
	}
	return !close_window;
}


void
start_window (const char *mix_elem_name)
/*
Input:
	mix_elem_name	- The name of the mixer element that should be used for
			  retrieving the volume.
Description:
	This function creates a window with a volume bar and shows it
	SHOW_WINDOW_TIME seconds when it receives a message on the message queue.
	The key of the message queue is generated by running
	ftok(get_keytouch_user_dir(), MSGQ_AMIXER_PROJ_ID). The messages that are
	sent to this queue should contain the time they are sent. The volume window
	will be showed from the time this function receives the message, until the
	time the message was sent plus SHOW_WINDOW_TIME seconds.
*/
{
	MSGBUF		msg;
	VOLUMEBAR_INFO	volumebar_info;
	key_t		msgq_key;
	char		*keytouch_user_dir;
	
	gtk_init (0, NULL);
	keytouch_user_dir = get_keytouch_user_dir();
	/* Get the key for the message queue */
	msgq_key = ftok(keytouch_user_dir, MSGQ_AMIXER_PROJ_ID);
	free (keytouch_user_dir);
	if (msgq_key == -1)
	{
		perror ("keytouch amixer plugin");
		return;
	}
	/* Get the message queue identifier and create the queue if necessary */
	volumebar_info.msgqid = msgget (msgq_key, 0);
	if (volumebar_info.msgqid == -1)
	{
		perror ("keytouch amixer plugin");
		return;
	}
	
	volumebar_info.mix_elem_name = mix_elem_name;
	
	while (1)
	{
		if (msgrcv(volumebar_info.msgqid, &msg, sizeof(msg.time), 1, 0) != -1)
		{
			volumebar_info.close_time = msg.time + SHOW_WINDOW_TIME;
			if (time(NULL) <= volumebar_info.close_time)
			{
				create_window (&volumebar_info);
				update_volume_bar (volumebar_info.volume_bar, mix_elem_name);
				gtk_widget_show (volumebar_info.window);
				g_timeout_add (UPDATE_INTERVAL, (GSourceFunc) update_window, &volumebar_info);
				gtk_main();
			}
		}
	}
}


char
*get_keytouch_user_dir (void)
/*
Returns:
	The address of some new allocated space which is a string containing the
	value of the environment variable HOME followed by "/.keytouch2".
*/
{
	char *keytouch_dir, *home;
	
	home = getenv("HOME");
	if (home == NULL)
	{
		fputs ("keytouch amixer plugin: could not get environment variable $HOME", stderr);
		exit (EXIT_FAILURE);
	}
	if (asprintf(&keytouch_dir, "%s/.keytouch2", home) == -1)
	{
		fputs ("keytouch amixer plugin: asprintf() failed. "
		       "This is probably caused because it failed to allocate memory.", stderr);
		exit (EXIT_FAILURE);
	}
	return (keytouch_dir);
}


void
clean_exit (int sig)
{
	exit (EXIT_SUCCESS);
}


void
send_volume_changed_signal (const char *mix_elem_name)
/*
Input:
	mix_elem_name	- The name of the mixer element that should be used for
			  retrieving the volume.
Description:
	This function sends a signal to the child program that manages the
	volumebar. The child will receive the signal and will show the volumebar.
	The child process will be created if it does not exist yet. The volume of
	the mixer element named 'mix_elem_name' will be used. When this function is
	called for the first time, then the value of 'mix_elem_name' will also be
	used for the next time this function is called.
*/
{
	static int qid = -1;
	MSGBUF msg;
	
	/* If this is the first time this function was called */
	if (qid == -1)
	{
		key_t msgq_key;
		char *keytouch_user_dir;
		
		keytouch_user_dir = get_keytouch_user_dir();
		/* Get the key for the message queue */
		msgq_key = ftok(keytouch_user_dir, MSGQ_AMIXER_PROJ_ID);
		free (keytouch_user_dir);
		if (msgq_key == -1)
		{
			perror ("keytouch amixer plugin");
			return;
		}
		/* Get the message queue identifier and create the queue if necessary */
		qid = msgget(msgq_key, MSGQ_PERMISSIONS | IPC_CREAT);
		if (qid == -1)
		{
			perror ("keytouch amixer plugin");
			return;
		}
		if (fork() == 0)
		{
			/* Trap key signals */
			signal (SIGINT, clean_exit);
			signal (SIGQUIT, clean_exit);
			signal (SIGTERM, clean_exit);
			/* We will now start the run_window() function in our
			 * child process for showing a volume bar to the user
			 */
			start_window (mix_elem_name);
			exit (EXIT_SUCCESS); /* We will never get here because of
			                      * the infinite loop in start_window()
			                      */
		}
	}
	msg.mtype = 1;
	msg.time = time(NULL);
	if (msgsnd(qid, &msg, sizeof(msg.time), 0) == -1)
	{
		perror ("keytouch amixer plugin");
	}
}


void
change_volume (	int		vol_incr,
		const char	*mix_elem_name )
/*
Input:
	command		- The command that changes the volume.
	mix_elem_name	- The name of the mixer element to use.
Description:
	This function executes 'command' in a child process and then calls
	send_volume_changed_signal().
*/
{
	long vol_min, vol_max, cur_vol;
	snd_mixer_selem_channel_id_t chn;
	snd_mixer_elem_t *mix_elem;
	
	mix_elem = get_mixer_elem (mix_elem_name);
	if (mix_elem)
	{
		snd_mixer_selem_get_playback_volume_range (mix_elem, &vol_min, &vol_max);
		
		for (chn = 0; chn <= SND_MIXER_SCHN_LAST; chn++)
		{
			if (snd_mixer_selem_has_playback_channel(mix_elem, chn))
			{
				snd_mixer_selem_get_playback_volume (mix_elem, chn, &cur_vol);
				cur_vol += rint((double)(vol_max - vol_min) * ((double)vol_incr*.01));
				if (cur_vol > vol_max)
				{
					cur_vol = vol_max;
				}
				else if (cur_vol < vol_min)
				{
					cur_vol = vol_min;
				}
				snd_mixer_selem_set_playback_volume (mix_elem, chn, cur_vol);
				/* If the volume level of this channel also controls the level
				 * of the other channels of 'mix_elem' */
				if (snd_mixer_selem_has_playback_volume_joined (mix_elem))
				{
					break;
				}
			}
		}
		send_volume_changed_signal (mix_elem_name);
	}
}


void
vol_increase (KTPreferences *preferences)
{
	change_volume (VOL_DEFAULT_INCR, preferences->mixer_channel);
}


void
vol_decrease (KTPreferences *preferences)
{
	change_volume (VOL_DEFAULT_DECR, preferences->mixer_channel);
}


void
vol_increase_10 (KTPreferences *preferences)
{
	change_volume (VOL_10PERCENT_INCR, preferences->mixer_channel);
}


void
vol_decrease_10 (KTPreferences *preferences)
{
	change_volume (VOL_10PERCENT_DECR, preferences->mixer_channel);
}


void
mute (KTPreferences *preferences)
{
	snd_mixer_elem_t *mix_elem;
	int unmuted;
	snd_mixer_selem_channel_id_t chn;
	/* If no mixer channel does not have a playback switch (for muting), the value
	 * of 'no_switch_muted' indicates whether the plugin has muted the volume (TRUE)
	 * or not (FALSE) */
	static Boolean no_switch_muted = FALSE;
	static long prev_volume = -1;
	long volume, vol_min, vol_max;
	
	mix_elem = get_mixer_elem (preferences->mixer_channel);
	if (mix_elem)
	{
		/* if mix_elem has a playback switch for muting: */
		if (snd_mixer_selem_has_playback_switch(mix_elem))
		{
			/* Toggle the switch for every channel: */
			for (chn = 0; chn <= SND_MIXER_SCHN_LAST; chn++)
			{
				/* Is it possible to mute/unmute this channel? */
				if (snd_mixer_selem_has_playback_channel (mix_elem, chn))
				{
					snd_mixer_selem_get_playback_switch (mix_elem, chn, &unmuted);
					snd_mixer_selem_set_playback_switch (mix_elem, chn, (unmuted ? 1 : 0) ^ 1);
					/* If the mute switch of this channel also controls the mute switch
					 * of the other channels of 'mix_elem' */
					if (snd_mixer_selem_has_playback_switch_joined (mix_elem))
					{
						break;
					}
				}
			}
		}
		else
		{
			snd_mixer_selem_get_playback_volume_range (mix_elem, &vol_min, &vol_max);
			snd_mixer_selem_get_playback_volume (mix_elem, 0, &volume);
			/* If the volume level is not equal to the lowest possible level then
			 * the mixer channel is not muted: */
			no_switch_muted &= !(volume - vol_min);
			if (no_switch_muted) /* if muted */
			{
				volume = prev_volume;
			}
			else
			{
				prev_volume = volume;
				volume = vol_min;
			}
			no_switch_muted = !no_switch_muted;
			
			/* Set the new volume for every channel: */
			for (chn = 0; chn <= SND_MIXER_SCHN_LAST; chn++)
			{
				/* Is it possible to mute/unmute this channel? */
				if (snd_mixer_selem_has_playback_channel (mix_elem, chn))
				{
					snd_mixer_selem_set_playback_volume (mix_elem, chn, volume);
					/* If the volume level of this channel also controls the level
					 * of the other channels of 'mix_elem' */
					if (snd_mixer_selem_has_playback_volume_joined (mix_elem))
					{
						break;
					}
				}
			}
		}
		send_volume_changed_signal (preferences->mixer_channel);
	}
}
