86dac627f6b0b07f2fb277b522649ba8ca40a1dd
[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) {
10
11   struct termios tios;
12   int size;
13
14   puts("[input] initializing input system ...");
15
16   // size=((input->mode&CONTENT_BUFFER)?MAX_CONTENT:1); <- ???
17   size=MAX_CONTENT;
18
19   if((input->content=(char *)malloc(size))==NULL) {
20     perror("[input] malloc call");
21     return I_ERROR;
22   }
23     
24   memset(input->content,0,size);
25   input->c_count=0;
26
27   tcgetattr(0,&(input->tios));
28   tios=input->tios;
29
30   /* general settings */
31   tios.c_iflag&=ICRNL; /* \r -> \n */
32   tios.c_cc[VTIME]=0; /* no timeout */
33   tios.c_cc[VMIN]=1; /* 1 char for non-can. mode */
34
35   /* depending on used modes */
36   if(!(input->mode&LINE_BUFFERED)) tios.c_lflag&=(~ICANON);
37   if(!(input->mode&INPUT_ECHO)) tios.c_lflag&=(~ECHO);
38
39   tcsetattr(0,TCSANOW,&tios);
40
41   return I_SUCCESS;
42 }
43
44 int input_shutdown(t_input *input) {
45
46   free(input->content);
47   tcsetattr(0,TCSANOW,&(input->tios));
48   puts("[input] shutdown");
49
50   return I_SUCCESS;
51 }
52
53 int input_get_event(t_input *input,int (*callback)(t_input *input,void *ptr),
54                    void *ptr) {
55
56   char data[MAX_CONTENT];
57   int count;
58
59   /* delete char counter if not buffered */
60   if(!(input->mode&CONTENT_BUFFER)) input->c_count=0;
61
62   if((count=read(0,data,MAX_CONTENT))==-1) {
63     perror("[input] read call");
64     return I_ERROR;
65   }
66
67   if(input->c_count>=MAX_CONTENT) {
68     puts("[input] max input length reached");
69     return I_ERROR;
70   }
71
72   strncpy(&(input->content[input->c_count]),data,count);
73   input->c_count+=count;
74
75   callback(input,ptr);
76
77   return I_SUCCESS;
78 }