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

   LIBGCP: extension initialization.

   Copyright (C) 2000-2001 Christoph Egger	[Christoph_Egger@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 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/gcp.h>
#include <ggi/internal/gcp_debug.h>

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


/* Static variables 
 */
static int 	 _gcpLibIsUp       = 0;
static void	*_gcpConfigHandle  = NULL;
static char      _gcpconfstub[512] = GCPCONFDIR;
static char     *_gcpconfdir       = _gcpconfstub+GCPTAGLEN;

uint32_t _gcpDebug = 0;

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

#define SUBLIB_PREFIX	"GCPdl_"


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

const char *gcpGetConfDir(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 _gcpconfdir;
}


/* Dummy function which returns -1
   We use this to reset the function pointers */
static int dummyfunc(void)
{
	DPRINT_CORE("dummyfunc() of LibGCP called\n");

	return GGI_ENOFUNC;
}	/* dummyfunc */



/* Reset all function pointers to dummyfunc */
static void clearfuncs(gcppriv *priv)
{
        /* Color palette manipulation
         */

        /* RGBA */
	priv->MapRGBAColor = (void *) dummyfunc;
	priv->UnmapRGBAPixel = (void *) dummyfunc;

	priv->PackRGBAColors = (void *) dummyfunc;
	priv->UnpackRGBAPixels = (void *) dummyfunc;
	priv->GetRGBAPalette = (void *) dummyfunc;
	priv->SetRGBAPalette = (void *) dummyfunc;


        /* YUV */
	priv->MapYUVColor = (void *) dummyfunc;
	priv->UnmapYUVPixel = (void *) dummyfunc;

	priv->PackYUVColors = (void *) dummyfunc;
	priv->UnpackYUVPixels = (void *) dummyfunc;

	priv->GetYUVPalette = (void *) dummyfunc;
	priv->SetYUVPalette = (void *) dummyfunc;


        /* CMYK */
	priv->MapCMYKColor = (void *) dummyfunc;
	priv->UnmapCMYKPixel = (void *) dummyfunc;

	priv->PackCMYKColors = (void *) dummyfunc;
	priv->UnpackCMYKPixels = (void *) dummyfunc;

	priv->GetCMYKPalette = (void *) dummyfunc;
	priv->SetCMYKPalette = (void *) dummyfunc;


        /* HSV */
	priv->MapHSVColor = (void *) dummyfunc;
	priv->UnmapHSVPixel = (void *) dummyfunc;

	priv->PackHSVColors = (void *) dummyfunc;
	priv->UnpackHSVPixels = (void *) dummyfunc;

	priv->GetHSVPalette = (void *) dummyfunc;
	priv->SetHSVPalette = (void *) dummyfunc;


	/* Kodak PhotoCD */
	priv->MapYCCColor = (void *) dummyfunc;
	priv->UnmapYCCPixel = (void *) dummyfunc;

	priv->PackYCCColors = (void *) dummyfunc;
	priv->UnpackYCCPixels = (void *) dummyfunc;

	priv->GetYCCPalette = (void *) dummyfunc;
	priv->SetYCCPalette = (void *) dummyfunc;



        /* Gamma map manipulation
         */

        /* RGBA */
	priv->GetRGBAGamma = (void *) dummyfunc;
	priv->SetRGBAGamma = (void *) dummyfunc;

	priv->GetRGBAGammaMap = (void *) dummyfunc;
	priv->SetRGBAGammaMap = (void *) dummyfunc;


        /* YUV */
	priv->GetYUVGamma = (void *) dummyfunc;
	priv->SetYUVGamma = (void *) dummyfunc;

	priv->GetYUVGammaMap = (void *) dummyfunc;
	priv->SetYUVGammaMap = (void *) dummyfunc;


        /* CMYK */
	priv->GetCMYKGamma = (void *) dummyfunc;
	priv->SetCMYKGamma = (void *) dummyfunc;

	priv->GetCMYKGammaMap = (void *) dummyfunc;
	priv->SetCMYKGammaMap = (void *) dummyfunc;


        /* HSV */
	priv->GetHSVGamma = (void *) dummyfunc;
	priv->SetHSVGamma = (void *) dummyfunc;

	priv->GetHSVGammaMap = (void *) dummyfunc;
	priv->SetHSVGammaMap = (void *) dummyfunc;


        /* Kodak PhotoCD */
	priv->GetYCCGamma = (void *) dummyfunc;
	priv->SetYCCGamma = (void *) dummyfunc;

	priv->GetYCCGammaMap = (void *) dummyfunc;
	priv->SetYCCGammaMap = (void *) dummyfunc;



        /* Blending manipulation
         */

        /* Color blending */
	priv->BlendColor = (void *) dummyfunc;


	/* Luminance manipulation
	 */
	priv->GetLuminance = (void *) dummyfunc;


	/* Lightness manipulation
	 */

	priv->SetIntensity = (void *) dummyfunc;
	priv->GetIntensity = (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 LibGCP 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_GCPEXT(vis));

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

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

	return 0;
}	/* changed */



void _ggigcpInitBuiltins(void);
void _ggigcpExitBuiltins(void);


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

	_gcpLibIsUp++;
	if (_gcpLibIsUp > 1) return 0; /* Initialize only at first call. */
	
	str = getenv("GCP_DEBUGSYNC");
        if (str != NULL) {
                _gcpDebug |= DEBUG_SYNC;
        }
	
        str = getenv("GCP_DEBUG");
        if (str != NULL) {
                _gcpDebug |= atoi(str) & DEBUG_ALL;
                DPRINT_CORE("%s Debugging=%d\n",
                            DEBUG_ISSYNC ? "sync" : "async",
                            _gcpDebug);
        }
	
	confdir = gcpGetConfDir();
	conffile = malloc(strlen(confdir) + 1 + strlen(GCPCONFFILE)+1);
	if (!conffile) {
		fprintf(stderr, "LibGCP: unable to allocate memory for config filename.\n");
		_gcpLibIsUp--;
		return GGI_ENOMEM;
	}

	snprintf(conffile, strlen(confdir) + strlen(GCPCONFFILE) + 2,
		"%s/%s", confdir, GCPCONFFILE);

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


	_gcpID = ggiExtensionRegister("GCP", sizeof(gcppriv), changed);

	if (_gcpID < 0) {
		fprintf(stderr,
			"LibGCP: failed to register as extension.\n");
		_gcpLibIsUp--;
		ggFreeConfig(_gcpConfigHandle);
		_gcpConfigHandle = NULL;
		return _gcpID;
	}	/* if */

	_ggigcpInitBuiltins();

	return 0;
}	/* gcpInit */



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

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

	rc = ggiExtensionUnregister(_gcpID);
	ggFreeConfig(_gcpConfigHandle);
	_gcpConfigHandle = NULL;

	_gcpLibIsUp = 0;

	return rc;
}	/* gcpExit */



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

	DPRINT_CORE("gcpAttach(%p) called\n", vis);

	rc = ggiExtensionAttach(vis, _gcpID);
	if (rc == 0) {
		/* We are actually creating the primary instance. */
		memset(LIBGGI_GCPEXT(vis), 0, sizeof(gcppriv));
		LIBGGI_GCPEXT(vis)->priv = NULL;

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

	return rc;
}	/* gcpAttach */



/* Detach the extension from a visual
 */
int gcpDetach(ggi_visual_t vis)
{
	DPRINT_CORE("gcpDetach(%p) called\n", vis);

	return ggiExtensionDetach(vis, _gcpID);
}	/* gcpDetach */


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