keyboard.cpp 1.7KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. #include <chrono>
  2. #include <thread>
  3. #include "keyboard.hpp"
  4. bool slop::Keyboard::getKey( KeySym key ) {
  5. KeyCode keycode = XKeysymToKeycode( x11->display, key );
  6. if ( keycode != 0 ) {
  7. // Get the whole keyboard state
  8. char keys[32];
  9. XQueryKeymap( x11->display, keys );
  10. // Check our keycode
  11. return ( keys[ keycode / 8 ] & ( 1 << ( keycode % 8 ) ) ) != 0;
  12. } else {
  13. return false;
  14. }
  15. }
  16. bool slop::Keyboard::anyKeyDown() {
  17. return keyDown;
  18. }
  19. void slop::Keyboard::update() {
  20. char keys[32];
  21. XQueryKeymap( x11->display, keys );
  22. keyDown = false;
  23. for ( int i=0;i<32;i++ ) {
  24. if ( deltaState[i] == keys[i] ) {
  25. continue;
  26. }
  27. // Found a key in a group of 4 that's different
  28. char a = deltaState[i];
  29. char b = keys[i];
  30. // Find the "different" bits
  31. char c = a^b;
  32. // A new key was pressed since the last update.
  33. if ( c && b&c ) {
  34. keyDown = true;
  35. }
  36. deltaState[i] = keys[i];
  37. }
  38. }
  39. slop::Keyboard::Keyboard( X11* x11 ) {
  40. this->x11 = x11;
  41. int err = XGrabKeyboard( x11->display, x11->root, False, GrabModeAsync, GrabModeAsync, CurrentTime );
  42. int tries = 0;
  43. while( err != GrabSuccess && tries < 5 ) {
  44. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  45. err = XGrabKeyboard( x11->display, x11->root, False, GrabModeAsync, GrabModeAsync, CurrentTime );
  46. tries++;
  47. }
  48. // Non-fatal.
  49. if ( err != GrabSuccess ) {
  50. //throw new std::runtime_error( "Couldn't grab the keyboard after 10 tries." );
  51. }
  52. XQueryKeymap( x11->display, deltaState );
  53. keyDown = false;
  54. }
  55. slop::Keyboard::~Keyboard() {
  56. XUngrabKeyboard( x11->display, CurrentTime );
  57. }