Blob Blame Raw
#ifndef KEYBOARD_INC_C
#define KEYBOARD_INC_C


struct Keyboard;


typedef struct Key {
  int x, y, w, h;
  const char *label;

  struct Keyboard *kbd;
  int lx, ly;
  
  int pressed;
} Key;


typedef struct Keyboard {
  Key *keys;
  int keysCount;

  Display* dpy;
  Window win;
  GC gc;
  GContext gcid;
  XFontStruct *font;
  
  Key *keyMousePressed;
} Keyboard;



void keyInit(Key *k, Keyboard *kbd) {
  k->pressed = 0;
  k->kbd = kbd;
  XFontStruct *font = XQueryFont(k->kbd->dpy, k->kbd->gcid);
  XRectangle r = {};
  XTextExtents(font, k->label, strlen(k->label), NULL, &r);
  k->lx = k->x + (k->w - r.width)/2 - r.x;
  k->ly = k->y + (k->h - r.height)/2 - r.y;
}

void keyDeinit(Key *k) {
  k->pressed = 0;
}

void keyDraw(Key *k, int cx, int cy, int cw, int ch) {
  if ( k->x + k->w <= cx || k->x >= cx + cw
    || k->y + k->h <= cy || k->y >= cy + ch ) return;
  if (k->pressed)
    XDrawRectangle(k->kbd->dpy, k->kbd->win, k->kbd->gc, k->x, k->y, k->w, k->h);
  XDrawString(k->kbd->dpy, k->kbd->win);
}

void keyMouseDown(Key *k) {
  k->pressed = 1;
}

void keyMouseUp(Key *k) {
  k->pressed = 0;
}


void keyboardInit(Keyboard *kbd, Display *dpy, Window win) {
  kbd->keyMousePressed = NULL;
  kbd->dpy = dpy;
  kbd->win = win;
  kbd->gc = DefaultGC(kbd->dpy, kbd->win);
  kbd->gcid = XGContextFromGC(kbd->gc);
  kbd->font = XQueryFont(k->kbd->dpy, k->kbd->gcid);
  for(int i = 0; i < kbd->keysCount; ++i)
    keyInit(&kbd->keys[i], kbd);
}

void keyboardDeinit(Keyboard *kbd) {
  for(int i = 0; i < kbd->keysCount; ++i)
    keyDeinit(kbd->keys[i]);
  kbd->keyMousePressed = NULL;
  kbd->font = XFreeFont(kbd->dpy, kbd->font);
  kbd->gcid = NULL;
  kbd->gc = NULL;
  kbd->win = NULL;
  kbd->dpy = NULL;
}

void keyboardDraw(Keyboard *kbd, int cx, int cy, int cw, int ch) {
  for(int i = 0; i < kbd->keysCount; ++i)
    keyDraw(&kbd->keys[i], cx, cy, cw, ch);
}

void keyboardMouseDown(Keyboard *kbd, int x, int y) {
  for(int i = kbd->keysCount - 1; i >= 0; --i) {
    Key *k = &kbd->keys[i];
    if ( k->x <= x && x < k->x + k->w
      && k->y <= y && y < k->y + k->h )
    {
      if (kbd->keyMousePressed != k) {
        keyboardMouseUp(kbd);
        kbd->keyMousePressed = k;
        keyMouseDown(k);
      }
      break;
    }
  }
}

void keyboardMouseUp(Keyboard *kbd) {
  if (kbd->keyMousePressed) {
    kbd->keyMouseUp(kbd->keyMousePressed);
    kbd->keyMousePressed = NULL;
  }
}



#endif