#include "X11Displays.h"
#include "X11Screen.h"
#include "displays.h"
#include "global.h"
#include "keyboard.h"
#include "pixmaps.h"

void
exposeNotify(Widget /*w*/, WDisplay *window, XEvent* event, Boolean* /*b*/)
{
#define ev (event->xexpose)
  window->ExposeNotify(ev.x, ev.y, ev.width, ev.height);
#undef ev
}

void getEvent(Widget /*w*/, WDisplay *win, XEvent *event, Boolean * /*b*/)
{
  if (state == IN_SELECT)
    return;
  if (event->type == ButtonRelease)
    {
      XButtonEvent *button_event = (XButtonEvent *)event;
      if (button_event->button == Button1)
	win->GetEvent(MOUSE_LEFT, button_event->x, button_event->y, NULL);
      else if (button_event->button == Button3)
	win->GetEvent(MOUSE_RIGHT, button_event->x, button_event->y, NULL);
      return;
    }
  else if (event->type != KeyRelease)
    return;
  
  XKeyEvent *key_event = (XKeyEvent *)event;
  int key = TranslateMoveKey(key_event->keycode);
  if (key == 0) {
    char buf[20];
    XLookupString(key_event, buf, 20, NULL, NULL);
    key = *buf;
    if (TranslateChar2MoveKey(key))
      key = TranslateChar2MoveKey(key);
  }
  win->GetEvent(KEYBOARD, key, 0, NULL);
}

X11DisplayData::X11DisplayData(X11Screen *scr, Display *display)
{
  screen = scr;
  dpy = display;
}

X11DisplayData::~X11DisplayData() {;}

void X11DisplayData::Clear()
{
  FillRect(0,0,width, height, screen->AllocColor("black"));
  /*XClearWindow(dpy, window);
  XCopyArea(dpy, window, pix, screen->gc, 0, 0, width, height,0,0);*/
}

void X11DisplayData::FillRect(int x, int y, int width, int ht, int col)
{
  XSetForeground(dpy, screen->gc, col);
  XFillRectangle(dpy, window, screen->gc, x, y, width, ht);
  XFillRectangle(dpy, pix, screen->gc, x, y, width, ht);
}

void X11DisplayData::Rect(int x, int y, int width, int ht, int col)
{
  XSetForeground(dpy, screen->gc, col);
  XDrawRectangle(dpy, window, screen->gc, x, y, width, ht);
  XDrawRectangle(dpy, pix, screen->gc, x, y, width, ht);
}

void X11DisplayData::Raise()
{
  XRaiseWindow(dpy, frame);
}

void X11DisplayData::Flush()
{
  XFlush(dpy);
}

void X11DisplayData::WriteStr(int x, int y, char *str, int color)
{
  XSetForeground(dpy, screen->gc, color);
  XDrawString(dpy, window, screen->gc, x, y+FontHeight, str, strlen(str));
  XDrawString(dpy, pix, screen->gc, x, y+FontHeight, str, strlen(str));
}

void X11DisplayData::DrawPixmap(int xc, int yc, CPixmap *handle, int owner)
{
  PixmapInfo *info = handle->Handle(owner);
  if (info->mask != None) {
    XSetClipOrigin(dpy, screen->gc, xc, yc);
    XSetClipMask(dpy, screen->gc, info->mask);
  }
  XCopyArea(dpy, info->pixmap, window, screen->gc, 0, 0, info->w, info->h, xc, yc);
  XCopyArea(dpy, info->pixmap, pix, screen->gc, 0, 0, info->w, info->h, xc, yc);
  if (info->mask != None)
    XSetClipMask(dpy, screen->gc, None);
}
