ex1.c (2286B)
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <time.h> 4 #include <unistd.h> 5 #include <math.h> 6 7 #include <X11/Xlib.h> 8 9 /* macros */ 10 #define INIT_WIDTH 800 11 #define INIT_HEIGHT 600 12 13 14 /* variables */ 15 Display *display; 16 Window window; 17 unsigned int win_width = INIT_WIDTH, win_height = INIT_HEIGHT; 18 GC gc; 19 Atom wm_delete_window; 20 21 /* function prototypes */ 22 void setup(void); 23 void cleanup(void); 24 25 26 void 27 setup(void) 28 { 29 if ((display = XOpenDisplay(NULL)) == NULL){ 30 fprintf(stderr, "ERROR: could not open display\n"); 31 exit(1); 32 } 33 window = XCreateSimpleWindow( 34 display, 35 XDefaultRootWindow(display), 36 0, 0, 37 win_width, win_height, 38 0, 0, 39 0); 40 XStoreName(display, window, "UNKO"); 41 gc = XCreateGC(display, window, 0, NULL); 42 43 wm_delete_window = XInternAtom(display, 44 "WM_DELETE_WINDOW", False); 45 XSetWMProtocols(display, window, &wm_delete_window, 1); 46 47 XSelectInput(display, window, 48 ExposureMask|KeyPressMask|KeyReleaseMask); 49 50 XSetForeground(display, gc, 0x0000FF); 51 XMapWindow(display, window); 52 } 53 54 void 55 cleanup(void) 56 { 57 XCloseDisplay(display); 58 } 59 60 int 61 main(void) 62 { 63 int px, py; 64 int quit; 65 struct timespec ts; 66 XEvent event; 67 68 setup(); 69 quit = 0; 70 71 while (!quit){ 72 while(XPending(display) > 0){ 73 XNextEvent(display, &event); 74 switch (event.type){ 75 case KeyPress: { 76 switch (XLookupKeysym(&event.xkey, 0)){ 77 case 'q': 78 quit = 1; 79 break; 80 default: 81 break; 82 } 83 } break; 84 case ClientMessage: { 85 if ((Atom) event.xclient.data.l[0] == wm_delete_window) { 86 quit = 1; 87 } 88 } break; 89 default: 90 break; 91 } 92 } 93 clock_gettime(CLOCK_MONOTONIC, &ts); 94 px = 200 + (int) (100 * sinf(ts.tv_sec + ts.tv_nsec / 1000.0 / 1000 / 1000)); 95 py = 200 + (int) (100 * cosf(ts.tv_sec + ts.tv_nsec / 1000.0 / 1000 / 1000)); 96 XClearArea(display, window, 97 0, 0, // position 98 win_width, win_height, // width and height 99 False); 100 XFillRectangle(display, window, gc, 101 px, py, // position 102 100, 100); // width and height 103 104 ts.tv_sec = 0; 105 ts.tv_nsec = 10 * 1000 * 1000; 106 nanosleep(&ts, NULL); 107 } 108 109 cleanup(); 110 return 0; 111 }