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