x.cpp 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  1. /* x.cpp: Handles starting and managing X.
  2. *
  3. * Copyright (C) 2014: Dalton Nell, Slop Contributors (https://github.com/naelstrof/slop/graphs/contributors).
  4. *
  5. * This file is part of Slop.
  6. *
  7. * Slop is free software: you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation, either version 3 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * Slop is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with Slop. If not, see <http://www.gnu.org/licenses/>.
  19. */
  20. #include "x.hpp"
  21. slop::XEngine* xengine = new slop::XEngine();
  22. int slop::XEngineErrorHandler( Display* dpy, XErrorEvent* event ) {
  23. // Ignore XGrabKeyboard BadAccess errors, we can work without it.
  24. // 31 = XGrabKeyboard's request code
  25. if ( event->request_code == 31 && event->error_code == BadAccess ) {
  26. fprintf( stderr, "_X Error \"BadAccess\" for XGrabKeyboard ignored...\n" );
  27. return EXIT_SUCCESS;
  28. }
  29. // Ignore XQueryKeymap BadValue errors, we can work without it.
  30. // 128 = XShape request code, not sure why XQueryKeymap generates this?
  31. if ( event->request_code == 128 && event->error_code == BadValue ) {
  32. fprintf( stderr, "_X Error \"BadValue\" for XQueryKeymap ignored...\n" );
  33. return EXIT_SUCCESS;
  34. }
  35. // Everything else should be fatal as I don't like undefined behavior.
  36. char buffer[1024];
  37. XGetErrorText( dpy, event->error_code, buffer, 1024 );
  38. fprintf( stderr,
  39. "_X Error of failed request: %s\n_ Error code of failed request: %3d\n_ Major opcode of failed request: %3d\n_ Minor opcode of failed request: %3d\n_ Serial number of failed request: %5li\n_ Current serial number in output stream:?????\n",
  40. buffer,
  41. event->error_code,
  42. event->request_code,
  43. event->minor_code,
  44. event->serial );
  45. exit(1);
  46. }
  47. unsigned int slop::XEngine::getWidth() {
  48. if ( !m_good ) {
  49. return -1;
  50. }
  51. return WidthOfScreen( m_screen );
  52. }
  53. unsigned int slop::XEngine::getHeight() {
  54. if ( !m_good ) {
  55. return -1;
  56. }
  57. return HeightOfScreen( m_screen );
  58. }
  59. slop::XEngine::XEngine() {
  60. m_keypressed = false;
  61. m_display = NULL;
  62. m_visual = NULL;
  63. m_screen = NULL;
  64. m_good = false;
  65. m_mousex = -1;
  66. m_mousey = -1;
  67. m_hoverWindow = None;
  68. }
  69. slop::XEngine::~XEngine() {
  70. if ( !m_good ) {
  71. return;
  72. }
  73. for ( unsigned int i=0; i<m_cursors.size(); i++ ) {
  74. if ( m_cursors.at( i ) ) {
  75. XFreeCursor( m_display, m_cursors[i] );
  76. }
  77. }
  78. XCloseDisplay( m_display );
  79. }
  80. bool slop::XEngine::mouseDown( unsigned int button ) {
  81. if ( button >= m_mouse.size() ) {
  82. return false;
  83. }
  84. return m_mouse.at( button );
  85. }
  86. int slop::XEngine::init( std::string display ) {
  87. // Initialize display
  88. m_display = XOpenDisplay( display.c_str() );
  89. if ( !m_display ) {
  90. fprintf( stderr, "Error: Failed to open X display %s\n", display.c_str() );
  91. return EXIT_FAILURE;
  92. }
  93. m_screen = ScreenOfDisplay( m_display, DefaultScreen( m_display ) );
  94. m_visual = DefaultVisual ( m_display, XScreenNumberOfScreen( m_screen ) );
  95. m_colormap = DefaultColormap( m_display, XScreenNumberOfScreen( m_screen ) );
  96. //m_root = RootWindow ( m_display, XScreenNumberOfScreen( m_screen ) );
  97. m_root = DefaultRootWindow( m_display );
  98. m_res = XRRGetScreenResourcesCurrent( m_display, m_root);
  99. m_good = true;
  100. XSetErrorHandler( slop::XEngineErrorHandler );
  101. selectAllInputs( m_root, EnterWindowMask );
  102. return EXIT_SUCCESS;
  103. }
  104. std::vector<XRRCrtcInfo*> slop::XEngine::getCRTCS() {
  105. std::vector<XRRCrtcInfo*> monitors;
  106. if ( !m_res ) {
  107. return monitors;
  108. }
  109. for ( int i=0;i<m_res->ncrtc;i++ ) {
  110. monitors.push_back( XRRGetCrtcInfo( m_display, m_res, m_res->crtcs[ i ] ) );
  111. }
  112. return monitors;
  113. }
  114. bool slop::XEngine::keyPressed( KeySym key ) {
  115. KeyCode keycode = XKeysymToKeycode( m_display, key );
  116. if ( keycode != 0 ) {
  117. // Get the whole keyboard state
  118. char keys[32];
  119. XQueryKeymap( m_display, keys );
  120. // Check our keycode
  121. return ( keys[ keycode / 8 ] & ( 1 << ( keycode % 8 ) ) ) != 0;
  122. } else {
  123. return false;
  124. }
  125. }
  126. bool slop::XEngine::anyKeyPressed() {
  127. if ( !m_good ) {
  128. return false;
  129. }
  130. // Thanks to SFML for some reliable key state grabbing.
  131. // Get the whole keyboard state
  132. char keys[ 32 ];
  133. XQueryKeymap( m_display, keys );
  134. // Each bit indicates a different key, 1 for pressed, 0 otherwise.
  135. // Every bit should be 0 if nothing is pressed.
  136. for ( unsigned int i = 0; i < 32; i++ ) {
  137. if ( keys[ i ] != 0 ) {
  138. return true;
  139. }
  140. }
  141. return false;
  142. }
  143. int slop::XEngine::grabKeyboard() {
  144. if ( !m_good ) {
  145. return EXIT_FAILURE;
  146. }
  147. int err = XGrabKeyboard( m_display, m_root, False, GrabModeAsync, GrabModeAsync, CurrentTime );
  148. if ( err != GrabSuccess ) {
  149. fprintf( stderr, "Warning: Failed to grab X keyboard.\n" );
  150. fprintf( stderr, " This happens when something has already grabbed your keybaord.\n" );
  151. fprintf( stderr, " slop should still run properly though.\n" );
  152. return EXIT_FAILURE;
  153. }
  154. return EXIT_SUCCESS;
  155. }
  156. int slop::XEngine::releaseKeyboard() {
  157. if ( !m_good ) {
  158. return EXIT_FAILURE;
  159. }
  160. XUngrabKeyboard( m_display, CurrentTime );
  161. return EXIT_SUCCESS;
  162. }
  163. void slop::XEngine::selectAllInputs( Window win, long event_mask) {
  164. Window root, parent;
  165. Window* children;
  166. unsigned int nchildren;
  167. XQueryTree( m_display, win, &root, &parent, &children, &nchildren );
  168. for ( unsigned int i=0;i<nchildren;i++ ) {
  169. XSelectInput( m_display, children[ i ], event_mask );
  170. selectAllInputs( children[ i ], event_mask );
  171. }
  172. free( children );
  173. }
  174. // Grabs the cursor, be wary that setCursor changes the mouse masks.
  175. // waittime is how long grabCursor can repeatedly try to grab the cursor, if it fails to grab.
  176. // This is because tiling window managers like i3 grab the mouse while holding down certain keys,
  177. // while these certain keys also launch slop.
  178. int slop::XEngine::grabCursor( slop::CursorType type, double waittime ) {
  179. if ( !m_good ) {
  180. return EXIT_FAILURE;
  181. }
  182. int xfontcursor = makeCursor( type );
  183. int err = XGrabPointer( m_display, m_root, True,
  184. PointerMotionMask | ButtonPressMask | ButtonReleaseMask | EnterWindowMask,
  185. GrabModeAsync, GrabModeAsync, None, xfontcursor, CurrentTime );
  186. double accumulationtime = 0;
  187. int timestep = 10000; // in microseconds
  188. while ( err != GrabSuccess && accumulationtime < waittime ) {
  189. err = XGrabPointer( m_display, m_root, True,
  190. PointerMotionMask | ButtonPressMask | ButtonReleaseMask | EnterWindowMask,
  191. GrabModeAsync, GrabModeAsync, None, xfontcursor, CurrentTime );
  192. usleep( timestep );
  193. accumulationtime += double( timestep/1000000.f );
  194. }
  195. if ( err != GrabSuccess ) {
  196. fprintf( stderr, "Error: Failed to grab X cursor.\n" );
  197. switch( err ) {
  198. case 1:
  199. fprintf( stderr, " The cursor is already grabbed by another application.\n" );
  200. break;
  201. case 2:
  202. fprintf( stderr, " The cursor grab was initiated at an invalid time (in the past?) .\n" );
  203. break;
  204. case 3:
  205. fprintf( stderr, " The cursor is not viewable or outside of the bounds of the root window.\n" );
  206. break;
  207. case 4:
  208. fprintf( stderr, " The grab is frozen already by an active grab by another application.\n" );
  209. break;
  210. default:
  211. break;
  212. }
  213. fprintf( stderr, " This can be caused by launching slop weirdly.\n" );
  214. return EXIT_FAILURE;
  215. }
  216. // Quickly set the mouse position so we don't have to worry about x11 generating an event.
  217. Window root, child;
  218. int mx, my;
  219. int wx, wy;
  220. unsigned int mask;
  221. XQueryPointer( m_display, m_root, &root, &child, &mx, &my, &wx, &wy, &mask );
  222. m_mousex = mx;
  223. m_mousey = my;
  224. // Get the deepest available window.
  225. Window test = child;
  226. while( test ) {
  227. child = test;
  228. XQueryPointer( m_display, child, &root, &test, &mx, &my, &wx, &wy, &mask );
  229. }
  230. m_hoverWindow = child;
  231. return EXIT_SUCCESS;
  232. }
  233. int slop::XEngine::releaseCursor() {
  234. if ( !m_good ) {
  235. return EXIT_FAILURE;
  236. }
  237. XUngrabPointer( m_display, CurrentTime );
  238. return EXIT_SUCCESS;
  239. }
  240. void slop::XEngine::tick() {
  241. if ( !m_good ) {
  242. return;
  243. }
  244. XEvent event;
  245. while ( XPending( m_display ) ) {
  246. XNextEvent( m_display, &event );
  247. switch ( event.type ) {
  248. case MotionNotify: {
  249. m_mousex = event.xmotion.x;
  250. m_mousey = event.xmotion.y;
  251. break;
  252. }
  253. case ButtonPress: {
  254. // Our pitiful mouse manager--
  255. if ( m_mouse.size() > event.xbutton.button ) {
  256. m_mouse.at( event.xbutton.button ) = true;
  257. } else {
  258. m_mouse.resize( event.xbutton.button+2, false );
  259. m_mouse.at( event.xbutton.button ) = true;
  260. }
  261. break;
  262. }
  263. case EnterNotify: {
  264. if ( event.xcrossing.subwindow != None ) {
  265. m_hoverWindow = event.xcrossing.subwindow;
  266. } else {
  267. m_hoverWindow = event.xcrossing.window;
  268. }
  269. break;
  270. }
  271. case ButtonRelease: {
  272. if ( m_mouse.size() > event.xbutton.button ) {
  273. m_mouse.at( event.xbutton.button ) = false;
  274. } else {
  275. m_mouse.resize( event.xbutton.button+2, false );
  276. m_mouse.at( event.xbutton.button ) = false;
  277. }
  278. break;
  279. }
  280. default: break;
  281. }
  282. }
  283. }
  284. // This converts an enum into a preallocated cursor, the cursor will automatically deallocate itself on ~XEngine
  285. Cursor slop::XEngine::makeCursor( slop::CursorType type ) {
  286. int xfontcursor;
  287. switch ( type ) {
  288. default:
  289. case Left: xfontcursor = XC_left_ptr; break;
  290. case Crosshair: xfontcursor = XC_crosshair; break;
  291. case Cross: xfontcursor = XC_cross; break;
  292. case UpperLeftCorner: xfontcursor = XC_ul_angle; break;
  293. case UpperRightCorner: xfontcursor = XC_ur_angle; break;
  294. case LowerLeftCorner: xfontcursor = XC_ll_angle; break;
  295. case LowerRightCorner: xfontcursor = XC_lr_angle; break;
  296. case Dot: xfontcursor = XC_dot; break;
  297. case Box: xfontcursor = 40; break;
  298. }
  299. Cursor newcursor = 0;
  300. if ( m_cursors.size() > (unsigned int)xfontcursor ) {
  301. newcursor = m_cursors.at( xfontcursor );
  302. }
  303. if ( !newcursor ) {
  304. newcursor = XCreateFontCursor( m_display, xfontcursor );
  305. m_cursors.resize( xfontcursor+2, 0 );
  306. m_cursors.at( xfontcursor ) = newcursor;
  307. }
  308. return newcursor;
  309. }
  310. slop::CursorType slop::XEngine::getCursor() {
  311. if ( m_currentCursor ) {
  312. return m_currentCursor;
  313. } else {
  314. return slop::Left;
  315. }
  316. }
  317. // Swaps out the current cursor, bewary that XChangeActivePointerGrab also resets masks, so if you change the mouse masks on grab you need to change them here too.
  318. void slop::XEngine::setCursor( slop::CursorType type ) {
  319. if ( !m_good ) {
  320. return;
  321. }
  322. m_currentCursor = type;
  323. Cursor xfontcursor = makeCursor( type );
  324. XChangeActivePointerGrab( m_display,
  325. PointerMotionMask | ButtonPressMask | ButtonReleaseMask,
  326. xfontcursor, CurrentTime );
  327. }
  328. void slop::WindowRectangle::applyPadding( int padding ) {
  329. if ( (int)m_width + padding*2 >= 0 ) {
  330. m_x -= padding;
  331. m_width += padding*2;
  332. }
  333. if ( (int)m_height + padding*2 >= 0 ) {
  334. m_y -= padding;
  335. m_height += padding*2;
  336. }
  337. }
  338. Window slop::WindowRectangle::getWindow() {
  339. return m_window;
  340. }
  341. void slop::WindowRectangle::applyMinMaxSize( unsigned int minimumsize, unsigned int maximumsize ) {
  342. if ( minimumsize > maximumsize && maximumsize > 0 ) {
  343. fprintf( stderr, "Error: minimumsize is greater than maximumsize.\n" );
  344. exit( 1 );
  345. }
  346. if ( m_width < minimumsize ) {
  347. int diff = minimumsize - m_width;
  348. m_width = minimumsize;
  349. m_x -= diff/2;
  350. }
  351. if ( m_height < minimumsize ) {
  352. int diff = minimumsize - m_height;
  353. m_height = minimumsize;
  354. m_y -= diff/2;
  355. }
  356. if ( maximumsize > 0 ) {
  357. if ( m_width > maximumsize ) {
  358. int diff = m_width;
  359. m_width = maximumsize;
  360. // Center in the center of the window
  361. m_x += diff/2 - maximumsize/2;
  362. }
  363. if ( m_height > maximumsize ) {
  364. int diff = m_height;
  365. m_height = maximumsize;
  366. // Center in the center of the window
  367. m_y += diff/2 - maximumsize/2;
  368. }
  369. }
  370. }
  371. void slop::WindowRectangle::setGeometry( Window win, bool decorations ) {
  372. if ( decorations ) {
  373. Window root, parent, test, junk;
  374. Window* childlist;
  375. unsigned int ujunk;
  376. // Try to find the actual decorations.
  377. test = win;
  378. int status = XQueryTree( xengine->m_display, test, &root, &parent, &childlist, &ujunk);
  379. free( childlist );
  380. while( parent != root ) {
  381. if ( !parent || !status ) {
  382. break;
  383. }
  384. test = parent;
  385. status = XQueryTree( xengine->m_display, test, &root, &parent, &childlist, &ujunk);
  386. free( childlist );
  387. }
  388. // test contains the window we're screenshotting.
  389. m_window = test;
  390. // Once found, proceed normally.
  391. if ( test && parent == root && status ) {
  392. XWindowAttributes attr;
  393. XGetWindowAttributes( xengine->m_display, test, &attr );
  394. m_width = attr.width;
  395. m_height = attr.height;
  396. m_border = attr.border_width;
  397. XTranslateCoordinates( xengine->m_display, test, attr.root, -attr.border_width, -attr.border_width, &(m_x), &(m_y), &junk );
  398. // We make sure we include borders, since we want decorations.
  399. m_width += m_border * 2;
  400. m_height += m_border * 2;
  401. }
  402. return;
  403. }
  404. Window junk;
  405. // Now here we should be able to just use whatever we get.
  406. XWindowAttributes attr;
  407. // We use XGetWindowAttributes to know our root window.
  408. XGetWindowAttributes( xengine->m_display, win, &attr );
  409. //m_x = attr.x;
  410. //m_y = attr.y;
  411. m_width = attr.width;
  412. m_height = attr.height;
  413. m_border = attr.border_width;
  414. XTranslateCoordinates( xengine->m_display, win, attr.root, -attr.border_width, -attr.border_width, &(m_x), &(m_y), &junk );
  415. m_window = win;
  416. }