1/*
2
3Copyright 1985, 1987, 1998  The Open Group
4
5Permission to use, copy, modify, distribute, and sell this software and its
6documentation for any purpose is hereby granted without fee, provided that
7the above copyright notice appear in all copies and that both that
8copyright notice and this permission notice appear in supporting
9documentation.
10
11The above copyright notice and this permission notice shall be included in
12all copies or substantial portions of the Software.
13
14THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
17OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
18AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
19CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
20
21Except as contained in this notice, the name of The Open Group shall not be
22used in advertising or otherwise to promote the sale, use or other dealings
23in this Software without prior written authorization from The Open Group.
24
25*/
26
27#ifdef HAVE_CONFIG_H
28#include <config.h>
29#endif
30#include "Xlibint.h"
31
32/*
33 * Check existing events in queue to find if any match.  If so, return.
34 * If not, flush buffer and see if any more events are readable. If one
35 * matches, return.  If all else fails, tell the user no events found.
36 */
37
38Bool XCheckTypedEvent (
39	register Display *dpy,
40	int type,		/* Selected event type. */
41	register XEvent *event)	/* XEvent to be filled in. */
42{
43	register _XQEvent *prev, *qelt;
44	unsigned long qe_serial = 0;
45	int n;			/* time through count */
46
47        LockDisplay(dpy);
48
49	/* Delete unclaimed cookies */
50	_XFreeEventCookies(dpy);
51
52	prev = NULL;
53	for (n = 3; --n >= 0;) {
54	    for (qelt = prev ? prev->next : dpy->head;
55		 qelt;
56		 prev = qelt, qelt = qelt->next) {
57		if (qelt->event.type == type) {
58		    *event = qelt->event;
59		    _XDeq(dpy, prev, qelt);
60		    _XStoreEventCookie(dpy, event);
61		    UnlockDisplay(dpy);
62		    return True;
63		}
64	    }
65	    if (prev)
66		qe_serial = prev->qserial_num;
67	    switch (n) {
68	      case 2:
69		_XEventsQueued(dpy, QueuedAfterReading);
70		break;
71	      case 1:
72		_XFlush(dpy);
73		break;
74	    }
75	    if (prev && prev->qserial_num != qe_serial)
76		/* another thread has snatched this event */
77		prev = NULL;
78	}
79	UnlockDisplay(dpy);
80	return False;
81}
82