/*
  Copyright 1990-2001 Sun Microsystems, Inc. All Rights Reserved.

  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 OPEN GROUP OR SUN MICROSYSTEMS, INC. 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 EVEN IF
  ADVISED IN ADVANCE OF THE POSSIBILITY OF SUCH DAMAGES.


  Except as contained in this notice, the names of The Open Group and/or
  Sun Microsystems, Inc. shall not be used in advertising or otherwise to
  promote the sale, use or other dealings in this Software without prior
  written authorization from The Open Group and/or Sun Microsystems,
  Inc., as applicable.


  X Window System is a trademark of The Open Group

  OSF/1, OSF/Motif and Motif are registered trademarks, and OSF, the OSF
  logo, LBX, X Window System, and Xinerama are trademarks of the Open
  Group. All other trademarks and registered trademarks mentioned herein
  are the property of their respective owners. No right, title or
  interest in or to any trademark, service mark, logo or trade name of
  Sun Microsystems, Inc. or its licensors is granted.

*/
#ifdef	WIN32
#include <windows.h>
#endif

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

#ifdef	sun
#include <sys/types.h>
#include <sys/stat.h>
#endif

#ifndef	WIN32
#include <unistd.h>
#include <dlfcn.h>
#endif

#include "SunIM.h"

#ifdef ENABLE_EIMIL
#define IFPATH_ENV "CURRENT_IFPATH"
#endif

Public iml_methods_t *_iml_dup_iml_methods();

#ifdef	sun
int is_cm_available(char *locale);
int is_engine_available(char *locale, char *engine);
#endif

Private void *open_le_module(char *);
Public void close_le_module(void *);
Private Bool get_ifinfo(const char*, iml_if_t *, void *);

#ifdef _POSIX_PATH_MAX
#define PATHNAME_MAX _POSIX_PATH_MAX
#else
#define PATHNAME_MAX 1024
#endif

#define	PROCNAME	"if_GetIfInfo"
#define	HOTKEY_PROCNAME	"if_GetHotKeyInfo"

#define	OPENWINHOME		"/usr/openwin"

#ifdef	USE_XSUNIM_ADAPTER
#define	XSUNIMADAPTER_MODULE	"xsunimadapter"
#define	XSUNIMADAPTER_METHOD	"xsunim_methods"
static void *dl_module_xsunimadapter = 0;
#endif

#ifdef	USE_SUNIM_ADAPTER
#ifndef	WIN32
static void *dl_module_sunimadapter = 0;
#define	SUNIMADAPTER_MODULE	"sunimadapter"
#define	SUNIMADAPTER_METHOD	"sunim_methods"
#endif
#endif	/* USE_SUNIM_ADAPTER */

extern if_methods_t sunim_default_methods;

Private void *
open_le_module(
	       char *if_path
	       )
{
#ifndef	WIN32
  void *pr;
  char *perr;
  if (access(if_path, F_OK) == -1) {
    return (void *) 0;
  }
  pr = dlopen(if_path, RTLD_LAZY);
  if (!pr) {
    perr = dlerror();
    if (perr) fprintf(stderr, "dlopen() failed:%s\n", perr);
  }
  return pr;
#else
  return (void *) LoadLibrary(if_path);
#endif
}

Public void
close_le_module(void *module)
{
#ifndef	WIN32
  if(module && dlclose((void*)module) != 0){
    fprintf(stderr, dlerror());
    fprintf(stderr, "\n");
  }
#else
  FreeLibrary((HINSTANCE) module);
#endif
}

Private Bool
get_ifinfo(
	   const char *iiimf_home,
	   iml_if_t * If,
	   void *module
	   )
{
  void *(*get_le_info) ();
  IMHotkeyManagerStruct *(*get_hotkey_info) (IMLEName*);
  int count;
  int if_version_idx, if_lename_idx, if_locales_idx, if_objects_idx;
  int if_methods_idx, if_thread_lock_idx;
#ifdef USE_SUNIM_ADAPTER
  int if_locale_dependency_idx;
#endif
#ifdef ENABLE_EIMIL
  int if_EIMIL_handle_idx;
#endif
  IMArg p[9] ; /* XXX FIXME Magic number */
    
#ifndef	WIN32
  get_le_info = (void *(*) ()) dlsym(module, PROCNAME);
#else
  get_le_info = (void *(*) ()) GetProcAddress((HINSTANCE) module, TEXT(PROCNAME));
#endif
    
  if (get_le_info == NULL) {
    return False;
  }
  count = 0;
  IMSetArg(p[count], IF_VERSION, NULL); if_version_idx = count++;
  IMSetArg(p[count], IF_LE_NAME, NULL); if_lename_idx = count++;
  IMSetArg(p[count], IF_SUPPORTED_LOCALES, NULL); if_locales_idx = count++;
  IMSetArg(p[count], IF_SUPPORTED_OBJECTS, NULL); if_objects_idx = count++;
  IMSetArg(p[count], IF_METHOD_TABLE, NULL); if_methods_idx = count++;
  IMSetArg(p[count], IF_NEED_THREAD_LOCK, NULL); if_thread_lock_idx = count++;
#ifdef	USE_SUNIM_ADAPTER
  IMSetArg(p[count], IF_HAVE_LOCALE_DEPENDENCY, NULL);
  if_locale_dependency_idx = count++;
#endif
#ifdef ENABLE_EIMIL
  IMSetArg(p[count], IF_EIMIL_HANDLE, EIMIL_VOID_HANDLE);
  if_EIMIL_handle_idx = count++;
  setenv(IFPATH_ENV, iiimf_home, 1);
#endif
  (*get_le_info) (p, count);
    
  If->if_version = (char *) p[if_version_idx].value;
  If->ifm = (if_methods_t *) p[if_methods_idx].value;
  If->lename = (IMLEName *) p[if_lename_idx].value;
  If->locale_list = (IMLocale *) p[if_locales_idx].value;
  If->object_list = (IMObjectDescriptorStruct *) p[if_objects_idx].value;
  If->need_thread_lock = (Bool) p[if_thread_lock_idx].value;

  /* hotkey infomation */
  get_hotkey_info = (void *(*) ()) dlsym(module, HOTKEY_PROCNAME);
  if (get_hotkey_info) {
    If->hkm = (*get_hotkey_info)(If->lename);
  } else
    If->hkm = NULL;
  
#ifdef	USE_SUNIM_ADAPTER
#ifndef	WIN32
  If->need_adapter = (Bool) p[if_locale_dependency_idx].value;
  if (If->need_adapter == True) {
    If->need_thread_lock = True;
  }
#else
  If->need_adapter = False;
#endif
#endif /* USE_SUNIM_ADAPTER */

#ifdef ENABLE_EIMIL
  If->eh = (EIMIL_handle) p[if_EIMIL_handle_idx].value;
#endif

  if (!If->ifm || !If->lename || !If->locale_list) {
    return False;
  }
  return True;
}


Public Bool
if_configure(
	     iml_if_t * If,
	     const char *iiimf_home,
	     const char *if_name,
	     const char *locale_,
	     Bool call_openif
	     )
{
  const char *locale = locale_;
  char if_path[PATHNAME_MAX];
    
  void *if_so = (void *) NULL;
  If->xsunim = False;

  /* If OpenDesktop() fails, use this default engine */
  if(!strcmp(if_name, "sunim_default")){
    If->ifm = &sunim_default_methods;
    goto sunim_default;
  }

#ifndef	WIN32
  sprintf(if_path, "%s/%s.so", iiimf_home, if_name);
    
  if_so = open_le_module(if_path);
    
  if (if_so) {
    if (get_ifinfo(iiimf_home, If, if_so) == False) {
      fprintf(stderr, "if_configure: get_method_table() failed\n");
      close_le_module(if_so);
      if_so = NULL;
    } else {
#ifdef	USE_SUNIM_ADAPTER
      if (If->need_adapter == True && call_openif == True) {
	if (dl_module_sunimadapter == 0) {
	  sprintf(if_path, "%s/%s.so", iiimf_home, SUNIMADAPTER_MODULE);
	  dl_module_sunimadapter = open_le_module(if_path);
	}
	if (dl_module_sunimadapter) {
	  If->ifm = (if_methods_t *) dlsym(dl_module_sunimadapter, SUNIMADAPTER_METHOD);
	}
      }
#endif /* SUNIM_ADAPTER */
    }
  }

#ifdef USE_XSUNIM_ADAPTER
  if (if_so == NULL) {
    sprintf(if_path, "%s/lib/locale/%s/xim/%s.so", OPENWINHOME, locale, if_name);
    if (!access(if_path, F_OK)) {
      If->xsunim = True;
    } else {
      sprintf(if_path, "%s/lib/locale/common/xim/%s.so", OPENWINHOME, if_name);
      if (!access(if_path, F_OK)) {
	If->xsunim = True;
      }
    }
    if (If->xsunim == True) {
      if (dl_module_xsunimadapter == 0) {
	sprintf(if_path, "%s/%s.so", iiimf_home, XSUNIMADAPTER_MODULE);
	dl_module_xsunimadapter = open_le_module(if_path);
      }
      if (dl_module_xsunimadapter) {
	If->ifm = (if_methods_t *) dlsym(dl_module_xsunimadapter, XSUNIMADAPTER_METHOD);
	If->lename = (IMLEName *) 0;
	If->locale_list = (IMLocale *) 0;
	If->object_list = (IMObjectDescriptorStruct *) 0;
	If->hkm = (IMHotkeyManagerStruct *) 0;
	If->need_thread_lock = True;
      }
    }
  }
#endif
    
  If->dl_module = if_so;
#else /* WIN32 */
  sprintf(if_path, "%s\\%s.dll", iiimf_home, if_name);
  if_so = open_le_module(if_path);
  if (if_so) {
    get_ifinfo(iiimf_home, If, if_so);
    if (If->ifm == NULL) {
#ifdef	DEBUG
      printf("if_configure: get_method_table() failed\n");
#endif
      close_le_module(if_so);
      if_so = NULL;
    }
  } else {
    printf("open_le_module failed\n");
  }
#endif /* WIN32 */
    
  if (!If->ifm) {
    fprintf(stderr, "Fatal error in dynamic LE i/f loader -  A library is missing in your system. Please call your system administrator.\n");
    If->ifm = &sunim_default_methods;
  }

 sunim_default:
  If->locale = strdup(locale);
  If->if_name = strdup(if_name);
  If->ifpath_name = strdup(iiimf_home);
  If->m = _iml_dup_iml_methods();
#ifdef	DEBUG
  printf("try to call if_OpenIF() with locale=%s if_name=%s if_path=%s\n",
	 If->locale, If->if_name, if_path);
#endif

  if (call_openif == True) {
    if (If->ifm->if_OpenIF(If) == False) {
      If->ifm = &sunim_default_methods;
      If->ifm->if_OpenIF(If);
    }
  }
  return True;
}

#ifdef  sun
is_cm_available(
		char *locale
		)
{
  struct stat buf;
  char path[256];
  sprintf(path, "/usr/openwin/lib/locale/%s/xim/cm.so", locale);
  if (access(path, F_OK) == -1) {
    sprintf(path, "/usr/openwin/lib/locale/common/xim/cm.so");
    if (access(path, F_OK) == -1) {
      return 0;
    }
  }
  sprintf(path, "/usr/lib/mle/%s/mle.so", locale);
  if (access(path, F_OK) == -1) {
    return 0;
  }
  sprintf(path, "/usr/lib/locale/%s/", locale);
  if ((stat(path, &buf) < 0) || !((buf.st_mode & S_IFMT) == S_IFDIR)) {
    return 0;
  }
  return 1;
}

is_engine_available(
		    char *locale,
		    char *engine
		    )
{
  struct stat buf;
  char path[256];
  sprintf(path, "/usr/openwin/lib/locale/%s/xim/%s.so", locale,engine);
  if (access(path, F_OK) == -1) {
    return 0;
  }
  sprintf(path, "/usr/lib/locale/%s/", locale);
  if ((stat(path, &buf) < 0) || !((buf.st_mode & S_IFMT) == S_IFDIR)) {
    return 0;
  }
  return 1;
}
#endif
