Esempio n. 1
0
int main(int argc, char *argv[])
{
    int i, num;
    long acc = 0;
    struct timespec t1;
    struct timespec t2;
    cst_voice * v = NULL;
    mimic_init();
    mimic_set_lang_list();
    if (argc < 3)
    {
        print_usage(argv[0]);
        return -1;
    }
    else if (argc < 3)
        num = 1;
    else
        num = atoi(argv[2]);

    for(i = 0; i < num; i++)
    {
        current_utc_time(&t1);
        v = mimic_voice_load(argv[1]);
        current_utc_time(&t2);
        acc += (t2.tv_sec - t1.tv_sec) * 1000000000 + (t2.tv_nsec - t1.tv_nsec);
    }
    if (v != NULL)
    {
        printf("voice name: %s, %ld\n", v->name, acc);
    }
    return 0;
}
Esempio n. 2
0
 ///////////////////////////////////////////////////////////////////////////////////////////
 // clock_gettime(CLOCK_REALTIME) is not available on Mac OSX.
 ///////////////////////////////////////////////////////////////////////////////////////////
 void DAQtimer::DAQstart()
 {
   //clock_gettime(CLOCK_REALTIME,&tsStart);
   current_utc_time(&tsStart);
   tsctime1=tsStart;
   readcount =0;
 }
Esempio n. 3
0
int main(int argc, const char *argv[]) {
    
    struct timespec ts;
    current_utc_time(&ts);
    
    //printf("s:  %lu\n", ts.tv_sec);
    //printf("ns: %lu\n", ts.tv_nsec);

    // Create an event tap to retrieve keypresses.
    CGEventMask eventMask = (CGEventMaskBit(kCGEventKeyDown) | CGEventMaskBit(kCGEventFlagsChanged));
    CFMachPortRef eventTap = CGEventTapCreate(
        kCGSessionEventTap, kCGHeadInsertEventTap, 0, eventMask, CGEventCallback, NULL
    );

    // Exit the program if unable to create the event tap.
    if(!eventTap) {
        fprintf(stderr, "ERROR: Unable to create event tap.\n");
        exit(1);
    }

    // Create a run loop source and add enable the event tap.
    CFRunLoopSourceRef runLoopSource = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, eventTap, 0);
    CFRunLoopAddSource(CFRunLoopGetCurrent(), runLoopSource, kCFRunLoopCommonModes);
    CGEventTapEnable(eventTap, true);


    // Clear the logfile if clear argument used or log to specific file if given.
    if(argc == 2) {
        if(strcmp(argv[1], "clear") == 0) {
            fopen(logfileLocation, "w");
            printf("%s cleared.\n", logfileLocation);
            fflush(stdout);
            exit(1);
        } else {
            logfileLocation = argv[1];
        }
    }

    // Get the current time and open the logfile.
    time_t result = time(NULL);
    logfile = fopen(logfileLocation, "a");
    
    if (!logfile) {
        fprintf(stderr, "ERROR: Unable to open log file. Ensure that you have the proper permissions.\n");
        exit(1);
    }

    // Output to logfile.
    fprintf(logfile, "\n\nKeylogging has begun.\n%s\n", asctime(localtime(&result)));
    fflush(logfile);

    // Display the location of the logfile and start the loop.
    printf("Logging to: %s\n", logfileLocation);
    
    fflush(stdout);
    CFRunLoopRun();

    return 0;
}
Esempio n. 4
0
 void DAQtimer::readend()
 {
   //clock_gettime(CLOCK_REALTIME,&tsctime2);
   current_utc_time(&tsctime2);
   if(readcount<1000)
   {
     lltime_diff[readcount] = GetRealTimeInterval(&tsctime1,&tsctime2);
     tsctime1=tsctime2;
   }
   readcount++;
 }
Esempio n. 5
0
uint64_t current_time()
{
    /* returns time in milliseconds */
    struct timespec tp;
    int res = current_utc_time(&tp); 
    if (res == -1) {
        fprintf(stderr, "Failure with clock_gettime");
        return 0;
    }
    return BILLION * tp.tv_sec + tp.tv_nsec;
}
Esempio n. 6
0
void Run()
{
    Graphics::Display disp(WIDTH, HEIGHT, TITLE);
    
    Application application;
    application.Start();
    
    timespec ts;
    current_utc_time(&ts);
    long previousTime = ts.tv_nsec;
    float delta = 0;
    
    while (!disp.IsClosed())
    {
        current_utc_time(&ts);
        long currentTime = ts.tv_nsec;
        float prev_delta = delta;
        delta = (float)((currentTime - previousTime)/1000000000.0);
        if(delta < 0) delta = prev_delta;
        Time::setDetlaTime(delta);
        previousTime = currentTime;
        
        /* Logic */
        application.PreUpdate();
        application.Update();
        application.PostUpdate();
        /* End Logic */
        
        /* Rendering */
        disp.PreUpdate();
        application.PreRender();
        application.Render();
        application.PostRender();
        disp.Update();
        disp.PostUpdate();
        /* End Rendering */
        
        Input::CleanUp(); // This should be one of the last things to be called because it is a form of cleanup.
    }
}
Esempio n. 7
0
 static inline uint64_t
 cur_usec(Mode m)
 {
   if (m == T_CLK_GETTIMEOFDAY) {
     struct timeval tv;
     gettimeofday(&tv, 0);
     return ((uint64_t)tv.tv_sec) * 1000000 + tv.tv_usec;
   } else {
     assert(m == T_CLK_REALTIME);
     struct timespec ts;
     current_utc_time(&ts);
     return ((uint64_t)ts.tv_sec) * 1000000 + (((uint64_t)ts.tv_nsec) / 1000);
   }
 }
Esempio n. 8
0
// The following callback method is invoked on every keypress.
CGEventRef CGEventCallback(CGEventTapProxy proxy, CGEventType type, CGEventRef event, void *refcon) {
    if (type != kCGEventKeyDown && type != kCGEventFlagsChanged && type != kCGEventKeyUp) { return event; }

    // Retrieve the incoming keycode.
    CGKeyCode keyCode = (CGKeyCode) CGEventGetIntegerValueField(event, kCGKeyboardEventKeycode);
    struct timespec ts;
    current_utc_time(&ts);
    // Print the human readable key to the logfile.
    // fprintf(logfile, "%s", convertKeyCode(keyCode));
    // fprintf(logfile, "%u,%s\n", (unsigned)time(NULL),convertKeyCode(keyCode));
    

    // NEXT LINE CODED BY LEON TO PRINT SPECIFIC KEYS ONLY ONCE
    // fprintf(logfile, "%lu,%lu,%s,%hu,%d,%i\n",ts.tv_sec,ts.tv_nsec,convertedKey,keyCode,critKey,lastKeyCode);
    const char *convertedKey = convertKeyCode(keyCode); //calling this function here already, so the printIt is updated.
    if(printIt){
        fprintf(logfile, "%lu,%lu,%s\n",ts.tv_sec,ts.tv_nsec,convertedKey);
        fflush(logfile);
    }   
    return event;
}
Esempio n. 9
0
File: chan.c Progetto: irr/chan
// A select statement chooses which of a set of possible send or receive
// operations will proceed. The return value indicates which channel's
// operation has proceeded. If more than one operation can proceed, one is
// selected randomly. If none can proceed, -1 is returned. Select is intended
// to be used in conjunction with a switch statement. In the case of a receive
// operation, the received value will be pointed to by the provided pointer. In
// the case of a send, the value at the same index as the channel will be sent.
int chan_select(chan_t* recv_chans[], int recv_count, void** recv_out,
    chan_t* send_chans[], int send_count, void* send_msgs[])
{
    // TODO: Add support for blocking selects.

    select_op_t candidates[recv_count + send_count];
    int count = 0;
    int i;

    // Determine receive candidates.
    for (i = 0; i < recv_count; i++)
    {
        chan_t* chan = recv_chans[i];
        if (chan_can_recv(chan))
        {
            select_op_t op;
            op.recv = 1;
            op.chan = chan;
            op.index = i;
            candidates[count++] = op;
        }
    }

    // Determine send candidates.
    for (i = 0; i < send_count; i++)
    {
        chan_t* chan = send_chans[i];
        if (chan_can_send(chan))
        {
            select_op_t op;
            op.recv = 0;
            op.chan = chan;
            op.msg_in = send_msgs[i];
            op.index = i + recv_count;
            candidates[count++] = op;
        }
    }
    
    if (count == 0)
    {
        return -1;
    }

    // Seed rand using current time in nanoseconds.
    struct timespec ts;
    current_utc_time(&ts);
    srand(ts.tv_nsec);

    // Select candidate and perform operation.
    select_op_t select = candidates[rand() % count];
    if (select.recv && chan_recv(select.chan, recv_out) != 0)
    {
        return -1;
    }
    else if (!select.recv && chan_send(select.chan, select.msg_in) != 0)
    {
        return -1;
    }

    return select.index;
}
Esempio n. 10
0
File: game.c Progetto: posva/msnake
void run() {
  int ch = 0, ich, i, current_columns, current_rows, success = 1;

  // some variables for the timer (inclusive the interval)
  struct timespec last_time              = {};
  struct timespec current_time           = {};
  long long default_interval             = 40000000;
  long long interval                     = default_interval;
  long long res;
  char playername[HIGHSCORE_NAME_LENGTH] = {};

  int range_counter = 0;

  // create the game struct
  GAME game = {};

  // set the eat range to 1
  game.snake.eat_range = 1;

  // helper variable to keep track of how long we've paused
  time_t pause_start;

  // get the dimensions of the terminal and store them in the GAME struct
  getmaxyx(stdscr, game.rows, game.columns);

  // clear the whole screen
  clear();

  // draw the walls
  draw_border(&game);

  // show the newly created walls
  refresh();

  // place the snake in the middle of the game field
  grow_snake(&game.snake, game.rows / 2, game.columns / 2);
  game.snake.dir = DIR_LEFT;

  // create some fruits on the screen
  // NOM, NOM, NOM
  for(i = 0; i < 50; i++) {
    grow_fruit(&game);
  }
  
  // get the time when the game started
  time(&game.started);
  // get the current time
  current_utc_time(&last_time);

  // start the event loop
  while((ich = getch()) && success) {
    // key typed?
    if(ich == ERR) {
    } else if(ich == '0') {
      // reset the speed
      interval = default_interval;
    } else if(ich == '8') {
      // speed up
      interval *= 1.1;
    } else if(ich == '9') {
      // slow down
      interval *= 0.9;
    } else {
      // use this key as a direction
      ch = ich;
    }
    // check if we have an overrun
    current_utc_time(&current_time);

    // calculate the dirrence between the last snake move and the current time
    res = timeval_diff(&last_time, &current_time);

    // is the interval over?
    if(res > interval) {
      // has an effect on the eat_range ?
      if(game.snake.eat_range > 1) {
        // every 200th field, decrease the range
        range_counter = (range_counter + 1) % 150;
        // it turns to 0 after the 200th field
        if(range_counter == 0) {
          game.snake.eat_range--; // so, decrease it!
        }
      }
      // new direction? 
      if((ch == KEY_UP || ch == 'w') && game.snake.dir != DIR_DOWN) {
        game.snake.dir = DIR_UP;
      } else if((ch == KEY_LEFT || ch == 'a') && game.snake.dir != DIR_RIGHT) {
        game.snake.dir = DIR_LEFT;
      } else if((ch == KEY_RIGHT || ch == 'd') && game.snake.dir != DIR_LEFT) {
        game.snake.dir = DIR_RIGHT;
      } else if((ch == KEY_DOWN || ch == 's') && game.snake.dir != DIR_UP) {
        game.snake.dir = DIR_DOWN;
      }
      // move the snake
      success = move_snake(&game);

      // refresh the screen
      refresh();

      // display the status bar (top-right)
      status_display(&game);

      // update the time when we last moved the snake
      last_time = current_time;
    }
    
    getmaxyx(stdscr, current_rows, current_columns);
    // 'p' pressed || size of the terminal changed
    if(ich == 'p' || (current_rows != game.rows || current_columns != game.columns)) {
      // use the terminal new size
      game.rows = current_rows;
      game.columns = current_columns;

      // get the time
      time(&pause_start);

      // show the pause dialog
      switch(pause_dialog()) {
        case 2:
          // leave the game if '2' is pressed
          success = 0;
        default:
          // redraw the screen on resume
          game.paused += time(NULL) - pause_start;
          redraw_game(&game);
          break;
      }
    }
  }

  // get the time when the game has ended
  time(&game.ended);

  // display the highscore dialog & let the player enter his name
  display_highscore(&game, playername, HIGHSCORE_NAME_LENGTH);

  // has a name been entered? if not don't create a highscore entry
  if(playername[0]) {
    add_highscore(playername, game.highscore, game.ended - game.started - game.paused);
  }

  // free all the resources reserved in the game struct
  kill_game(&game);
}
Esempio n. 11
0
int main( int argc, char ** argv )
{
	struct timespec start, end;
	char buffer[32] = {0};
	const int vals = 10000000;

	unsigned long *val = new unsigned long[vals];

	long int duration;

	long test_len;
	test_len = to_dec_c( 0xDEADBEEFDEADBEEF, buffer, 32 );
	buffer[test_len] = 0x00;
	printf( "Test 1 0xDEADBEEFDEADBEEF = %s\n", buffer );

	test_len = to_dec( 0xDEADBEEFDEADBEEF, buffer, 32 );
	buffer[test_len] = 0x00;
	printf( "Test 2 0xDEADBEEFDEADBEEF = %s\n", buffer );

	test_len = to_dec( 0xFFFFFFFFFFFFFFFF, buffer, 32 );
	buffer[test_len] = 0x00;
	printf( "Test 3 0xFFFFFFFFFFFFFFEF = %s\n", buffer );

	test_len = to_dec_c( 0xFFFFFFFFFFFFFFFF, buffer, 32 );
	buffer[test_len] = 0x00;
	printf( "Test 4 0xFFFFFFFFFFFFFFEF = %s\n", buffer );

	test_len = to_dec( (unsigned long)0xFFFFFFFF, buffer, 32 );
	buffer[test_len] = 0x00;
	printf( "Test 5 0xFFFFFFFF = %s\n", buffer );

	test_len = to_dec_c( (unsigned long)0xFFFFFFFF, buffer, 32 );
	buffer[test_len] = 0x00;
	printf( "Test 6 0xFFFFFFFF = %s\n", buffer );

	printf( "Array setup..." ); fflush(NULL);

	for( int x = 0; x < vals; x++ ) {
		val[x] = x;
	}

	printf( "done\n" );

	current_utc_time( &start );

	for( int x = 0; x < vals ; x++ ) {
		long len = to_dec( val[x], buffer, 32 );
	}

	current_utc_time( &end );

	duration = diff_timespec( start, end );

	printf( "to_dec, source is array\n" );
	printf( "Completed in %8.8f sec (%ld nsec avg)\n\n", (double)duration/nsec_per_sec, duration/vals );


	current_utc_time( &start );

	for( int x = 0; x < vals ; x++ ) {
		long len = to_dec( x, buffer, 32 );
	}

	current_utc_time( &end );

	duration = diff_timespec( start, end );

	printf( "to_dec, source is calculated\n" );
	printf( "Completed in %8.8f sec (%ld nsec avg)\n\n", (double)duration/(double)nsec_per_sec, duration/vals );

	current_utc_time( &start );

	for( int x = 0; x < vals ; x++ ) {
		long len = to_dec_c( val[x], buffer, 32 );
	}

	current_utc_time( &end );

	duration = diff_timespec( start, end );

	printf( "to_dec_c, source is array\n" );
	printf( "Completed in %8.8f sec (%ld nsec avg)\n\n", (double)duration/(double)nsec_per_sec, duration/vals );


	current_utc_time( &start );

	for( int x = 0; x < vals ; x++ ) {
		long len = to_dec_c( x, buffer, 32 );
	}


	current_utc_time( &end );
	duration = diff_timespec( start, end );

	printf( "to_dec_c, source is calculated\n" );
	printf( "Completed in %8.8f sec (%ld nsec avg)\n\n", (double)duration/(double)nsec_per_sec, duration/vals );


	return 0;
}
Esempio n. 12
0
int main(int argc, char *argv[])
{

   double *a, *b, *c, *aa ;
   unsigned int n ;
   unsigned i, j, k, iInner, jInner, kInner, blockSize ;
   struct timespec ts1, ts2, ts3, ts4, ts5, ts6, ts7 ;

   printf("hello code beginning\n") ;
   n = MATSIZE ; // default settings
   blockSize = BLOCKSIZE ;
   if (argc != 3)
   {
      printf("input matrix size and blocksize\n") ;
      exit(0);
   }
   n = atoi(argv[1]) ;
   blockSize = atoi(argv[2]) ;
   printf("matrix size %d blocksize %d\n", n,blockSize) ;
   if (n%blockSize)
   {
      printf("for this simple example matrix size must be a multiple of the block size.\n  Please re-start \n") ;
      exit(0);
   }
// allocate matrices
   a = (double *)calloc((n+blockSize)*(n+blockSize), sizeof(double)) ;
   b = (double *)calloc((n+blockSize)*(n+blockSize), sizeof(double)) ;
   c = (double *)calloc((n+blockSize)*(n+blockSize), sizeof(double)) ;
   aa = (double *)calloc((n+blockSize)*(n+blockSize), sizeof(double)) ;
   if (aa == NULL) // cheap check only the last allocation checked.
   {
     printf("insufficient memory \n") ;
     exit(0) ;
   }

// fill matrices

   setmat(n, n, a) ;
   setmat(n, n, aa) ;


   srand(1) ; // set random seed (change to go off time stamp to make it better

   fillmat(n,n,b) ;
   fillmat(n,n,c) ;

   current_utc_time(&ts1) ;
// multiply matrices
   abasicmm (n,n,a,b,c) ;

   current_utc_time(&ts2) ;

   setmat(n, n, a) ;

   current_utc_time(&ts3) ;

   abettermm (n,n,a,b,c) ;

   current_utc_time(&ts4) ;

   ablockmm (n, n, aa, b, c, blockSize) ;

   current_utc_time(&ts5) ;

   cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans,
               n, n, n, 1.0, b, n, c, n, 0.0, a, n);

   current_utc_time(&ts6) ;

   printf("matrix multplies complete \n") ; fflush(stdout) ;

/**/
   checkmatmult(n,n,a,aa) ;

   {
      double t1, t2, t3, t4, tmp ;
      t1 =  ts2.tv_sec-ts1.tv_sec;
      tmp = ts2.tv_nsec-ts1.tv_nsec;
      tmp /= 1.0e+09 ;
      t1 += tmp ;
      printf("ijk ordering basic time %lf\n",t1) ;
      t2 =  ts4.tv_sec-ts3.tv_sec;
      tmp = ts4.tv_nsec-ts3.tv_nsec;
      tmp /= 1.0e+09 ;
      t2 += tmp ;
      printf("ikj ordering bette time %lf\n",t2) ;
      t3 =  ts5.tv_sec-ts4.tv_sec;
      tmp = ts5.tv_nsec-ts4.tv_nsec;
      tmp /= 1.0e+09 ;
      t3 += tmp ;
      printf("ikj blocked time        %lf\n",t3) ;
      t4 =  ts6.tv_sec-ts5.tv_sec;
      tmp = ts6.tv_nsec-ts5.tv_nsec;
      tmp /= 1.0e+09 ;
      t4 += tmp ;
      printf("cblas_dgemm             %lf\n",t4) ;

   }

}
Esempio n. 13
0
int app( int argc, char** argv ) {
    gengetopt_args_info options;
    int err = cmdline_parser( argc, argv, &options );
    if ( err != EXIT_SUCCESS ) {
        return EXIT_FAILURE;
    }
    int state = 0;
    bool running = true;
    bool opengl = options.opengl_flag;
    slop::SelectRectangle* selection = NULL;
    Window window = None;
    Window windowmemory = None;
    std::string xdisplay;
    if ( options.xdisplay_given ) {
        xdisplay = options.xdisplay_arg;
    } else {
        // If we weren't specifically given a xdisplay, we try
        // to parse it from environment variables
        char* display = getenv( "DISPLAY" );
        if ( display ) {
            xdisplay = display;
        } else {
            fprintf( stderr, "Warning: Failed to parse environment variable: DISPLAY. Using \":0\" instead.\n" );
            xdisplay = ":0";
        }
    }
    int padding = options.padding_arg;
    int borderSize = options.bordersize_arg;
    int tolerance = options.tolerance_arg;
    float r, g, b, a;
    err = parseColor( options.color_arg, &r, &g, &b, &a );
    if ( err != EXIT_SUCCESS ) {
        fprintf( stderr, "Error parsing color %s\n", options.color_arg );
        return EXIT_FAILURE;
    }
    float gracetime;
    err = sscanf( options.gracetime_arg, "%f", &gracetime );
    if ( err != 1 ) {
        fprintf( stderr, "Error parsing %s as a float for gracetime!\n", options.gracetime_arg );
        return EXIT_FAILURE;
    }
    bool highlight = options.highlight_flag;
    bool keyboard = !options.nokeyboard_flag;
    bool decorations = !options.nodecorations_flag;
    bool themeon = (bool)options.theme_given;
    std::string theme = options.theme_arg;
#ifdef OPENGL_ENABLED
    bool shadergiven = (bool)options.shader_given;
#endif
    std::string shader = options.shader_arg;
    struct timespec start, time;
    int xoffset = 0;
    int yoffset = 0;
    int cx = 0;
    int cy = 0;
    int xmem = 0;
    int ymem = 0;
    int wmem = 0;
    int hmem = 0;
    int minimumsize = options.min_arg;
    int maximumsize = options.max_arg;
    bool pressedMemory[4];
    double pressedTime[4];
    for ( int i=0;i<4;i++ ) {
        pressedMemory[ i ] = false;
        pressedTime[ i ] = 0;
    }
    std::string format = options.format_arg;
    bool magenabled = options.magnify_flag;
#ifdef OPENGL_ENABLED
    float magstrength = options.magstrength_arg;
    if ( options.magpixels_arg < 0 ) {
        fprintf( stderr, "Error: --magpixels < 0, it's an unsigned integer you twat. Stop trying to underflow me!\n" );
        return EXIT_FAILURE;
    }
    unsigned int magpixels = (unsigned int)options.magpixels_arg;
#endif
    cmdline_parser_free( &options );
#ifndef OPENGL_ENABLED
    if ( opengl || themeon || magenabled ) {
        throw std::runtime_error( "Slop wasn't compiled with OpenGL support, so themes, magnifications, and shaders are disabled! Try compiling it with the CMAKE_OPENGL_SUPPORT set to true." );
    }
#else // OPENGL_ENABLED
    if ( ( themeon || magenabled || shadergiven ) && !opengl ) {
        throw std::runtime_error( "Slop needs --opengl enabled to use themes, shaders, or magnifications." );
    }
#endif

    // First we set up the x interface and grab the mouse,
    // if we fail for either we exit immediately.
    err = xengine->init( xdisplay.c_str() );
    if ( err != EXIT_SUCCESS ) {
        printSelection( format, true, 0, 0, 0, 0, None );
        return EXIT_FAILURE;
    }
    if ( !slop::isSelectRectangleSupported() ) {
        fprintf( stderr, "Error: Your X server doesn't support the XShape extension. There's nothing slop can do about this!\n" );
        fprintf( stderr, "  Try updating X and making sure you have XExtensions installed. (/usr/lib/libXext.so, /usr/include/X11/extensions/shape.h)\n" );
        return EXIT_FAILURE;
    }
    err = xengine->grabCursor( slop::Cross, gracetime );
    if ( err != EXIT_SUCCESS ) {
        printSelection( format, true, 0, 0, 0, 0, None );
        return EXIT_FAILURE;
    }
    if ( keyboard ) {
        err = xengine->grabKeyboard();
        if ( err ) {
            fprintf( stderr, "Warning: Failed to grab the keyboard. This is non-fatal, keyboard presses might fall through to other applications.\n" );
        }
    }
    current_utc_time( &start );
    double deltatime = 0;
    double curtime = double( start.tv_sec*1000000000L + start.tv_nsec )/1000000000.f;
    while ( running ) {
        current_utc_time( &time );
        // "ticking" the xengine makes it process all queued events.
        xengine->tick();
        // If the user presses any key on the keyboard, exit the application.
        // Make sure at least gracetime has passed before allowing canceling
        double newtime = double( time.tv_sec*1000000000L + time.tv_nsec )/1000000000.f;
        deltatime = newtime-curtime;
        curtime = newtime;
        double starttime = double( start.tv_sec*1000000000L + start.tv_nsec )/1000000000.f;
        if ( curtime - starttime > gracetime ) {
            if ( keyRepeat( XK_Up, curtime, 0.5, &pressedTime[ 0 ], &pressedMemory[ 0 ] ) ) {
                yoffset -= 1;
            }
            if ( keyRepeat( XK_Down, curtime, 0.5, &pressedTime[ 1 ], &pressedMemory[ 1 ] ) ) {
                yoffset += 1;
            }
            if ( keyRepeat( XK_Left, curtime, 0.5, &pressedTime[ 2 ], &pressedMemory[ 2 ] ) ) {
                xoffset -= 1;
            }
            if ( keyRepeat( XK_Right, curtime, 0.5, &pressedTime[ 3 ], &pressedMemory[ 3 ] ) ) {
                xoffset += 1;
            }
            // If we pressed enter we move the state onward.
            if ( xengine->keyPressed( XK_Return ) ) {
                // If we're highlight windows, just select the active window.
                if ( state == 0 ) {
                    state = 1;
                // If we're making a custom selection, select the custom selection.
                } else if ( state == 2 ) {
                    state = 3;
                }
            }
            // If we press any key other than the arrow keys or enter key, we shut down!
            if ( !( xengine->keyPressed( XK_Up ) || xengine->keyPressed( XK_Down ) || xengine->keyPressed( XK_Left ) || xengine->keyPressed( XK_Right ) ) &&
                !( xengine->keyPressed( XK_Return ) ) &&
                ( ( xengine->anyKeyPressed() && keyboard ) || xengine->mouseDown( 3 ) ) ) {
                printSelection( format, true, 0, 0, 0, 0, None );
                fprintf( stderr, "User pressed key. Canceled selection.\n" );
                state = -1;
                running = false;
            }
        }
        // Our adorable little state manager will handle what state we're in.
        switch ( state ) {
            default: {
                break;
            }
            case 0: {
                // If xengine has found a window we're hovering over (or if it changed)
                // create a rectangle around it so the user knows he/she can click on it.
                // --but only if the user wants us to
                if ( window != xengine->m_hoverWindow && tolerance > 0 ) {
                    slop::WindowRectangle t;
                    t.setGeometry( xengine->m_hoverWindow, decorations );
                    t.applyPadding( padding );
                    t.applyMinMaxSize( minimumsize, maximumsize );
                    // Make sure we only apply offsets to windows that we've forcibly removed decorations on.
                    if ( !selection ) {
#ifdef OPENGL_ENABLED
                        if ( opengl ) {
                            selection = new slop::GLSelectRectangle( t.m_x, t.m_y,
                                                                     t.m_x + t.m_width,
                                                                     t.m_y + t.m_height,
                                                                     borderSize,
                                                                     highlight,
                                                                     r, g, b, a );
                            // Haha why is this so hard to cast?
                            ((slop::GLSelectRectangle*)(selection))->setMagnifySettings( magenabled, magstrength, magpixels );
                            ((slop::GLSelectRectangle*)(selection))->setTheme( themeon, theme );
                            ((slop::GLSelectRectangle*)(selection))->setShader( shader );
                        } else {
#endif // OPENGL_ENABLED
                            selection = new slop::XSelectRectangle( t.m_x, t.m_y,
                                                                    t.m_x + t.m_width,
                                                                    t.m_y + t.m_height,
                                                                    borderSize,
                                                                    highlight,
                                                                    r, g, b, a );
#ifdef OPENGL_ENABLED
                        }
#endif // OPENGL_ENABLED
                    } else {
                        selection->setGeo( t.m_x, t.m_y, t.m_x + t.m_width, t.m_y + t.m_height );
                    }
                    //window = xengine->m_hoverWindow;
                    // Since WindowRectangle can select different windows depending on click location...
                    window = t.getWindow();
                }
                if ( selection ) {
                    selection->update( deltatime );
                }
                // If the user clicked we move on to the next state.
                if ( xengine->mouseDown( 1 ) ) {
                    state++;
                }
                break;
            }
            case 1: {
                // Set the mouse position of where we clicked, used so that click tolerance doesn't affect the rectangle's position.
                cx = xengine->m_mousex;
                cy = xengine->m_mousey;
                // Make sure we don't have un-seen applied offsets.
                xoffset = 0;
                yoffset = 0;
                // Also remember where the original selection was
                if ( selection ) {
                    xmem = selection->m_x;
                    ymem = selection->m_y;
                    wmem = selection->m_width;
                    hmem = selection->m_height;
                } else {
                    xmem = cx;
                    ymem = cy;
                }
                state++;
                break;
            }
            case 2: {
                // It's possible that our selection doesn't exist still, lets make sure it actually gets created here.
                if ( !selection ) {
                    int sx, sy, ex, ey;
                    constrain( cx, cy, xengine->m_mousex, xengine->m_mousey, padding, minimumsize, maximumsize, &sx, &sy, &ex, &ey );
#ifdef OPENGL_ENABLED
                    if ( opengl ) {
                        selection = new slop::GLSelectRectangle( sx, sy,
                                                                 ex, ey,
                                                                 borderSize,
                                                                 highlight,
                                                                 r, g, b, a );
                        // Haha why is this so hard to cast?
                        ((slop::GLSelectRectangle*)(selection))->setMagnifySettings( magenabled, magstrength, magpixels );
                        ((slop::GLSelectRectangle*)(selection))->setTheme( themeon, theme );
                        ((slop::GLSelectRectangle*)(selection))->setShader( shader );
                    } else {
#endif // OPENGL_ENABLED
                        selection = new slop::XSelectRectangle( sx, sy,
                                                                ex, ey,
                                                                borderSize,
                                                                highlight,
                                                                r, g, b, a );
#ifdef OPENGL_ENABLED
                    }
#endif // OPENGL_ENABLED
                }
                windowmemory = window;
                // If the user has let go of the mouse button, we'll just
                // continue to the next state.
                if ( !xengine->mouseDown( 1 ) ) {
                    state++;
                    break;
                }
                // Check to make sure the user actually wants to drag for a selection before moving things around.
                int w = xengine->m_mousex - cx;
                int h = xengine->m_mousey - cy;
                if ( ( std::abs( w ) < tolerance && std::abs( h ) < tolerance ) ) {
                    // We make sure the selection rectangle stays on the window we had selected
                    selection->setGeo( xmem, ymem, xmem + wmem, ymem + hmem );
                    selection->update( deltatime );
                    xengine->setCursor( slop::Left );
                    // Make sure
                    window = windowmemory;
                    continue;
                }
                // If we're not selecting a window.
                windowmemory = window;
                window = None;
                // We also detect which way the user is pulling and set the mouse icon accordingly.
                bool x = cx > xengine->m_mousex;
                bool y = cy > xengine->m_mousey;
                if ( ( selection->m_width <= 1 && selection->m_height <= 1 ) || ( minimumsize == maximumsize && minimumsize != 0 && maximumsize != 0 ) ) {
                    xengine->setCursor( slop::Cross );
                } else if ( !x && !y ) {
                    xengine->setCursor( slop::LowerRightCorner );
                } else if ( x && !y ) {
                    xengine->setCursor( slop::LowerLeftCorner );
                } else if ( !x && y ) {
                    xengine->setCursor( slop::UpperRightCorner );
                } else if ( x && y ) {
                    xengine->setCursor( slop::UpperLeftCorner );
                }
                // Apply padding and minimum size adjustments.
                int sx, sy, ex, ey;
                constrain( cx, cy, xengine->m_mousex, xengine->m_mousey, padding, minimumsize, maximumsize, &sx, &sy, &ex, &ey );
                // Set the selection rectangle's dimensions to mouse movement.
                selection->setGeo( sx + xoffset, sy + yoffset, ex, ey );
                selection->update( deltatime );
                break;
            }
            case 3: {
                int x, y, w, h;
                // Exit the utility after this state runs once.
                running = false;
                // We pull the dimensions and positions from the selection rectangle.
                // The selection rectangle automatically converts the positions and
                // dimensions to absolute coordinates when we set them earilier.
                x = selection->m_x;
                y = selection->m_y;
                w = selection->m_width;
                h = selection->m_height;
                // Delete the rectangle, which will remove it from the screen.
                delete selection;
                // Make sure if no window was specifically specified, that we output the root window.
                Window temp = window;
                if ( temp == None ) {
                    temp = xengine->m_root;
                }
                // Print the selection :)
                printSelection( format, false, x, y, w, h, temp );
                break;
            }
        }
        // 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.
        // 0.01 seconds
        usleep( 10000 );
    }
    xengine->releaseCursor();
    xengine->releaseKeyboard();
    // Try to process any last-second requests.
    //xengine->tick();
    // Clean up global classes.
    delete xengine;
    // Sleep for 0.05 seconds to ensure everything was cleaned up. (Without this, slop's window often shows up in screenshots.)
    usleep( 50000 );
    // If we canceled the selection, return error.
    if ( state == -1 ) {
        return EXIT_FAILURE;
    }
    return EXIT_SUCCESS;
}
Esempio n. 14
0
 void DAQtimer::DAQend()
 {
   //clock_gettime(CLOCK_REALTIME,&tsEnd);
   current_utc_time(&tsEnd);
 }
Esempio n. 15
0
int main(int argc, char **argv)
{
    setbuf(stdout, NULL);
    signal(SIGINT, INThandler);

    unsigned char ply = 6;

    int opt;
    while ((opt = getopt(argc, argv, "p:")) != -1) {
        switch (opt) {
        case 'p':
            ply = atoi(optarg);
            break;
        default:
            fprintf(stderr, "Usage: %s [-p ply]\n", argv[0]);
            exit(EXIT_FAILURE);
        }
    }

    struct position pos;
    init_position(&pos);
    assert(consistency(&pos));

    struct timespec realt_old, realt_new;

    tt = new_trans_tables();

#ifdef _USE_HISTORY
    hist = init_history();
#endif

#ifdef _DEBUG
    testing();
#endif

#ifndef _XBOARD
    print_position(&pos);
#endif

    while (1) {
        if (is_check(&pos)) {
            fprintf(stderr, "check.\n");
        }

        user_input(&pos);
#ifndef _XBOARD
        print_position(&pos);
#endif
        assert(consistency(&pos));

        if (is_check(&pos)) {
            fprintf(stderr, "check.\n");
        }

        current_utc_time(&realt_old);
        computer_move(&pos, ply);
        assert(consistency(&pos));
        current_utc_time(&realt_new);

#ifndef _XBOARD
        fprintf(stderr, "One second: %12llu ns\n",
            (long long unsigned)BILLION);
        fprintf(stderr, "Real  time: %12llu ns\n",
            (long long unsigned)minus_time(&realt_new, &realt_old));

        print_position(&pos);
#endif
    }

    return (0);
}