| 1 | /* strobe.c (<~Harvie 2oo9) |
| 2 | * Dream Machine implementation for GNU/Linux |
| 3 | * usage ./strobe [frequency] |
| 4 | */ |
| 5 | |
| 6 | //#define __WIN32__ |
| 7 | #include <stdio.h> |
| 8 | #include <stdlib.h> |
| 9 | #include <unistd.h> |
| 10 | #include <signal.h> |
| 11 | #ifndef __WIN32__ |
| 12 | #include <fcntl.h> |
| 13 | #else |
| 14 | #include <windows.h> |
| 15 | #endif |
| 16 | |
| 17 | void signal_handler(int signo) { |
| 18 | if(signo == SIGTERM || signo == SIGINT || signo == SIGQUIT) { |
| 19 | fputs("\033[0m" "\033[2J" "\033[0;0H", stdout); fflush(stdout); //restore default terminal settings |
| 20 | exit(0); |
| 21 | } |
| 22 | } |
| 23 | |
| 24 | int main(int argc, char *argv[]) { |
| 25 | //Settings |
| 26 | char bg_black[] = "\033[40m\033[1;37m"; //set black background |
| 27 | char bg_white[] = "\033[47m\033[1;30m"; //set white background |
| 28 | char cls[] = "\033[2J" "\033[0;0H"; //clear screen and return to begining of it |
| 29 | char format_str[] = "%s%s" //"\033[40m\033[1;37m" |
| 30 | "Warning: this software can cause seizures. Use it on your own risk only! Don't forget to close your eyes! Running at %g Hz (Press ^C to exit)"; |
| 31 | double frequency = 10; //Hz |
| 32 | |
| 33 | //Compute intervals |
| 34 | int cache_size = 0; |
| 35 | if(argc > 1) { |
| 36 | frequency = strtod(argv[1], NULL); //get frequency from argv[1] (if present) |
| 37 | cache_size += sizeof(argv[1]); |
| 38 | } |
| 39 | useconds_t half_interval = (1000000/frequency)/2; //uSeconds |
| 40 | |
| 41 | //Pre-cache output strings |
| 42 | cache_size += sizeof(bg_black) + sizeof(cls) + sizeof(format_str) + 5; |
| 43 | char state_a[cache_size]; |
| 44 | char state_b[cache_size]; |
| 45 | |
| 46 | sprintf(state_a, format_str, bg_black, cls, frequency); |
| 47 | sprintf(state_b, format_str, bg_white, cls, frequency); |
| 48 | |
| 49 | //Register signals |
| 50 | signal(SIGINT, signal_handler); signal(SIGTERM, signal_handler); signal(SIGQUIT, signal_handler); |
| 51 | |
| 52 | //Main loop |
| 53 | while(1) { |
| 54 | fputs(state_a, stdout); |
| 55 | fflush(stdout); |
| 56 | usleep(half_interval); |
| 57 | /* |
| 58 | #ifndef __WIN32__ |
| 59 | int fflags = fcntl(fileno(stdin), F_GETFL, 0); |
| 60 | fcntl(fileno(stdin), F_SETFL, fflags | O_NONBLOCK); |
| 61 | while(getchar()) puts("."); |
| 62 | fcntl(fileno(stdin), F_SETFL, fflags); |
| 63 | #else |
| 64 | //WARNING! Somehow implement FILE_FLAG_OVERLAPPED & FILE_FLAG_NO_BUFFERING support on windows |
| 65 | #endif |
| 66 | */ |
| 67 | if(argc > 2) getchar(); //interactive strobe |
| 68 | fputs(state_b, stdout); |
| 69 | fflush(stdout); |
| 70 | usleep(half_interval); |
| 71 | } |
| 72 | } |