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

   Wmh extension initialization.

   Copyright (C) 1999 Andreas Beck	[becka@ggi-project.org]
   Copyright (C) 1999 Marcus Sundberg	[marcus@ggi-project.org]
  
   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 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/internal/wmh.h>
#include <ggi/internal/wmh_debug.h>

#include <ggi/internal/gg_replace.h>	/* for snprintf() */


/* Exported variables
 */

uint32_t _wmhDebug = 0;

/* Static variables 
 */

static int 	 _WmhLibIsUp=0;
static void	*_WmhConfigHandle;
static char      _Wmhconfstub[512]=WMHCONFDIR;
static char     *_Wmhconfdir=_Wmhconfstub+WMHTAGLEN;

/* Extension ID. Defaulting to -1 should make segfault on abuse more likely...
 */
ggi_extid _WmhID = -1;


#define SUBLIB_PREFIX  "WMHdl_"



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

const char *ggiWmhGetConfDir(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 _Wmhconfdir;
}


/* Dummy function which returns GGI_ENOFUNC
   We use this to reset the function pointers */
static int dummyfunc(void)
{
	return GGI_ENOFUNC;
}	/* dummyfunc */

/*-* Reset all function pointers to dummyfunc */
static void clearfuncs(wmhpriv *priv)
{
	priv->move		= (ggiwmhfunc_move *) dummyfunc;
	priv->resize		= (ggiwmhfunc_resize *) dummyfunc;
	priv->getpos		= (ggiwmhfunc_getpos *) dummyfunc;
	priv->getsize		= (ggiwmhfunc_getsize *) dummyfunc;
	priv->maximize		= (ggiwmhfunc_maximize *) dummyfunc;
	priv->moveicon		= (ggiwmhfunc_moveicon *) dummyfunc;
	priv->settitle		= (ggiwmhfunc_settitle *) dummyfunc;
	priv->seticontitle	= (ggiwmhfunc_seticontitle *) dummyfunc;
	priv->zorder		= (ggiwmhfunc_zorder *) dummyfunc;
	priv->iconify		= (ggiwmhfunc_iconify *) dummyfunc;
	priv->allowresize	= (ggiwmhfunc_allowresize *) dummyfunc;
}	/* clearfuncs */


static int changed(ggi_visual_t vis,int whatchanged)
{
	DPRINT("changed(%p, %i) called for wmh extension\n",
		  vis, whatchanged);

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

		DPRINT("changed() APILIST \n");

		clearfuncs(LIBGGI_WMHEXT(vis));

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

			lib = ggiExtensionLoadDL(vis, _WmhConfigHandle,
						api, args, NULL, SUBLIB_PREFIX);
			if (lib != NULL) break;
		}

	}
	break;
	}	/* switch */


	return 0;
}	/* changed */



void _ggiwmhInitBuiltins(void);
void _ggiwmhExitBuiltins(void);


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

	_WmhLibIsUp++;
	if (_WmhLibIsUp > 1) return 0; /* Initialize only at first call. */
	
	str = getenv("WMH_DEBUGSYNC");
        if (str != NULL) {
                _wmhDebug |= DEBUG_SYNC;
        }
	
        str = getenv("WMH_DEBUG");
        if (str != NULL) {
                _wmhDebug |= atoi(str) & DEBUG_ALL;
                DPRINT_CORE("%s Debugging=%d\n",
                            DEBUG_ISSYNC ? "sync" : "async",
                            _wmhDebug);
        }
	
	confdir = ggiWmhGetConfDir();
	conffile = malloc(strlen(confdir) + 1 + strlen(WMHCONFFILE)+1);
	if (!conffile) {
		fprintf(stderr, "LibWMH: unable to allocate memory for config filename.\n");
		_WmhLibIsUp--;
		return GGI_ENOMEM;
	}
	snprintf(conffile, strlen(confdir) + strlen(WMHCONFFILE) + 2,
		"%s/%s", confdir, WMHCONFFILE);

	err = ggLoadConfig(conffile, &_WmhConfigHandle);
	if (err != GGI_OK) {
		fprintf(stderr,"LibWMH: couldn't open %s\n",
			conffile);
		_WmhLibIsUp--;
		free(conffile);
		return err;
	}
	free(conffile);

	_WmhID = ggiExtensionRegister("WMH", sizeof(wmhpriv), changed);

	if (_WmhID < 0) {
		fprintf(stderr,
			"LibWMH: failed to register as extension.\n");
		_WmhLibIsUp--;
		ggFreeConfig(_WmhConfigHandle);
		return _WmhID;
	}	/* if */

	_ggiwmhInitBuiltins();

	return 0;
}	/* ggiWmhInit */


/* Deinitialize the extension
 */
int ggiWmhExit(void)
{
	int rc;
    
	if (!_WmhLibIsUp) return GGI_ENOTALLOC;

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

	_ggiwmhExitBuiltins();
	
	rc = ggiExtensionUnregister(_WmhID);
	ggFreeConfig(_WmhConfigHandle);
	_WmhConfigHandle = NULL;

	_WmhLibIsUp = 0;

	return rc;
}	/* ggiWmhExit */



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

	rc = ggiExtensionAttach(vis, _WmhID);
	if (rc < 0) {
		DPRINT_CORE("Failed to attach myself to this visual.\n");
		goto err0;
	}	/* if */

	if (rc != 0) return rc;

	rc = 0;

	/* We are actually creating the primary instance. */
	memset(LIBGGI_WMHEXT(vis), 0, sizeof(wmhpriv));
                        
	/* Now fake an "API change" so the right libs get loaded */
	changed(vis, GGI_CHG_APILIST);

	return rc;

err0:
	return rc;
}	/* ggiWmhAttach */


/* Detach the extension from a visual
 */
int ggiWmhDetach(ggi_visual_t vis)
{
	return ggiExtensionDetach(vis, _WmhID);
}	/* ggiWmhDetach */
