tty.c 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. /* Copyright (C) 2016 Jeremiah Orians
  2. * This file is part of stage0.
  3. *
  4. * stage0 is free software: you can redistribute it and/or modify
  5. * it under the terms of the GNU General Public License as published by
  6. * the Free Software Foundation, either version 3 of the License, or
  7. * (at your option) any later version.
  8. *
  9. * stage0 is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License
  15. * along with stage0. If not, see <http://www.gnu.org/licenses/>.
  16. */
  17. #include <stdlib.h>
  18. #include <termios.h>
  19. #include <unistd.h>
  20. /****************************************************
  21. * To make effective use of this library function: *
  22. * add prototypes for the below functions that you *
  23. * wish to use. Please note that they contain bugs *
  24. ****************************************************/
  25. /* In order to restore at exit.*/
  26. static struct termios orig_termios;
  27. /* Raw mode: 1960 magic shit. */
  28. void enableRawMode()
  29. {
  30. struct termios raw;
  31. if(!isatty(STDIN_FILENO))
  32. {
  33. exit(EXIT_FAILURE);
  34. }
  35. if(tcgetattr(STDIN_FILENO, &orig_termios) == -1)
  36. {
  37. exit(EXIT_FAILURE);
  38. }
  39. raw = orig_termios; /* modify the original mode */
  40. /* input modes: no break, no CR to NL, no parity check, no strip char,
  41. * no start/stop output control. */
  42. raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
  43. /* output modes - disable post processing */
  44. raw.c_oflag &= ~(OPOST);
  45. /* control modes - set 8 bit chars */
  46. raw.c_cflag |= (CS8);
  47. /* local modes - choing off, canonical off, no extended functions,
  48. * no signal chars (^Z,^C) */
  49. raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
  50. /* control chars - set return condition: min number of bytes and timer. */
  51. raw.c_cc[VMIN] = 0; /* Return each byte, or zero for timeout. */
  52. raw.c_cc[VTIME] = 1; /* 100 ms timeout (unit is tens of second). */
  53. /* put terminal in raw mode after flushing */
  54. if(tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw) < 0)
  55. {
  56. exit(EXIT_FAILURE);
  57. }
  58. return;
  59. }
  60. void disableRawMode()
  61. {
  62. tcsetattr(STDIN_FILENO, TCSAFLUSH, &orig_termios);
  63. }
  64. char tty_getchar()
  65. {
  66. int nread;
  67. char c;
  68. enableRawMode();
  69. do
  70. {
  71. nread = read(STDIN_FILENO, &c, 1);
  72. } while(nread == 0);
  73. disableRawMode();
  74. return c;
  75. }