main.cpp 22KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  1. /* main.cpp
  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 <unistd.h>
  21. #include <time.h>
  22. #include <cstdio>
  23. #include <sstream>
  24. #ifdef __MACH__
  25. #include <mach/clock.h>
  26. #include <mach/mach.h>
  27. #endif
  28. #include "x.hpp"
  29. #include "selectrectangle.hpp"
  30. #include "glselectrectangle.hpp"
  31. #include "xselectrectangle.hpp"
  32. #include "cmdline.h"
  33. // Work around lack of clock_gettime in OSX
  34. // https://gist.github.com/jbenet/1087739
  35. void current_utc_time(struct timespec *ts) {
  36. #ifdef __MACH__
  37. // OS X does not have clock_gettime, use clock_get_time
  38. clock_serv_t cclock;
  39. mach_timespec_t mts;
  40. host_get_clock_service( mach_host_self(), CALENDAR_CLOCK, &cclock );
  41. clock_get_time( cclock, &mts );
  42. mach_port_deallocate( mach_task_self(), cclock );
  43. ts->tv_sec = mts.tv_sec;
  44. ts->tv_nsec = mts.tv_nsec;
  45. #else
  46. clock_gettime( CLOCK_REALTIME, ts );
  47. #endif
  48. }
  49. int printSelection( std::string format, bool cancelled, int x, int y, int w, int h, int window ) {
  50. size_t pos = 0;
  51. while ( ( pos = format.find( "%", pos ) ) != std::string::npos ) {
  52. if ( pos + 1 > format.size() ) {
  53. fprintf( stderr, "Format error: %% found at the end of format string.\n" );
  54. return EXIT_FAILURE;
  55. }
  56. std::stringstream foo;
  57. switch( format[ pos + 1 ] ) {
  58. case '%':
  59. format.replace( pos, 2, "%" );
  60. pos += 1;
  61. break;
  62. case 'x':
  63. case 'X':
  64. foo << x;
  65. format.replace( pos, 2, foo.str() );
  66. break;
  67. case 'y':
  68. case 'Y':
  69. foo << y;
  70. format.replace( pos, 2, foo.str() );
  71. break;
  72. case 'w':
  73. case 'W':
  74. foo << w;
  75. format.replace( pos, 2, foo.str() );
  76. break;
  77. case 'h':
  78. case 'H':
  79. foo << h;
  80. format.replace( pos, 2, foo.str() );
  81. break;
  82. case 'g':
  83. case 'G':
  84. foo << w << 'x' << h << '+' << x << '+' << y;
  85. format.replace( pos, 2, foo.str() );
  86. break;
  87. case 'i':
  88. case 'I':
  89. foo << window;
  90. format.replace( pos, 2, foo.str() );
  91. break;
  92. case 'c':
  93. case 'C':
  94. format.replace( pos, 2, cancelled ? "true" : "false" );
  95. break;
  96. default:
  97. fprintf( stderr, "Format error: %%%c is an unknown replacement identifier.\n", format[ pos + 1 ] );
  98. fprintf( stderr, "Valid replacements: %%x, %%y, %%w, %%h, %%i, %%c, %%.\n" );
  99. return EXIT_FAILURE;
  100. break;
  101. }
  102. }
  103. pos = 0;
  104. while ( ( pos = format.find( "\\", pos ) ) != std::string::npos ) {
  105. if ( pos + 1 > format.size() ) {
  106. break;
  107. }
  108. if ( format[ pos + 1 ] == 'n' ) {
  109. format.replace( pos, 2, "\n" );
  110. }
  111. pos = pos + 1;
  112. }
  113. printf( "%s", format.c_str() );
  114. return EXIT_SUCCESS;
  115. }
  116. int parseColor( std::string arg, float* r, float* g, float* b, float* a ) {
  117. std::string copy = arg;
  118. int find = copy.find( "," );
  119. while( find != (int)copy.npos ) {
  120. copy.at( find ) = ' ';
  121. find = copy.find( "," );
  122. }
  123. // Just in case we didn't include an alpha value
  124. *a = 1;
  125. int num = sscanf( copy.c_str(), "%f %f %f %f", r, g, b, a );
  126. if ( num != 3 && num != 4 ) {
  127. return EXIT_FAILURE;
  128. }
  129. return EXIT_SUCCESS;
  130. }
  131. void constrain( int sx, int sy, int ex, int ey, int padding, int minimumsize, int maximumsize, int* rsx, int* rsy, int* rex, int* rey ) {
  132. if ( minimumsize > maximumsize && maximumsize > 0 ) {
  133. fprintf( stderr, "Error: minimumsize is greater than maximumsize.\n" );
  134. exit( 1 );
  135. }
  136. int x = std::min( sx, ex );
  137. int y = std::min( sy, ey );
  138. // We add one to make sure we select the pixel under the mouse.
  139. int w = std::max( sx, ex ) - x + 1;
  140. int h = std::max( sy, ey ) - y + 1;
  141. // Make sure we don't turn inside out...
  142. if ( w + padding*2 >= 0 ) {
  143. x -= padding;
  144. w += padding*2;
  145. }
  146. if ( h + padding*2 >= 0 ) {
  147. y -= padding;
  148. h += padding*2;
  149. }
  150. if ( w < minimumsize ) {
  151. int diff = minimumsize - w;
  152. w = minimumsize;
  153. x -= diff/2;
  154. }
  155. if ( h < minimumsize ) {
  156. int diff = minimumsize - h;
  157. h = minimumsize;
  158. y -= diff/2;
  159. }
  160. if ( maximumsize > 0 ) {
  161. if ( w > maximumsize ) {
  162. int diff = w;
  163. w = maximumsize;
  164. x += diff/2 - maximumsize/2;
  165. }
  166. if ( h > maximumsize ) {
  167. int diff = h;
  168. h = maximumsize;
  169. y += diff/2 - maximumsize/2;
  170. }
  171. }
  172. // Center around mouse if we have a fixed size.
  173. if ( maximumsize == minimumsize && w == maximumsize && h == maximumsize ) {
  174. x = ex - maximumsize/2;
  175. y = ey - maximumsize/2;
  176. }
  177. *rsx = x;
  178. *rsy = y;
  179. *rex = x + w;
  180. *rey = y + h;
  181. }
  182. // Some complicated key detection to replicate key repeating
  183. bool keyRepeat( KeySym key, double curtime, double repeatdelay, double* time, bool* memory ) {
  184. if ( xengine->keyPressed( key ) != *memory ) {
  185. if ( xengine->keyPressed( key ) ) {
  186. *memory = true;
  187. *time = curtime;
  188. return true;
  189. } else {
  190. *memory = false;
  191. }
  192. }
  193. if ( xengine->keyPressed( key ) && curtime - *time > repeatdelay ) {
  194. return true;
  195. }
  196. return false;
  197. }
  198. int app( int argc, char** argv ) {
  199. gengetopt_args_info options;
  200. int err = cmdline_parser( argc, argv, &options );
  201. if ( err != EXIT_SUCCESS ) {
  202. return EXIT_FAILURE;
  203. }
  204. int state = 0;
  205. bool running = true;
  206. bool opengl = options.opengl_flag;
  207. slop::SelectRectangle* selection = NULL;
  208. Window window = None;
  209. Window windowmemory = None;
  210. std::string xdisplay;
  211. if ( options.xdisplay_given ) {
  212. xdisplay = options.xdisplay_arg;
  213. } else {
  214. // If we weren't specifically given a xdisplay, we try
  215. // to parse it from environment variables
  216. char* display = getenv( "DISPLAY" );
  217. if ( display ) {
  218. xdisplay = display;
  219. } else {
  220. fprintf( stderr, "Warning: Failed to parse environment variable: DISPLAY. Using \":0\" instead.\n" );
  221. xdisplay = ":0";
  222. }
  223. }
  224. int padding = options.padding_arg;
  225. int borderSize = options.bordersize_arg;
  226. int tolerance = options.tolerance_arg;
  227. float r, g, b, a;
  228. err = parseColor( options.color_arg, &r, &g, &b, &a );
  229. if ( err != EXIT_SUCCESS ) {
  230. fprintf( stderr, "Error parsing color %s\n", options.color_arg );
  231. return EXIT_FAILURE;
  232. }
  233. float gracetime;
  234. err = sscanf( options.gracetime_arg, "%f", &gracetime );
  235. if ( err != 1 ) {
  236. fprintf( stderr, "Error parsing %s as a float for gracetime!\n", options.gracetime_arg );
  237. return EXIT_FAILURE;
  238. }
  239. bool highlight = options.highlight_flag;
  240. bool keyboard = !options.nokeyboard_flag;
  241. bool decorations = !options.nodecorations_flag;
  242. struct timespec start, time;
  243. int xoffset = 0;
  244. int yoffset = 0;
  245. int cx = 0;
  246. int cy = 0;
  247. int xmem = 0;
  248. int ymem = 0;
  249. int wmem = 0;
  250. int hmem = 0;
  251. int minimumsize = options.min_arg;
  252. int maximumsize = options.max_arg;
  253. bool pressedMemory[4];
  254. double pressedTime[4];
  255. for ( int i=0;i<4;i++ ) {
  256. pressedMemory[ i ] = false;
  257. pressedTime[ i ] = 0;
  258. }
  259. std::string format = options.format_arg;
  260. bool magenabled = options.magnify_flag;
  261. float magstrength = options.magstrength_arg;
  262. if ( options.magpixels_arg < 0 ) {
  263. fprintf( stderr, "Error: --magpixels < 0, it's an unsigned integer you twat. Stop trying to underflow me!\n" );
  264. return EXIT_FAILURE;
  265. }
  266. unsigned int magpixels = (unsigned int)options.magpixels_arg;
  267. cmdline_parser_free( &options );
  268. // First we set up the x interface and grab the mouse,
  269. // if we fail for either we exit immediately.
  270. err = xengine->init( xdisplay.c_str() );
  271. if ( err != EXIT_SUCCESS ) {
  272. printSelection( format, true, 0, 0, 0, 0, None );
  273. return EXIT_FAILURE;
  274. }
  275. if ( !slop::isSelectRectangleSupported() ) {
  276. fprintf( stderr, "Error: Your X server doesn't support the XShape extension. There's nothing slop can do about this!\n" );
  277. fprintf( stderr, " Try updating X and making sure you have XExtensions installed. (/usr/lib/libXext.so, /usr/include/X11/extensions/shape.h)\n" );
  278. return EXIT_FAILURE;
  279. }
  280. err = xengine->grabCursor( slop::Cross, gracetime );
  281. if ( err != EXIT_SUCCESS ) {
  282. printSelection( format, true, 0, 0, 0, 0, None );
  283. return EXIT_FAILURE;
  284. }
  285. if ( keyboard ) {
  286. err = xengine->grabKeyboard();
  287. if ( err ) {
  288. fprintf( stderr, "Warning: Failed to grab the keyboard. This is non-fatal, keyboard presses might fall through to other applications.\n" );
  289. }
  290. }
  291. current_utc_time( &start );
  292. double deltatime = 0;
  293. double curtime = double( start.tv_sec*1000000000L + start.tv_nsec )/1000000000.f;
  294. while ( running ) {
  295. current_utc_time( &time );
  296. // "ticking" the xengine makes it process all queued events.
  297. xengine->tick();
  298. // If the user presses any key on the keyboard, exit the application.
  299. // Make sure at least gracetime has passed before allowing canceling
  300. double newtime = double( time.tv_sec*1000000000L + time.tv_nsec )/1000000000.f;
  301. deltatime = newtime-curtime;
  302. curtime = newtime;
  303. double starttime = double( start.tv_sec*1000000000L + start.tv_nsec )/1000000000.f;
  304. if ( curtime - starttime > gracetime ) {
  305. if ( keyRepeat( XK_Up, curtime, 0.5, &pressedTime[ 0 ], &pressedMemory[ 0 ] ) ) {
  306. yoffset -= 1;
  307. }
  308. if ( keyRepeat( XK_Down, curtime, 0.5, &pressedTime[ 1 ], &pressedMemory[ 1 ] ) ) {
  309. yoffset += 1;
  310. }
  311. if ( keyRepeat( XK_Left, curtime, 0.5, &pressedTime[ 2 ], &pressedMemory[ 2 ] ) ) {
  312. xoffset -= 1;
  313. }
  314. if ( keyRepeat( XK_Right, curtime, 0.5, &pressedTime[ 3 ], &pressedMemory[ 3 ] ) ) {
  315. xoffset += 1;
  316. }
  317. // If we pressed enter we move the state onward.
  318. if ( xengine->keyPressed( XK_Return ) ) {
  319. // If we're highlight windows, just select the active window.
  320. if ( state == 0 ) {
  321. state = 1;
  322. // If we're making a custom selection, select the custom selection.
  323. } else if ( state == 2 ) {
  324. state = 3;
  325. }
  326. }
  327. // If we press any key other than the arrow keys or enter key, we shut down!
  328. if ( !( xengine->keyPressed( XK_Up ) || xengine->keyPressed( XK_Down ) || xengine->keyPressed( XK_Left ) || xengine->keyPressed( XK_Right ) ) &&
  329. !( xengine->keyPressed( XK_Return ) ) &&
  330. ( ( xengine->anyKeyPressed() && keyboard ) || xengine->mouseDown( 3 ) ) ) {
  331. printSelection( format, true, 0, 0, 0, 0, None );
  332. fprintf( stderr, "User pressed key. Canceled selection.\n" );
  333. state = -1;
  334. running = false;
  335. }
  336. }
  337. // Our adorable little state manager will handle what state we're in.
  338. switch ( state ) {
  339. default: {
  340. break;
  341. }
  342. case 0: {
  343. // If xengine has found a window we're hovering over (or if it changed)
  344. // create a rectangle around it so the user knows he/she can click on it.
  345. // --but only if the user wants us to
  346. if ( window != xengine->m_hoverWindow && tolerance > 0 ) {
  347. slop::WindowRectangle t;
  348. t.setGeometry( xengine->m_hoverWindow, decorations );
  349. t.applyPadding( padding );
  350. t.applyMinMaxSize( minimumsize, maximumsize );
  351. // Make sure we only apply offsets to windows that we've forcibly removed decorations on.
  352. if ( !selection ) {
  353. if ( opengl ) {
  354. selection = new slop::GLSelectRectangle( t.m_x, t.m_y,
  355. t.m_x + t.m_width,
  356. t.m_y + t.m_height,
  357. borderSize,
  358. highlight,
  359. r, g, b, a );
  360. // Haha why is this so hard to cast?
  361. ((slop::GLSelectRectangle*)(selection))->setMagnifySettings( magenabled, magstrength, magpixels );
  362. ((slop::GLSelectRectangle*)(selection))->setTheme( true, "gothic" );
  363. } else {
  364. selection = new slop::XSelectRectangle( t.m_x, t.m_y,
  365. t.m_x + t.m_width,
  366. t.m_y + t.m_height,
  367. borderSize,
  368. highlight,
  369. r, g, b, a );
  370. }
  371. } else {
  372. selection->setGeo( t.m_x, t.m_y, t.m_x + t.m_width, t.m_y + t.m_height );
  373. }
  374. //window = xengine->m_hoverWindow;
  375. // Since WindowRectangle can select different windows depending on click location...
  376. window = t.getWindow();
  377. }
  378. if ( selection ) {
  379. selection->update( deltatime );
  380. }
  381. // If the user clicked we move on to the next state.
  382. if ( xengine->mouseDown( 1 ) ) {
  383. state++;
  384. }
  385. break;
  386. }
  387. case 1: {
  388. // Set the mouse position of where we clicked, used so that click tolerance doesn't affect the rectangle's position.
  389. cx = xengine->m_mousex;
  390. cy = xengine->m_mousey;
  391. // Make sure we don't have un-seen applied offsets.
  392. xoffset = 0;
  393. yoffset = 0;
  394. // Also remember where the original selection was
  395. if ( selection ) {
  396. xmem = selection->m_x;
  397. ymem = selection->m_y;
  398. wmem = selection->m_width;
  399. hmem = selection->m_height;
  400. } else {
  401. xmem = cx;
  402. ymem = cy;
  403. }
  404. state++;
  405. break;
  406. }
  407. case 2: {
  408. // It's possible that our selection doesn't exist still, lets make sure it actually gets created here.
  409. if ( !selection ) {
  410. int sx, sy, ex, ey;
  411. constrain( cx, cy, xengine->m_mousex, xengine->m_mousey, padding, minimumsize, maximumsize, &sx, &sy, &ex, &ey );
  412. if ( opengl ) {
  413. selection = new slop::GLSelectRectangle( sx, sy,
  414. ex, ey,
  415. borderSize,
  416. highlight,
  417. r, g, b, a );
  418. // Haha why is this so hard to cast?
  419. ((slop::GLSelectRectangle*)(selection))->setMagnifySettings( magenabled, magstrength, magpixels );
  420. ((slop::GLSelectRectangle*)(selection))->setTheme( true, "gothic" );
  421. } else {
  422. selection = new slop::XSelectRectangle( sx, sy,
  423. ex, ey,
  424. borderSize,
  425. highlight,
  426. r, g, b, a );
  427. }
  428. }
  429. windowmemory = window;
  430. // If the user has let go of the mouse button, we'll just
  431. // continue to the next state.
  432. if ( !xengine->mouseDown( 1 ) ) {
  433. state++;
  434. break;
  435. }
  436. // Check to make sure the user actually wants to drag for a selection before moving things around.
  437. int w = xengine->m_mousex - cx;
  438. int h = xengine->m_mousey - cy;
  439. if ( ( std::abs( w ) < tolerance && std::abs( h ) < tolerance ) ) {
  440. // We make sure the selection rectangle stays on the window we had selected
  441. selection->setGeo( xmem, ymem, xmem + wmem, ymem + hmem );
  442. selection->update( deltatime );
  443. xengine->setCursor( slop::Left );
  444. // Make sure
  445. window = windowmemory;
  446. continue;
  447. }
  448. // If we're not selecting a window.
  449. windowmemory = window;
  450. window = None;
  451. // We also detect which way the user is pulling and set the mouse icon accordingly.
  452. bool x = cx > xengine->m_mousex;
  453. bool y = cy > xengine->m_mousey;
  454. if ( ( selection->m_width <= 1 && selection->m_height <= 1 ) || ( minimumsize == maximumsize && minimumsize != 0 && maximumsize != 0 ) ) {
  455. xengine->setCursor( slop::Cross );
  456. } else if ( !x && !y ) {
  457. xengine->setCursor( slop::LowerRightCorner );
  458. } else if ( x && !y ) {
  459. xengine->setCursor( slop::LowerLeftCorner );
  460. } else if ( !x && y ) {
  461. xengine->setCursor( slop::UpperRightCorner );
  462. } else if ( x && y ) {
  463. xengine->setCursor( slop::UpperLeftCorner );
  464. }
  465. // Apply padding and minimum size adjustments.
  466. int sx, sy, ex, ey;
  467. constrain( cx, cy, xengine->m_mousex, xengine->m_mousey, padding, minimumsize, maximumsize, &sx, &sy, &ex, &ey );
  468. // Set the selection rectangle's dimensions to mouse movement.
  469. selection->setGeo( sx + xoffset, sy + yoffset, ex-1, ey-1 );
  470. selection->update( deltatime );
  471. break;
  472. }
  473. case 3: {
  474. int x, y, w, h;
  475. // Exit the utility after this state runs once.
  476. running = false;
  477. // We pull the dimensions and positions from the selection rectangle.
  478. // The selection rectangle automatically converts the positions and
  479. // dimensions to absolute coordinates when we set them earilier.
  480. x = selection->m_x;
  481. y = selection->m_y;
  482. w = selection->m_width;
  483. h = selection->m_height;
  484. // Delete the rectangle, which will remove it from the screen.
  485. delete selection;
  486. // Make sure if no window was specifically specified, that we output the root window.
  487. Window temp = window;
  488. if ( temp == None ) {
  489. temp = xengine->m_root;
  490. }
  491. // Print the selection :)
  492. printSelection( format, false, x, y, w, h, temp );
  493. break;
  494. }
  495. }
  496. // This sleep is required because drawing the rectangles is a very expensive task that acts really weird with Xorg when called as fast as possible.
  497. // 0.01 seconds
  498. usleep( 10000 );
  499. }
  500. xengine->releaseCursor();
  501. xengine->releaseKeyboard();
  502. // Try to process any last-second requests.
  503. //xengine->tick();
  504. // Clean up global classes.
  505. delete xengine;
  506. // Sleep for 0.05 seconds to ensure everything was cleaned up. (Without this, slop's window often shows up in screenshots.)
  507. usleep( 50000 );
  508. // If we canceled the selection, return error.
  509. if ( state == -1 ) {
  510. return EXIT_FAILURE;
  511. }
  512. return EXIT_SUCCESS;
  513. }
  514. int main( int argc, char** argv ) {
  515. try {
  516. return app( argc, argv );
  517. } catch( std::bad_alloc const& exception ) {
  518. fprintf( stderr, "Couldn't allocate enough memory! No space left in RAM." );
  519. return EXIT_FAILURE;
  520. } catch( std::exception const& exception ) {
  521. fprintf( stderr, "Unhandled Exception Thrown: %s\n", exception.what() );
  522. return EXIT_FAILURE;
  523. } catch( ... ) {
  524. fprintf( stderr, "Unknown Exception Thrown!\n" );
  525. return EXIT_FAILURE;
  526. }
  527. }