jkeyboard.cpp 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /*##############################################################################
  2. HPCC SYSTEMS software Copyright (C) 2012 HPCC Systems®.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. ############################################################################## */
  13. #include "platform.h"
  14. #include "jutil.hpp"
  15. #include "jkeyboard.hpp"
  16. keyboard::keyboard()
  17. {
  18. #ifndef _WIN32
  19. tcgetattr(0,&initial_settings);
  20. new_settings = initial_settings;
  21. new_settings.c_lflag &= ~ICANON;
  22. new_settings.c_lflag &= ~ECHO;
  23. new_settings.c_lflag &= ~ISIG;
  24. new_settings.c_cc[VMIN] = 1;
  25. new_settings.c_cc[VTIME] = 0;
  26. tcsetattr(0, TCSANOW, &new_settings);
  27. peek_character=-1;
  28. #endif
  29. }
  30. keyboard::~keyboard()
  31. {
  32. #ifndef _WIN32
  33. tcsetattr(0, TCSANOW, &initial_settings);
  34. #endif
  35. }
  36. int keyboard::kbhit()
  37. {
  38. #ifndef _WIN32
  39. unsigned char ch;
  40. int nread;
  41. if (peek_character != -1) return 1;
  42. new_settings.c_cc[VMIN]=0;
  43. tcsetattr(0, TCSANOW, &new_settings);
  44. nread = read(0,&ch,1);
  45. new_settings.c_cc[VMIN]=1;
  46. tcsetattr(0, TCSANOW, &new_settings);
  47. if (nread == 1)
  48. {
  49. peek_character = ch;
  50. return 1;
  51. }
  52. return 0;
  53. #else
  54. return ::_kbhit();
  55. #endif
  56. }
  57. int keyboard::getch()
  58. {
  59. #ifndef _WIN32
  60. char ch;
  61. if (peek_character != -1)
  62. {
  63. ch = peek_character;
  64. peek_character = -1;
  65. }
  66. else
  67. {
  68. if (read(0,&ch,1) == 0)
  69. return -1;
  70. }
  71. return ch;
  72. #else
  73. return ::_getch();
  74. #endif
  75. }