main.cpp 19KB

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