/* $Header: /mit/atdev/src/msgline/RCS/MessageLine.c,v 3.2 1991/05/21 17:28:21 dot Exp dot $ */

/*******************************************************************
  Copyright (C) 1990 by the Massachusetts Institute of Technology

   Export of this software from the United States of America is assumed
   to require a specific license from the United States Government.
   It is the responsibility of any person or organization contemplating
   export to obtain such a license before exporting.

WITHIN THAT CONSTRAINT, permission to use, copy, modify, and
distribute this software and its documentation for any purpose and
without fee is hereby granted, provided that the above copyright
notice appear in all copies and that both that copyright notice and
this permission notice appear in supporting documentation, and that
the name of M.I.T. not be used in advertising or publicity pertaining
to distribution of the software without specific, written prior
permission.  M.I.T. makes no representations about the suitability of
this software for any purpose.  It is provided "as is" without express
or implied warranty.

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

#include <Xm/Xm.h>
#include <stdio.h>

#ifdef _AtDevelopment_
#include "MessageLineP.h"
#else
#include <At/MessageLineP.h>
#endif
    
#define offset(field) XtOffset(AtMessageLineWidget, field)
static XtResource resources[] = {
    {
	XmNinputCallback, XmCCallback, XmRCallback,
	sizeof(XtCallbackList), offset(messageline.inputCallback),
	XmRPointer, (caddr_t) NULL
    },
};

    
static void EndInput(), CancelInput();
static void SaveCursorPosition(), RestoreCursorPosition();

static XtActionsRec MessageLine_actions[] = {
    {"end-input",               (XtActionProc)EndInput},
    {"cancel-input",            (XtActionProc)CancelInput},
    {"save-cursor-pos",         (XtActionProc)SaveCursorPosition},
    {"restore-cursor-pos",      (XtActionProc)RestoreCursorPosition},
};

static char MessageLine_translations[] = "\
	<Key>Return:		end-input()\n\
        Ctrl<Key>G:             cancel-input()\n\
        Ctrl<Key>C:             cancel-input()\n\
        ~Meta<Key>Escape:       cancel-input()\n\
	Ctrl<Key>D:		delete-next-character() \n\
	Meta<Key>D:		kill-next-word() \n\
	Ctrl<Key>K:		kill-to-end-of-line() \n\
	Ctrl<Key>W:		kill-selection() \n\
	Ctrl<Key>Y:		unkill() \n\
	Ctrl<Key>F:		forward-character() \n\
	Ctrl<Key>B:		backward-character() \n\
	Meta<Key>F:		forward-word() \n\
	Meta<Key>B:		backward-word() \n\
	Ctrl<Key>A:		beginning-of-line() \n\
	Ctrl<Key>E:		end-of-line() \n\
	Ctrl<Key>L:		redraw-display() \n\
        Shift<Key>Tab:		prev-tab-group() \n\
        Ctrl<Key>Tab:		next-tab-group() \n\
        <Key>Tab:		next-tab-group() \n\
        Ctrl<Key>Right:		forward-word()\n\
        Shift<Key>Right:	key-select(right)\n\
        Meta<Key>Right:	        key-select(right)\n\
	<Key>Right:		forward-character()\n\
	Ctrl<Key>Left:		backward-word()\n\
	Shift<Key>Left:		key-select(left)\n\
	Meta<Key>Left:		key-select(left)\n\
	<Key>Left:		backward-character()\n\
	Shift<Key>Delete:	delete-previous-word()\n\
	Meta<Key>Delete:	delete-previous-word()\n\
        <Key>Delete:            delete-previous-character()\n\
        Shift<Key>BackSpace:	delete-previous-word()\n\
	<Key>BackSpace:		delete-previous-character()\n\
	~Ctrl <Key>:		self-insert()\n\
        ~Meta <Btn1Down>:      save-cursor-pos() grab-focus() select-start()\n\
        ~Meta <Btn1Motion>:     extend-adjust()\n\
        ~Meta <Btn1Up>:         extend-end() restore-cursor-pos()\n\
        ~Meta <Btn3Down>:       save-cursor-pos() extend-start()\n\
        ~Meta <Btn3Motion>:     extend-adjust()\n\
        ~Meta <Btn3Up>:         extend-end() restore-cursor-pos()\n\
        ~Meta <Btn2Up>:         stuff()\n\
        <LeaveWindow>:		leave()\n\
        <FocusIn>:		focusIn()\n\
        <FocusOut>:		focusOut()\n\
	<Unmap>:		unmap()";


static void Initialize();	
    
AtMessageLineClassRec atMessageLineClassRec = {
  {
/* core_class fields */	
    /* superclass	  */	(WidgetClass) &xmTextClassRec,
    /* class_name	  */	"AtMessageLine",
    /* widget_size	  */	sizeof(AtMessageLineRec),
    /* class_initialize   */    NULL,
    /* class_part_initiali*/	NULL,
    /* class_inited       */	FALSE,
    /* initialize	  */	Initialize,
    /* initialize_hook    */	NULL,
    /* realize		  */	XtInheritRealize,
    /* actions		  */    MessageLine_actions,
    /* num_actions	  */	XtNumber(MessageLine_actions),
    /* resources	  */	resources,
    /* num_resources	  */	XtNumber(resources),
    /* xrm_class	  */	NULLQUARK,
    /* compress_motion	  */	TRUE,
    /* compress_exposure  */	TRUE,
    /* compress_enterleave*/	TRUE,
    /* visible_interest	  */	FALSE,
    /* destroy		  */    NULL,
    /* resize		  */	XtInheritResize,
    /* expose		  */	XtInheritExpose,
    /* set_values	  */	NULL,
    /* set_values_hook	  */	NULL,
    /* set_values_almost  */	XtInheritSetValuesAlmost,
    /* get_values_hook    */	NULL,
    /* accept_focus	  */	NULL,
    /* version		  */	XtVersion,
    /* callback_private   */	NULL,
    /* tm_table		  */	MessageLine_translations,
    /* query_geometry     */    NULL,
    /* display accel	  */	XtInheritDisplayAccelerator,
    /* extension	  */	NULL,
  },

   {				/* primitive_class fields 	*/
      _XtInherit,   		/* Primitive border_highlight   */
      _XtInherit,   		/* Primitive border_unhighlight */
      NULL,         		/* translations                 */
      NULL,         		/* arm_and_activate           	*/
      NULL,  	    	        /* get resources 	        */
      0,	                /* num get_resources            */
      NULL,         		/* extension                    */
   },

   {				/* text class fields */
      NULL,             	/* extension         */
   },
   {                            /* MessageLine class field */
      NULL,                     /* unused */
   }
};

WidgetClass atMessageLineWidgetClass = (WidgetClass) &atMessageLineClassRec;
     
static void VerifyCursorMotion(w,tag,client_data)
     AtMessageLineWidget w;
     caddr_t tag;
     XmTextVerifyCallbackStruct *client_data;
{
  Arg a;
  
  if (client_data->newInsert < w->messageline.inputpos) {
    client_data->doit = FALSE;
    XtSetArg(a,XmNcursorPosition,w->messageline.inputpos);
    XtSetValues(w,&a,1);
  }
}


static void VerifyModify(w,tag,client_data)
     AtMessageLineWidget w;
     caddr_t tag;
     XmTextVerifyCallbackStruct *client_data;
{
  if (client_data->startPos < w->messageline.inputpos) {
    client_data->doit = FALSE;
  }
}


static XmTextPosition SavedCursorPosition = -1;

static void SaveCursorPosition(w)
     AtMessageLineWidget w;
{
  if (SavedCursorPosition == -1) {
    SavedCursorPosition = XmTextGetInsertionPosition((Widget)w);
    XtRemoveCallback(w,XmNmotionVerifyCallback,VerifyCursorMotion,NULL);
    XtRemoveCallback(w,XmNmodifyVerifyCallback,VerifyModify,NULL);
  }
}

static void RestoreCursorPosition(w)
     AtMessageLineWidget w;
{
  if (SavedCursorPosition != -1) {
    XtAddCallback(w,XmNmotionVerifyCallback,VerifyCursorMotion,NULL);
    XtAddCallback(w,XmNmodifyVerifyCallback,VerifyModify,NULL);
    XmTextSetInsertionPosition((Widget)w,SavedCursorPosition);
    SavedCursorPosition = -1;
  }
}


static void EndInput(w, event, params, num_params)
     AtMessageLineWidget w;
     XEvent *event;
     String *params;
     Cardinal *num_params;     
{
  if (w->messageline.doing_sync_input == True)
    longjmp(w->messageline.mark,1);
  else {
    char *buf, s[512];
    buf = XmTextGetString((Widget)w);
    strncpy(s,&buf[w->messageline.inputpos],511);
    XtFree(buf);
    XmTextSetString((Widget)w,"");
    w->messageline.inputpos = 0;
    XtCallCallbacks(w,XmNinputCallback,s);
  }
}

static void CancelInput(w, event, params, num_params)
     AtMessageLineWidget w;
     XEvent *event;
     String *params;
     Cardinal *num_params;
{
  if (w->messageline.doing_sync_input == True)
    longjmp(w->messageline.mark, 2);
}

static void Initialize(request, new) 
     AtMessageLineWidget request, new;
{
  Arg al[10];
  int ac;
  
  new->messageline.inputpos = XmTextGetLastPosition((Widget)new);
  new->messageline.doing_sync_input = False;
  XtAddCallback(new,XmNmotionVerifyCallback,VerifyCursorMotion,NULL);
  XtAddCallback(new,XmNmodifyVerifyCallback,VerifyModify,NULL);
  
  ac = 0;
  XtSetArg(al[ac], XmNcursorPositionVisible, True); ac++;
  XtSetValues(new,al,ac);
}

void AtMessageLineClear(AtMessageLineWidget w)
{
  XmTextSetString((Widget)w, "");
  w->messageline.inputpos = 0;
  XFlush(XtDisplay(w));
}

void AtMessageLineSet(AtMessageLineWidget w,char *s)
{
  XmTextSetString((Widget)w, s);
  w->messageline.inputpos = strlen(s);
  XmTextShowPosition((Widget)w,XmTextGetLastPosition((Widget)w));    
  XFlush(XtDisplay(w));
}

void AtMessageLineAppend(AtMessageLineWidget w,char *s)
{
  XmTextReplace((Widget)w, w->messageline.inputpos, w->messageline.inputpos, s);
  w->messageline.inputpos += strlen(s);
  XmTextShowPosition((Widget)w,XmTextGetLastPosition((Widget)w));    
  XFlush(XtDisplay(w));
}

Boolean AtMessageLineGetString(AtMessageLineWidget w, char *buffer, int bufsize)
{
  int status;
  Boolean valid;
  char *buf;
    
  w->messageline.doing_sync_input = True;
  XmTextSetEditable((Widget)w,True);
  XtAddGrab(w, True, False);
  status = setjmp(w->messageline.mark);    
  
  switch (status) {
  case 0:
    XtMainLoop();
  case 1:
    buf = XmTextGetString((Widget)w);
    strncpy(buffer,&buf[w->messageline.inputpos],bufsize);
    XtFree(buf);
    valid = True;
    break;
  case 2:
    valid = False;
    break;
  }

  XmTextSetString((Widget)w,"");
  w->messageline.inputpos = 0;
  XmTextSetEditable((Widget)w,False);
  w->messageline.doing_sync_input = False;
  XtRemoveGrab(w);
  return (valid);
}
