/*
 *  WindowUtil.c    A set of Window and Screen utilities.
 *
 *  Written by Davide P. Cervone
 *  You may use these however you like.
 */

/*
 *  WindowAt(x,y,screen)    returns a pointer to the window that is at
 *                          the specified location on the specified screen,
 *                          or NULL if there isn't one.
 *                          (use WhichScreen() to find the screen, if you
 *                          have to).
 *
 *  WhichScreen()           returns a pointer to the screen where the mouse
 *                          currently is pointing, or NULL if there isn't one.
 *
 *  WhichWindow()           returns a pointer the window where the mouse
 *                          currently is pointing, or NULL if there isn't one.
 *
 *  Also in this set (but not used here) are routines for finding bottom,
 *  top, next and previous windows based on actual depth arrangement rather
 *  than order of creation.
 *
 */

#include <intuition/intuitionbase.h>

extern struct IntuitionBase *IntuitionBase;
extern struct Layer *WhichLayer();

#define WINDOW(layer)   ((struct Window *)((layer)->Window))
#define SCREENTOP\
   (theScreen->TopEdge << ((theScreen->ViewPort.Modes & LACE)? 0: 1))


struct Window *WindowAt(x,y,theScreen)
register long x,y;
register struct Screen *theScreen;
{
   register struct Window *theWindow = NULL;
   register struct Layer_Info *theLayerInfo = &(theScreen->LayerInfo);
   register struct Layer *theLayer;

   LockLayers(theLayerInfo);
   theLayer = WhichLayer(theLayerInfo,x,y);
   if (theLayer) theWindow = WINDOW(theLayer);
   UnlockLayers(theLayerInfo);
   return(theWindow);
}

struct Screen *WhichScreen()
{
    register struct Screen *theScreen;
    register int y;

   Forbid();
   y = IntuitionBase->MouseY;
   theScreen = IntuitionBase->FirstScreen;
   while (theScreen && y < SCREENTOP) theScreen = theScreen->NextScreen;
   if (theScreen == NULL) theScreen = IntuitionBase->FirstScreen;
   Permit();
   return(theScreen);
}

struct Window *WhichWindow()
{
    register struct Window *theWindow = NULL;
    register struct Screen *theScreen;

   if ((theScreen = WhichScreen()) != NULL)
      theWindow = WindowAt(theScreen->MouseX,theScreen->MouseY,theScreen);
   return(theWindow);
}
