All pastes #513712 Raw Edit

Mine

public text v1 · immutable
#513712 ·published 2007-05-27 11:34 UTC
rendered paste body
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <termios.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <curses.h>
#include <term.h>

/* compile with:  gcc kate.c -o kate -lncurses */
int tty, outfd, TTY_FILENO;
FILE *ctty, *tty_in, *tty_out;
struct termios original_termios, ttybuff;
struct termios *tty_ts_orig_pt;
unsigned long original_tty_flags;

char *
get_tty_path (void)
{
  int i;
  char *tty_path = NULL;

  for (i = 0; i <= 2; i++)
    if ((tty_path = ttyname (i)))
      break;

  return tty_path;
}

int
main()
{
  char *terminal = NULL;
  int status = 0;
  int key = 0;
  int buffer[3];
  int chars = 0;
  int i = 0;
  
  /* acquire this terminal */
  if (!isatty (STDIN_FILENO) || !isatty (STDOUT_FILENO))
    if ((ctty = fopen (get_tty_path (), "r+")) == NULL)
      return 1;
  
  if (!isatty (STDIN_FILENO) && ctty)
    {
      tty_in = ctty;
      tty = fileno (tty_in);
    }
  else
    {
      tty_in = stdin;
      tty = STDIN_FILENO;
    }

  if (!isatty (STDOUT_FILENO) && ctty)
    tty_out = ctty;
  else
    tty_out = stdout;
 
  tcgetattr (tty, &original_termios);
  tcgetattr (tty, &ttybuff);
  
  ttybuff.c_iflag &= (~ISTRIP & ~INLCR & ~IGNCR & ~ICRNL & ~IXON);
  ttybuff.c_oflag &= ~ONLCR;
  ttybuff.c_oflag &= ~OCRNL;
  ttybuff.c_lflag &= (~ICANON & ~ECHO);
  ttybuff.c_cc[VMIN] = 1;
  ttybuff.c_cc[VTIME] = 0;
  
  tcsetattr (tty, TCSANOW, &ttybuff);

  /* init terminfo */
  if ((terminal = getenv("TERM")) == NULL)
    {
      printf("TERM environment variable not set.\n");
      return 1;
    }

  setupterm(terminal, fileno (stdout), &status);

  if (clear_screen)
    putp (clear_screen);
  else
    printf ("couldn't clear the sreen\n");


  /* ask the user to press a key */
  printf("press the pgup key: ");
  fflush (stdout);

  read (fileno (stdin), &key, 1);

#ifdef FIONREAD  
  ioctl (tty, FIONREAD, &chars);

  if (chars)
    {
      memset (&buffer, 0, sizeof (buffer));
      chars = read (fileno(stdin), &buffer[0], chars);
    }
#endif
  
  if (clear_screen)
    putp (clear_screen);
  
  tcsetattr (tty, TCSADRAIN, &original_termios);

  printf("got the next sequence: ");

  if (buffer[0] == 0x7e355b)
    printf("ok\n");
  else
    printf("nop\n");

  putchar ('\n');
  return 0;
  
}