typer.h
1 #ifndef TYPERH 2 #define TYPERH 3 4 #include <termios.h> 5 #include <time.h> 6 7 8 #define COLOR_GREEN "\033[1;32m" 9 #define COLOR_YELLOW "\033[1;33m" 10 #define COLOR_RED "\033[1;31m" 11 #define COLOR_PALE_RED "\033[0;31m" 12 #define COLOR_BOLD "\033[1;37m" 13 #define COLOR_RESET "\033[0m" 14 #define CLEAR_TO_LINE_END "\033[0K" 15 #define CLEAR_TO_FILE_END "\033[0J" 16 17 #define KEY_CTRL_C 3 18 #define KEY_CTRL_D 4 19 #define KEY_ENTER 13 20 #define KEY_ESCAPE 27 21 #define KEY_BACKSPACE 127 22 #define KEY_SHIFT_BACKSPACE 8 23 24 #define IS_BLANK(X) ((X) == ' ' || (X) == '\t') 25 #define IS_NUMBER(X) ((X) >= '0' && (X) <= '9') 26 #define IS_LETTER(X) (((X) >= 'a' && (X) <= 'z') || ((X) >= 'A' && (X) <= 'Z')) 27 #define IS_ALPHANUMERIC(X) (IS_LETTER(X) || IS_NUMBER(X)) 28 29 #define KEYPRESS_CORRECT 0 30 #define KEYPRESS_INCORRECT 1 31 #define KEYPRESS_BACKSPACE 2 32 #define KEYPRESS_EXIT 3 33 #define KEYPRESS_ENTER 4 34 #define KEYPRESS_NONE 5 35 36 typedef struct { 37 int * buffer; 38 size_t length; 39 } Jumps; 40 41 typedef struct { 42 /* the string being typed */ 43 const char * prompt; 44 int prompt_length; 45 46 /* records how many characters are traversed by each keypress */ 47 Jumps jumps; 48 49 /* sum of jumps, cursor's index in prompt */ 50 int index; 51 52 /* cursor's position within the terminal */ 53 int column; 54 int row; 55 56 /* so that the terminal resumes after the end of the prompt */ 57 int max_row; 58 59 int * line_lengths; 60 61 /* for wrapping, we have to record what has been printed. */ 62 char * chars_printed; 63 int chars_printed_index; 64 65 /* keypress tallies */ 66 int chars_correct; 67 int chars_total; 68 69 /* options */ 70 int flags; 71 const char * outfile; 72 long int duration_millis; 73 74 /* timing */ 75 long int start_millis; 76 long int end_millis; 77 int timed_out; 78 } State; 79 80 void setup_termios(struct termios termios0); 81 void restore_termios(struct termios termios0); 82 83 void start_typing(State * state); 84 int handle_keypress(State * state, char c); 85 86 #endif /* TYPERH */