/* AttachMenu.c */

#include <stdlib.h>

#include "DeskLib:Wimp.h"
#include "DeskLib:WimpSWIs.h"
#include "DeskLib:Event.h"
#include "DeskLib:EventMsg.h"
#include "DeskLib:Menu.h"

#include "AttachMenu.h"

Menu_Attachment *_CurrentMenu;

void AttachMenu_Initialise(void)
{
  Event_Claim(event_MENU,event_ANY,event_ANY,Attachment_Select,0);
  EventMsg_Claim(message_MENUWARNING,event_ANY,Attachment_Warn,0);
}

Menu_Attachment *Event_AttachMenu(window_handle w,menu_ptr m,menu_handler f,void *ref)
{
  return(Event_AttachPopUp(w,event_ANY,m,f,ref));
}

Menu_Attachment *Event_AttachPopUp(window_handle w,icon_handle i,menu_ptr m,menu_handler f,void *ref)
{
  Menu_Attachment *AtBlock=NULL;
  
  if(m!=0) {
    AtBlock=(Menu_Attachment *)malloc(sizeof(Menu_Attachment));
    if(AtBlock!=NULL) {            
      AtBlock->MenuWind=w;   
      AtBlock->MenuIcon=i;
      AtBlock->ThisMenu=m;
      AtBlock->HandleProc=f;
      AtBlock->Handle=ref;
      Event_Claim(event_CLICK,w,i,Attachment_Click,(void *)AtBlock);
    }
  }
  
  return AtBlock;
}

void Event_RemoveMenu(Menu_Attachment *AtBlock)
{
  Event_Release(event_CLICK,AtBlock->MenuWind,AtBlock->MenuIcon,Attachment_Click,(void *)AtBlock);
  free((void *)AtBlock);
}

void Window_ShowAsMenu(window_handle w)
{
  if((event_lastevent.type==event_USERMESSAGE || 
      event_lastevent.type==event_USERMESSAGERECORDED)
     && event_lastevent.data.message.header.action==message_MENUWARNING) {
    
    Wimp_CreateSubMenu((menu_ptr)w,event_lastevent.data.message.data.menuwarn.openpos.x,
                         event_lastevent.data.message.data.menuwarn.openpos.y);
  }
}
   

BOOL Attachment_Click(event_pollblock *pb,void *AtV)
{
  Menu_Attachment *AtBlock=(Menu_Attachment *)AtV;
  BOOL rcode=FALSE;
  
  if(pb->data.mouse.button.data.menu || (AtBlock->MenuIcon!=event_ANY)) {                            _CurrentMenu=AtBlock;
    if(AtBlock->MenuWind==window_ICONBAR)
      Menu_Show(AtBlock->ThisMenu,pb->data.mouse.pos.x,-1);
    else
      Menu_Show(AtBlock->ThisMenu,pb->data.mouse.pos.x,pb->data.mouse.pos.y);
    rcode=TRUE;
  }
  
  return rcode;
}

BOOL Attachment_Select(event_pollblock *Sel,void *ref)
{         
  mouse_block ClickData;
  
  ref=ref;
  
  Wimp_GetPointerInfo(&ClickData);
  
  (_CurrentMenu->HandleProc)(_CurrentMenu->Handle,Sel->data.selection);
  
  if(ClickData.button.data.adjust)
    Menu_ShowLast();
  
  return TRUE;
}

BOOL Attachment_Warn(event_pollblock *Warning,void *ref)
{
  ref=ref;
 
  (_CurrentMenu->HandleProc)(_CurrentMenu->Handle,Warning->data.message.data.menuwarn.selection);
  
  return TRUE;
}
  



