/*

Sound audio library
   
Copyright (c) 1999 Pascal Hofstee & Alain Kalker
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products
   derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

$Id: wsoundserver.c,v 1.28 2000/02/24 11:20:05 daeron Exp $

*/

#include <dockapp.h>
#include <unistd.h>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/Xatom.h>
#include "wsound.h"
#include "wsoundserver.xpm"


char 	*displayName = "";
Bool 	done = False;
Bool	dragging = False;
Pixmap	pixmap;
Pixmap	pixmap2;
Atom	deleteWin;
Atom	protos[1];

static DAProgramOption options[] = {
	{"-d", "--display", "display to use", DOString, False, {&displayName} }
};


static int wssInitDisplay(int argc, char **argv);
static void wssProcessEvents(void);
static Window wssFindWindowMakerNoticeBoard(void);
static void buttonPress(int button, int state, int x, int y);
static void buttonRelease(int button, int state, int x, int y);
static void pointerMotion(int x, int y);
static void wssSetVolume(int x, int y);



int
main (int argc, char **argv) {
	SInitializeApplication(argv[0]);
	
	if (wssInitDisplay(argc, argv) < 0)
		sfatal(SMessageForError(SERR_NODISPLAY));
	
	wssProcessEvents();

	XCloseDisplay(DADisplay);

	SShutdownApplication();
	return 0;
}

int
wssInitDisplay (int argc, char **argv)
{
	GC	gc;
	Pixmap	mask;
	static unsigned d_width = 48;
	static unsigned d_height = 48;
	DACallbacks callbacks={NULL, buttonPress, buttonRelease, pointerMotion, NULL, NULL};
	char *package, *version;
	Window noticeboard; /* The window that Window Maker posts it's events on */

	package = malloc((strlen(PACKAGE) + strlen(" for ") + strlen(DRIVER) + 1) * sizeof(char));
	sprintf(package, "%s for %s", PACKAGE, DRIVER);

	version = malloc((strlen(package) + strlen(" version ") + strlen(VERSION)
#ifdef DEBUG
									+ strlen(" [DEBUG]")
#endif
									+1) * sizeof(char));
									
#ifndef DEBUG
	sprintf(version, "%s version %s", package, VERSION);
#else
	sprintf(version, "%s version %s [DEBUG]", package, VERSION);
#endif
	
	DAParseArguments(argc, argv, options,
			sizeof(options)/sizeof(DAProgramOption),
			package, version);

	free(package);
	free(version);
	
	DAInitialize(displayName, "wsoundserver", d_width, d_height, argc, argv);
	
	_XA_WINDOWMAKER_EVENT = XInternAtom(DADisplay, "_WINDOWMAKER_EVENT", False);

	protos[0] = _XA_WINDOWMAKER_EVENT;
	
	XSetWMProtocols(DADisplay, DAWindow, protos, 1);
	
	DAMakePixmapFromData(wsoundserver_xpm, &pixmap, &mask, &d_width, &d_height);
	DAMakePixmapFromData(wsoundserver_xpm, &pixmap2, &mask, &d_width, &d_height);

	DASetShape (mask);

	DASetPixmap(pixmap);
	gc = DefaultGC(DADisplay, DefaultScreen(DADisplay));
	
	DASetCallbacks(&callbacks);
	wssSetVolume(1,1);
	
	noticeboard = wssFindWindowMakerNoticeBoard();
	XSelectInput(DADisplay, noticeboard, StructureNotifyMask);
	
	DAShow();

	return 0;
}


void
wssProcessEvents ()
{
	XEvent event;
	Bool hadSuccess = False;
	Bool firstAppStart = True;
	
	while (!done) {
		XNextEvent(DADisplay, &event);
		DAProcessEvent(&event);
		
		switch (event.type) {
			case Expose:
				break;
			case ClientMessage:
				{
					if (event.xclient.message_type == _XA_WINDOWMAKER_EVENT) {
						/* Replace appStart sound generated by starting up
						 * the sound server with startup event.
						 */
						if (firstAppStart &&
								event.xclient.data.l[0] == SEVNT_APPSTART) {
							firstAppStart = False;
							event.xclient.data.l[0] = SEVNT_STARTUP;
						}
						
						if (SPlayEvent(event.xclient.data.l[0]) == -1) {
							/* Stop displaying "Could not open audio device" warning
							 * after we have at least once been successful in opening
							 * it. This prevents a lot of logfile spamming
							 */
							if ((SErrorCode != SERR_DEVOPEN) || hadSuccess == 0)
								swarning(SMessageForError(SErrorCode));

							SErrorCode = SERR_NONE;
						}
						else {
							if (hadSuccess < 2)
								hadSuccess++;
						}

						XSync(DADisplay, True);
					}
					break;
				}
			case DestroyNotify:
				done = True;
				break;
		}
	} /* while */

	SPlayEvent(SEVNT_SHUTDOWN);
}


Window
wssFindWindowMakerNoticeBoard(void)
{
	Window	noticeboard = None;
	
    Window	*lstChildren;
    Window	retRoot;
    Window	retParent;
    int		indexCount;
    u_int	numChildren;
    
    Atom	_XA_WINDOWMAKER_NOTICEBOARD = XInternAtom(DADisplay,
	    "_WINDOWMAKER_NOTICEBOARD", True);
    Atom	type_ret;
    int		format_ret;
    unsigned long nitems_ret;
    unsigned long bytes_after_ret;
    unsigned char *data;

    if (XQueryTree(DADisplay, DefaultRootWindow(DADisplay), &retRoot,
		&retParent, &lstChildren, &numChildren)) {

	for (indexCount = 1; indexCount < numChildren; indexCount++) {
	    if (XGetWindowProperty(DADisplay, lstChildren[indexCount],
		    _XA_WINDOWMAKER_NOTICEBOARD, 0, 1, False, XA_WINDOW,
		    &type_ret, &format_ret, &nitems_ret, &bytes_after_ret,
		    (unsigned char**)&data) == Success && data) {
		noticeboard = lstChildren[indexCount];
	    }
	}
	XFree(lstChildren);
    }

    return noticeboard;;
}



static void
buttonPress(int button, int state, int x, int y)
{
	/* We clicked the close button */
	if ((x >= 36) && (y <= 12))
		done = True;

	/* Button is down in volume slider */
	if ((x < 10) && (y > 0) && (y < 48)) {
		wssSetVolume(x,y);
		dragging = True;
	}
}


static void
buttonRelease(int button, int state, int x, int y)
{
	dragging = False;
}


static void
pointerMotion(int x, int y)
{
	if (dragging)
		wssSetVolume(x,y);
}


static void
wssSetVolume(int x, int y)
{
	if (x < 0) x = 0;
	if (x > 9) x = 9;
	if (y < 1) y = 1;
	if (y > 47) y = 47;
	
	XCopyArea(DADisplay, pixmap2, pixmap, DefaultGC(DADisplay, DefaultScreen(DADisplay)), 48, y, 8, 48 - y, 1, y);
	XCopyArea(DADisplay, pixmap2, pixmap, DefaultGC(DADisplay, DefaultScreen(DADisplay)),	1, 0, 8, y, 1, 0);
	/* DASetPixmap(pixmap); */
	/* The above is the exact same bug as wmdate has with shaped windows */
	/* Using workaround */
	XCopyArea(DADisplay, pixmap, DAWindow, DefaultGC(DADisplay, DefaultScreen(DADisplay)), 0, 0, 64, 64, 0, 0);

	SSetVolume((47.0 - (float)(y))/46.0);	/* Adjust the volume for soundevents */
}
