//********
//
// cx.c
//
//********

//******** Header files
#include <libraries/commodities.h>
#include <dos/dos.h>
#include <clib/exec_protos.h>
#include <clib/commodities_protos.h>
#include <clib/alib_protos.h>
#include <pragmas/exec_pragmas.h>
#include <pragmas/commodities_pragmas.h>

#include "Librarian.h"
#include "Prefs.h"
#include "cx.h"
#include "TDEBUG.H"


//******** Local Storage

extern UBYTE VersTag[];

struct NewBroker nb = {
  NB_VERSION,
  ONGONAME,
  &VersTag[7],
  "Cool workbench enhancer",
  NBU_UNIQUE | NBU_NOTIFY,
  COF_SHOW_HIDE,
  0,
  NULL,
  0
};
struct MsgPort *CX_Port=NULL;
CxObj *broker=NULL;



//******** Public functions

static void __saveds CxFollowMouse(register CxMsg *cxm, CxObj *co) {
  struct InputEvent *ie;

  ie=(struct InputEvent *)CxMsgData(cxm);

  if (ie->ie_Class==IECLASS_RAWMOUSE) {
    if (ie->ie_Qualifier & IEQUALIFIER_RELATIVEMOUSE) {
      DivertCxMsg(cxm, co, co);
    }
  }
} // CxFollowMouse


//******** Public functions

BOOL MyBeginCX(void) {
  BOOL rc=FALSE;
  CxObj *co;
  CxObj *co2;
  int i;

  if (CX_Port=CreateMsgPort()) {
    nb.nb_Pri  = my_cx_pri;
    nb.nb_Port = CX_Port;
    if (broker = CxBroker(&nb, NULL)) {
      ActivateCxObj(broker, 1L);
      for (i=0 ; i<NumVScreens+2; i++)
	if (co=HotKey(MyHotKey[i],CX_Port,i))
	  AttachCxObj(broker,co);
	if (AutoHide==1) {
	  if (co=CxCustom(CxFollowMouse,0L)) {
	    AttachCxObj(broker,co);
	    if (co2=CxSignal(FindTask(NULL),SIGBREAKB_CTRL_F)) {
	      AttachCxObj(co,co2);
	    } else {
	      DPRINT("CX: CxSender failed!\n",0);
	    }
	  } else {
	    DPRINT("CX: CxCustom failed!\n",0);
	  }
	} // if AutoHide
      rc=TRUE;
    } else {
      DPRINT("CX: CxBroker() failed\n",0);
      MyEndCX();
    }
  } else {
    DPRINT("CX: CreateMsgPort() failed\n",0);
  }

  return rc;
} // MyBeginCX


void MyEndCX(void) {
  struct Message *msg;

  if (broker) {
    ActivateCxObj(broker, 0L);
    DeleteCxObjAll(broker);
    broker=NULL;
  } // if CreateBroker

  if (CX_Port) {
    while (msg=GetMsg(CX_Port)) ReplyMsg((struct Message *)msg);
    DeleteMsgPort(CX_Port);
    CX_Port=NULL;
  }
} // MyEndCX

//******** End of file
