keyboard.cpp 1.4KB

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