1 /*
2 * The Rubik's cube.
3 *
4 * Sed - april 1999 / december 2003.
5 *
6 * This program is in the public domain.
7 *--------------------
8 * The wait event function, or how to show the superiority of select in face of threads shit.
9 */
10
11 #include "event.h"
12
13 #include <sys/time.h>
14 #include <sys/types.h>
15 #include <unistd.h>
16 #include <errno.h>
17 #include <stdio.h>
18 #include <X11/Xlib.h>
19
20 #include "screen.h"
21 #include "cube.h"
22
can_mix(int fd)23 int can_mix(int fd)
24 {
25 fd_set w;
26 struct timeval t;
27
28 FD_ZERO(&w);
29
30 t.tv_sec=0;
31 t.tv_usec=0;
32
33 FD_SET(fd, &w);
34
35 select(fd+1, 0, &w, 0, &t);
36
37 return FD_ISSET(fd, &w);
38 }
39
40 /* return -1 of error, and what it has to, read it */
wait_event(SCREEN * s,CUBE * c)41 int wait_event(SCREEN *s, CUBE *c)
42 {
43 fd_set r, w;
44 struct timeval t; /* , u; */
45 int ret;
46 XEvent ev;
47
48 FD_ZERO(&r);
49 FD_ZERO(&w);
50
51 t.tv_sec=0;
52 t.tv_usec=0; /* 50*1000; */
53
54 if (XCheckMaskEvent(s->d, -1L, &ev)!=False) {
55 XPutBackEvent(s->d, &ev);
56 return SCREEN_EVENT;
57 }
58
59 FD_SET(ConnectionNumber(s->d), &r);
60
61 if (c->anim)
62 while((ret=select(FD_SETSIZE, &r, &w, 0, &t))==-1) {
63 if (errno!=EINTR) {
64 perror("select");
65 return -1;
66 }
67 }
68 else
69 while((ret=select(FD_SETSIZE, &r, &w, 0, (struct timeval *)0))==-1) {
70 if (errno!=EINTR) {
71 perror("select");
72 return -1;
73 }
74 }
75
76 if (!ret) {
77 return CUBE_EVENT;
78 }
79 ret=0;
80
81 if (FD_ISSET(ConnectionNumber(s->d), &r))
82 ret|=SCREEN_EVENT;
83 else { /* I have to do this XCheckMaskEvent because X functions might already have taken
84 * away from the socket some events, that I may see too late, producing
85 * bad results for the player.
86 */
87 if (XCheckMaskEvent(s->d, -1L, &ev)!=False) {
88 ret |= SCREEN_EVENT;
89 XPutBackEvent(s->d, &ev);
90 }
91 }
92
93 return ret;
94 }
95