/*
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 HAVE_CONFIG_H
#include <config.h>
#endif

#include <strings.h>
#include <locale.h>
#include <stdlib.h>
#include <unistd.h>
#include <X11/Intrinsic.h>
#include <X11/Shell.h>
#ifdef USE_IMP_MANAGER
#include "IMProtocolManager.hh"
#else
#include "XIMProtocol.hh"
#ifdef SUPPORT_R6IM
#include "R6IMProtocol.hh"
#endif
#endif
#include "IMArg.h"
#include "IMProtocol.hh"
#include "IMTriggerKeyList.hh"

#include "ResourceDB.hh"

#define SetArg(arg, n, d) ((void)( (arg).id = (n), (arg).value = (char*)(d) ))

static IMProtocol *ximp = 0;
#ifdef SUPPORT_R6IM
static IMProtocol *r6im = 0;
#endif

static XrmOptionDescRec rdb_options[] = {
   {(char*)"-if",	(char*)"*engineModule",	XrmoptionSepArg, 0},
   {(char*)"-port",	(char*)"*portNumber",		XrmoptionSepArg, 0},
   {(char*)"-ximp40",	(char*)"*ximp40",		XrmoptionNoArg, (XPointer)"true"},
   {(char*)"-iiimp",	(char*)"*iiimp",		XrmoptionNoArg, (XPointer)"true"},
   {(char*)"-fs",	(char*)"*fontSet",		XrmoptionSepArg, NULL},
   {(char*)"-lucbg",	(char*)"*lookupBackground",	XrmoptionSepArg, NULL},
   {(char*)"-staticEventFlow",	(char*)"*staticEventFlow", XrmoptionNoArg, (XPointer)"true"},
   {(char*)"-noProps", (char*)"*HttProps",		XrmoptionNoArg, (XPointer)"false"}
   /* -noProps option is only used for debugging purpose,
      and must not be a public interface. */
};

static char *
check_locale(int argc, char *argv[]) {
  int i;

  for (i = 1; i < argc; i++) {
    if(!strcmp(argv[i], "-lc_basiclocale"))
      return (argv[i+1]);
  }
  return (char *)"";
}

#if 0
static int
check_xsunim(int argc, char *argv[]) {
  int i;

  for (i = 1; i < argc; i++) {
    if(!strcmp(argv[i], "-use_xsunim"))
      return True;
  }
  return False;
}
#endif

void
initialize(int argc, char *argv[]) { 
  XtAppContext app = (XtAppContext)0;
  const char *class_name = "Iiimx";
  const char *app_name = "iiimx";

#ifdef USE_IMP_MANAGER
  ximp = IMProtocolManager::getInstance(IMProtocolManager::XIMP40);
#else
  ximp = new XIMProtocol(0, 0);
#endif
  if (!ximp) exit(1);

#ifdef SUPPORT_R6IM
#ifdef USE_IMP_MANAGER
  r6im = IMProtocolManager::getInstance(IMProtocolManager::R6IMP);
#else
  r6im = new R6IMProtocol(0, 0);
#endif
#endif

  // just workaround
#ifndef linux
  XInitThreads();
#endif

  setlocale(LC_ALL, check_locale(argc, argv));
  char *primary_locale = strdup(setlocale(LC_CTYPE, (char*)0));
  // strip modifier
  char *p = strchr(primary_locale, '@');
  if (p) *p = '\0';
  // strip encoding
  p = strchr(primary_locale, '.');
  if (p) *p = '\0';
  // strip territory. can we ?
  // p = strchr(primary_locale, '_');
  // if (p) *p = '\0';

  XSetLocaleModifiers("");

  Widget toplevel = XtOpenApplication(&app, class_name,
				      rdb_options,
				      XtNumber(rdb_options),
				      &argc, argv,
				      0, // fallback resources
				      applicationShellWidgetClass,
				      0, 0); // args and num_args
  int n;

  ResourceDB *resource = new ResourceDB(toplevel);

  char *trigger_keys = 0;
  IMTriggerKeyList key_list;
  Bool disable_status_area;
  Bool static_event_flow;

  char *if_name = 0;

  char *font_name = 0;
  n = 0;
  IMArg res[5];
  SetArg(res[n], ResourceDB::RDB_CONV_ON_KEY, &trigger_keys); n++;
  SetArg(res[n], ResourceDB::RDB_IF_NAME, &if_name); n++;
  SetArg(res[n], ResourceDB::RDB_FS_NAME, &font_name); n++;
  SetArg(res[n], ResourceDB::RDB_DISABLE_STATUS_AREA, &disable_status_area); n++;
  SetArg(res[n], ResourceDB::RDB_STATIC_EVENT_FLOW, &static_event_flow); n++;
  resource->getValues(res, n);

  if (trigger_keys) {
    if (!static_event_flow) {
      key_list.add(trigger_keys);
    }
    XtFree(trigger_keys);
  }

  // for XIMP initialization
  n = 0;
  IMArg args[15];
  SetArg(args[n], IMProtocol::ServerName, app_name); n++;
  SetArg(args[n], IMProtocol::VendorName, "Sun"); n++;
  SetArg(args[n], IMProtocol::PrimaryInputLocale, primary_locale); n++;
  SetArg(args[n], IMProtocol::ConversionOnKeys, &key_list); n++;
  SetArg(args[n], IMProtocol::DisplayConnection, XtDisplay(toplevel)); n++;
  if (if_name && if_name[0]) {
    SetArg(args[n], IMProtocol::IFName, if_name); n++;
  }
  if (font_name && font_name[0]) {
    SetArg(args[n], IMProtocol::DefaultFontName, font_name); n++;
  }
  SetArg(args[n], IMProtocol::AppName, "IIIMX XIM Server"); n++;
  SetArg(args[n], IMProtocol::DisableStatusArea, disable_status_area); n++;

  ximp->set_values(args, n);

#ifdef SUPPORT_R6IM
  // for X11R6 IMP initialization
  n = 0;
  Display *display2 = XOpenDisplay("");	// must be different from XIMP
  SetArg(args[n], IMProtocol::ServerName, app_name); n++;
  SetArg(args[n], IMProtocol::VendorName, "Sun"); n++;
  SetArg(args[n], IMProtocol::PrimaryInputLocale, primary_locale); n++;
  SetArg(args[n], IMProtocol::ConversionOnKeys, &key_list); n++;
  SetArg(args[n], IMProtocol::DisplayConnection, display2); n++;
  if (if_name && if_name[0]) {
    SetArg(args[n], IMProtocol::IFName, if_name); n++;
  }
  if (font_name && font_name[0]) {
    SetArg(args[n], IMProtocol::DefaultFontName, font_name); n++;
  }
  SetArg(args[n], IMProtocol::AppName, "IIIMX XIM Server"); n++;
  SetArg(args[n], IMProtocol::DisableStatusArea, disable_status_area); n++;

  const char *transport = "X/"; // use X
  SetArg(args[n], IMProtocol::TransportAddress, transport); n++;
  r6im->set_values(args, n);
#endif

  return;
}

void
run() {
#ifndef linux
  ximp->run();
#endif
#ifdef SUPPORT_R6IM
  r6im->run();
#endif
}

int
main(int argc, char *argv[]) {
  initialize(argc, argv);
  run();
  while(1) {
    sleep(10000000);
  }
  return 0;
}
