jkeyboard.cpp 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. /*##############################################################################
  2. Copyright (C) 2011 HPCC Systems.
  3. All rights reserved. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU Affero General Public License as
  5. published by the Free Software Foundation, either version 3 of the
  6. License, or (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU Affero General Public License for more details.
  11. You should have received a copy of the GNU Affero General Public License
  12. along with this program. If not, see <http://www.gnu.org/licenses/>.
  13. ############################################################################## */
  14. #include "platform.h"
  15. #include "jutil.hpp"
  16. #include "jkeyboard.hpp"
  17. keyboard::keyboard()
  18. {
  19. #ifndef _WIN32
  20. tcgetattr(0,&initial_settings);
  21. new_settings = initial_settings;
  22. new_settings.c_lflag &= ~ICANON;
  23. new_settings.c_lflag &= ~ECHO;
  24. new_settings.c_lflag &= ~ISIG;
  25. new_settings.c_cc[VMIN] = 1;
  26. new_settings.c_cc[VTIME] = 0;
  27. tcsetattr(0, TCSANOW, &new_settings);
  28. peek_character=-1;
  29. #endif
  30. }
  31. keyboard::~keyboard()
  32. {
  33. #ifndef _WIN32
  34. tcsetattr(0, TCSANOW, &initial_settings);
  35. #endif
  36. }
  37. int keyboard::kbhit()
  38. {
  39. #ifndef _WIN32
  40. unsigned char ch;
  41. int nread;
  42. if (peek_character != -1) return 1;
  43. new_settings.c_cc[VMIN]=0;
  44. tcsetattr(0, TCSANOW, &new_settings);
  45. nread = read(0,&ch,1);
  46. new_settings.c_cc[VMIN]=1;
  47. tcsetattr(0, TCSANOW, &new_settings);
  48. if (nread == 1)
  49. {
  50. peek_character = ch;
  51. return 1;
  52. }
  53. return 0;
  54. #else
  55. return ::_kbhit();
  56. #endif
  57. }
  58. int keyboard::getch()
  59. {
  60. #ifndef _WIN32
  61. char ch;
  62. if (peek_character != -1)
  63. {
  64. ch = peek_character;
  65. peek_character = -1;
  66. }
  67. else
  68. {
  69. if (read(0,&ch,1) == 0)
  70. return -1;
  71. }
  72. return ch;
  73. #else
  74. return ::_getch();
  75. #endif
  76. }