/* $Id$
******************************************************************************

   LibGGIMisc extension API header file.

   Copyright (c) 2001 Brian S. Julin		bri@calyx.com
   Copyright (c) 1998 Andreas Beck              becka@ggi-project.org
   Copyright (c) 1997 Uwe Maurer                uwe_maurer@t-online.de
   
   Permission is hereby granted, free of charge, to any person obtaining a
   copy of this software and associated documentation files (the "Software"),
   to deal in the Software without restriction, including without limitation
   the rights to use, copy, modify, merge, publish, distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the
   Software is furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be included in
   all copies or substantial portions of the Software.

   The above copyright notice applies to all files in this package, unless 
   explicitly stated otherwise in the file itself or in a file named COPYING 
   in the same directory as the file.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
   IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
   THE AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
   IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
   CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


******************************************************************************
*/

#include <stdio.h>
#include <string.h>

#include "config.h"
#include <ggi/gg.h> /* We use LibGG to manage config files */
#include <ggi/internal/misc.h>
#include <ggi/internal/misc_debug.h>
#include <ggi/internal/gg_replace.h>	/* for snprintf() */


/* Static variables 
 */
static int 	 _ggiMiscLibIsUp       = 0;
static void	*_ggiMiscConfigHandle  = NULL;
static char      _ggiMiscconfstub[512] = GGIMISCCONFDIR;
static char     *_ggiMiscconfdir       = _ggiMiscconfstub+GGIMISCTAGLEN;


uint32_t _miscDebug = 0;


/* Extension ID. Defaulting to -1 should make segfault on abuse more likely...
   This is exported so that sublibs can use it.
 */
ggi_extid _ggiMiscID = -1;

#define SUBLIB_PREFIX   "GGIMISCdl_"


/* 
 * Returns the directory where global config files are kept
 */

const char *ggiMiscGetConfDir(void)
{
#if defined(__WIN32__) && !defined(__CYGWIN__)
	/* On Win32 we allow overriding of the compiled in path. */
	const char *envdir = getenv("GGI_CONFDIR");
	if (envdir) return envdir;
#endif
	return _ggiMiscconfdir;
}


/* Dummy function which returns -1
   We use this to reset the function pointers */
static int dummyfunc(void)
{
	DPRINT("LibGGIMisc: dummyfunc() of LibGGIMisc called\n");
	return GGI_ENOFUNC;
}	/* dummyfunc */


/*-* Reset all function pointers to dummyfunc */
static void clearfuncs(ggiMiscpriv *priv)
{
	priv->waitraypos = (void *) dummyfunc;
	priv->getraypos = (void *) dummyfunc;
	priv->setsplitline = (void *) dummyfunc;
}	/* clearfuncs */


/* This function is called by LibGGI when the API-list changes */
static int changed(ggi_visual_t vis, int whatchanged)
{
	DPRINT("changed(%p, 0x%x) of LibGGIMisc called\n",
	       vis, whatchanged);

	switch (whatchanged) {
	case GGI_CHG_APILIST: {
		int i;
		ggi_dlhandle *lib;
		char api[GGI_MAX_APILEN], args[GGI_MAX_APILEN];

		clearfuncs(LIBGGI_GGIMISCEXT(vis));

		for(i=0; ggiGetAPI(vis, i, api, args) == 0; i++) {
			ggstrlcat(api,"-ggimisc", sizeof(api));
			DPRINT_LIBS("Trying #%d: %s(%s)\n", i, api, args);

			lib = ggiExtensionLoadDL(vis, _ggiMiscConfigHandle,
					api, args, NULL, SUBLIB_PREFIX);
			if (lib != NULL) break;
		}	/* for */
		}
		break;
	}	/* switch */

	return 0;
}	/* changed */


void _ggimiscInitBuiltins(void);
void _ggimiscExitBuiltins(void);


/* Initialize the extension
 */
int ggiMiscInit(void)
{
	int err;
	char *str;
	const char *confdir;
	char *conffile;

	_ggiMiscLibIsUp++;
	if (_ggiMiscLibIsUp > 1) return 0; /* Initialize only at first call. */


	str = getenv("MISC_DEBUGSYNC");
	if (str != NULL) {
		_miscDebug |= DEBUG_SYNC;
	}

	str = getenv("MISC_DEBUG");
	if (str != NULL) {
		_miscDebug |= atoi(str) & DEBUG_ALL;
		DPRINT_CORE("%s Debugging=%d\n",
				DEBUG_ISSYNC ? "sync" : "async",
				_miscDebug);
	}

	confdir = ggiMiscGetConfDir();
	conffile = malloc(strlen(confdir) + 1 + strlen(GGIMISCCONFFILE)+1);
	if (!conffile) {
		fprintf(stderr, "LibGGIMisc: unable to allocate memory for config filename.\n");
		_ggiMiscLibIsUp--;
		return GGI_ENOMEM;
	}

	snprintf(conffile, strlen(confdir) + strlen(GGIMISCCONFFILE) + 2,
		"%s/%s", confdir, GGIMISCCONFFILE);
	err = ggLoadConfig(conffile, &_ggiMiscConfigHandle);
	if (err != GGI_OK) {
		fprintf(stderr,"LibGGIMisc: couldn't open %s\n",
			conffile);
		_ggiMiscLibIsUp--;
		free(conffile);
		return err;
	}
	free(conffile);

	_ggiMiscID = ggiExtensionRegister("GGIMISC", sizeof(ggiMiscpriv), changed);

	if (_ggiMiscID < 0) {
		fprintf(stderr,
			"LibGGIMisc: failed to register as extension.\n");
		_ggiMiscLibIsUp--;
		ggFreeConfig(_ggiMiscConfigHandle);
		return _ggiMiscID;
	}	/* if */

	_ggimiscInitBuiltins();

	return 0;
}	/* ggiMiscInit */


/* Deinitialize the extension
 */
int ggiMiscExit(void)
{
	int rc;

	if (!_ggiMiscLibIsUp) return GGI_ENOTALLOC;

	if (_ggiMiscLibIsUp > 1) {
		/* Exit only at last call */
		_ggiMiscLibIsUp--;
		return 0;
	}

	_ggimiscExitBuiltins();
	
	rc = ggiExtensionUnregister(_ggiMiscID);
	ggFreeConfig(_ggiMiscConfigHandle);
	_ggiMiscConfigHandle = NULL;

	_ggiMiscLibIsUp = 0;

	return rc;
}	/* ggiMiscExit */


/* Attach the extension to a visual
 */
int ggiMiscAttach(ggi_visual_t vis)
{
	int rc;

	DPRINT("LibGGIMisc: ggiMiscAttach(%p) called\n", vis);
	rc = ggiExtensionAttach(vis, _ggiMiscID);
	if (rc == 0) {
		/* We are actually creating the primary instance. */
		memset(LIBGGI_GGIMISCEXT(vis), 0, sizeof(ggiMiscpriv));

		/*-* Apply initial values */
		LIBGGI_GGIMISCEXT(vis)->priv = NULL;

		/* Now fake an "API change" so the right libs get loaded */
		changed(vis, GGI_CHG_APILIST);
	}	/* if */

	return rc;
}	/* ggiMiscAttach */


/* Detach the extension from a visual
 */
int ggiMiscDetach(ggi_visual_t vis)
{
	DPRINT("LibGGIMisc: ggiMiscDetach(%p) called\n", vis);
	return ggiExtensionDetach(vis, _ggiMiscID);
}	/* ggiMiscDetach */


/* This should be included by exactly _one_ file in each extension library. */
#include <ggi/internal/ggilibinit.h>
