index — thing @ master

A little something I'm working on

main.c (view raw)

 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
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
#include <stdint.h>
#include <stdio.h>

#include <poll.h>
#include <termios.h>
#include <unistd.h>

void move_cursor(int direction, uint8_t *pos, int len) {
  if (direction == -1) {
    if (*pos != 0) {
      *pos -= 1;
    } else {
      return;
    }
    printf("\x0D ");
    printf("\x0D\x1B[1A>");
    printf("\x0D");
  } else if (direction == 1) {
    if (*pos != len - 1) {
      *pos += 1;
    } else {
      return;
    }
    printf("\x0D ");
    printf("\x0D\x1B[1B>");
    printf("\x0D");
  }
  fflush(stdout);
}

struct termios setup_term() {
  struct termios old, new;

  tcgetattr(STDIN_FILENO, &old);

  new = old;

  new.c_lflag &= ~(ECHO | ICANON);
  new.c_cc[VMIN] = 0;  // bytes read to return
  new.c_cc[VTIME] = 0; // time before return

  printf("\x1B[?1049h");
  tcsetattr(STDIN_FILENO, TCSANOW, &new);

  return old;
}

void return_term(struct termios *old) {
  tcsetattr(STDIN_FILENO, TCSANOW, old);
  printf("\x1B[?1049l");
}

int menu(char **elements, int len) {
  struct pollfd poller[1];

  poller[0].fd = STDIN_FILENO;
  poller[0].events = POLLIN;

  for (int i = 0; i < len; i++) {
    printf(" %s\n", elements[i]);
  }

  printf("\x1B[%dA>\x0D", len);
  fflush(stdout);

  uint8_t pos = 0;
  while (1) {
    int events = poll(poller, 1, -1);
    if (events > 0 && poller[0].revents & POLLIN) {
      char buffer[10];
      uint16_t length = read(STDIN_FILENO, buffer, sizeof(buffer));
      if (length > 0) {
        uint8_t i;
        for (i = 0; i < length; i++) {
          if (buffer[i] == 'q')
            return -1;
          else if (buffer[i] == 'j') {
            move_cursor(1, &pos, len);
          } else if (buffer[i] == 'k') {
            move_cursor(-1, &pos, len);
          } else if (buffer[i] == 'o') {
            return pos;
          }
        }
      } else {
        return -1;
      }
    } else {
      return -1;
    }
  }
}

int main() {
  uint8_t ret = 0;
  struct termios old = setup_term();

  static char *elements[] = {"hi", "hello", "what's up", "dang",
                             "this is cool"};

  int seli = menu(elements, 5);
  if (seli < 0) {
    printf("ERROR: menu failed");
    ret = 1;
  }

  return_term(&old);
  if (ret == 0) {
    printf("%s", elements[seli]);
  }

  return ret;
}