keystack.c 1.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
/* Showkeys
   Copyright Noufal Ibrahim <noufal@nibrahim.net.in> 2011

   Licensed under the GPLv3 : http://www.gnu.org/licenses/gpl.txt

   Please see LICENSE file for complete license.
*/

#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "keystack.h"

static void
push_back(KeyStack *stack, int index)
{
  int i;
  free(stack->keystrokes[0].keyname);
  for (i=0; i<index; i++)
    stack->keystrokes[i] = stack->keystrokes[i+1];
}

KeyStack *
create_keystack(int size)
{
  int i;
  KeyStack *retval = NULL;
  KeyStroke *stack = NULL;

  stack = (KeyStroke *)malloc(sizeof(KeyStroke) * size);
  for (i=0; i<size; i++) {
    stack[i].keyname = NULL;
    stack[i].times = 0;
  }

  retval = (KeyStack *)malloc(sizeof(KeyStack));
  retval->size = size;
  retval->pos = -1;
  retval->keystrokes = stack;

  return retval;
}

void
push(KeyStack *stack, char *keyname)
{
  int index;
  KeyStroke *last;
  char *last_key;

  last = &stack->keystrokes[stack->pos];
  last_key = last->keyname;
  index = stack->pos + 1;

  if (index && strlen (keyname) < 3 && last->times != 0) {
    /* If the same as the top of the stack, increment count */
    int newlen =  strlen(keyname) + strlen(last_key) + 1;
    last->keyname = malloc(newlen);
    snprintf(last->keyname, newlen, "%s%s", last_key, keyname);
    free(last_key);
  } else {
    /* Add a new entry */
    if (index == stack->size) {
      push_back(stack, stack->pos);
      index = stack->size-1;
    }
    stack->keystrokes[index].keyname = keyname;

    int concat = 0;
    if(strlen(keyname) < 3){concat = 1;}else {concat = 0;}
    stack->keystrokes[index].times = concat;
    stack->pos = index;
  }
}


void
display_keystack(KeyStack *stack)
{
  int i;
  printf("---- Keystack ----\n");
  for (i = 0; i <= stack->pos; i++) {
    printf("%s %d times\n", stack->keystrokes[i].keyname, stack->keystrokes[i].times);
  }
  printf("---- -------- ----\n\n");
}