minor fixes + upgrades
[my-code/api.git] / input / input.c
1 /* input.c -- input management stuff
2  *
3  * author: hackbard@hackdaworld.dyndns.org
4  *
5  */
6
7 #include "input.h"
8
9 int input_init(t_input *input,int outfd) {
10
11   dprintf(outfd,"[input] initializing input system ...\n");
12
13   input->outfd=outfd;
14   input->mode=0;
15
16   return I_SUCCESS;
17 }
18
19 int input_ios_init(t_input *input) {
20
21   struct termios tios;
22   int size;
23
24   size=((input->mode&CONTENT_BUFFER)?MAX_CONTENT:1);
25
26   if((input->content=(char *)malloc(size))==NULL) {
27     perror("[input] malloc call");
28     return I_ERROR;
29   }
30     
31   memset(input->content,0,size);
32   input->c_count=0;
33
34   tcgetattr(0,&(input->tios));
35   tios=input->tios;
36
37   /* general settings */
38   tios.c_iflag&=ICRNL; /* \r -> \n */
39   tios.c_cc[VTIME]=0; /* no timeout */
40   tios.c_cc[VMIN]=1; /* 1 char for non-can. mode */
41
42   /* depending on used modes */
43   if(!(input->mode&LINE_BUFFERED)) tios.c_lflag&=(~ICANON);
44   if(!(input->mode&INPUT_ECHO)) tios.c_lflag&=(~ECHO);
45
46   tcsetattr(0,TCSANOW,&tios);
47
48   return I_SUCCESS;
49 }
50
51 int input_shutdown(t_input *input) {
52
53   free(input->content);
54   tcsetattr(0,TCSANOW,&(input->tios));
55   dprintf(input->outfd,"[input] shutdown\n");
56
57   return I_SUCCESS;
58 }
59
60 int input_get_event(t_input *input,int (*callback)(t_input *input,void *ptr),
61                    void *ptr) {
62
63   char data[MAX_CONTENT];
64   int count;
65
66   /* delete char counter if not buffered */
67   if(!(input->mode&CONTENT_BUFFER)) input->c_count=0;
68
69   if((count=read(0,data,MAX_CONTENT))==-1) {
70     perror("[input] read call");
71     return I_ERROR;
72   }
73
74   if(input->c_count>=MAX_CONTENT) {
75     dprintf(input->outfd,"[input] max input length reached\n");
76     return I_ERROR;
77   }
78
79   strncpy(&(input->content[input->c_count]),data,count);
80   input->c_count+=count;
81
82   callback(input,ptr);
83
84   return I_SUCCESS;
85 }