Blob Blame Raw

#include "app.h"



int keyInit(Key *k, Keyboard *kbd) {
  k->kbd = kbd;
  k->down = 0;
  
  int lx = k->x + k->w/2;
  int ly = k->y + k->h/2;
  if (k->label && !textLayoutInit(&k->tl, &k->kbd->app->graph, lx, ly, k->label))
    return 0;
  
  int d = k->h/4;
  lx = k->x + k->w - d;
  ly = k->y + d;
  if (k->label2 && !textLayoutInit(&k->tl2, &k->kbd->app->graph, lx, ly, k->label2)) {
    if (k->label) textLayoutDeinit(&k->tl);
    return 0;
  }
  
  return 1;
}


void keyDeinit(Key *k) {
  if (k->label) textLayoutDeinit(&k->tl);
  if (k->label2) textLayoutDeinit(&k->tl2);
}

  
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;
  graphDrawButton(&k->kbd->app->graph, k->x, k->y, k->w, k->h, k->down);
  textLayoutDraw(&k->tl, k->down);
}


void keyMouseDown(Key *k) {
  k->down = 1;
  inputEvent(&k->kbd->app->input, k->keySym, 1);
  appInvalidateRect(k->kbd->app, k->x, k->y, k->w, k->h);
}


void keyMouseUp(Key *k) {
  k->down = 0;
  inputEvent(&k->kbd->app->input, k->keySym, 0);
  appInvalidateRect(k->kbd->app, k->x, k->y, k->w, k->h);
}



int keyboardInit(Keyboard *kbd, App *app) {
  LOGDBG("keyboard: init");
  kbd->app = app;
  kbd->downKey = NULL;
  for(int i = 0; i < kbd->keysCount; ++i)
    if (!keyInit(&kbd->keys[i], kbd)) {
      for(--i; i >= 0; --i) keyDeinit(&kbd->keys[i]);
      return 0;
    }
  return 1;
}


void keyboardDeinit(Keyboard *kbd) {
  LOGDBG("keyboard: deinit");
  keyboardMouseUp(kbd);
  for(int i = 0; i < kbd->keysCount; ++i)
    keyDeinit(&kbd->keys[i]);
}


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->downKey != k) {
        keyboardMouseUp(kbd);
        kbd->downKey = k;
        keyMouseDown(k);
      }
      break;
    }
  }
}


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