aboutsummaryrefslogtreecommitdiff
path: root/xorg-server/dix/dixutils.c
blob: d9d9d8c7de8d265d5eba916515041284e206215c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
/***********************************************************

Copyright 1987, 1998  The Open Group

Permission to use, copy, modify, distribute, and sell this software and its
documentation for any purpose is hereby granted without fee, provided that
the above copyright notice appear in all copies and that both that
copyright notice and this permission notice appear in supporting
documentation.

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Except as contained in this notice, the name of The Open Group shall not be
used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from The Open Group.


Copyright 1987 by Digital Equipment Corporation, Maynard, Massachusetts.

                        All Rights Reserved

Permission to use, copy, modify, and distribute this software and its 
documentation for any purpose and without fee is hereby granted, 
provided that the above copyright notice appear in all copies and that
both that copyright notice and this permission notice appear in 
supporting documentation, and that the name of Digital not be
used in advertising or publicity pertaining to distribution of the
software without specific, written prior permission.  

DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
SOFTWARE.

******************************************************************/

/*

(c)Copyright 1988,1991 Adobe Systems Incorporated. All rights reserved.

Permission to use, copy, modify, distribute, and sublicense this software and its
documentation for any purpose and without fee is hereby granted, provided that
the above copyright notices appear in all copies and that both those copyright
notices and this permission notice appear in supporting documentation and that
the name of Adobe Systems Incorporated not be used in advertising or publicity
pertaining to distribution of the software without specific, written prior
permission.  No trademark license to use the Adobe trademarks is hereby
granted.  If the Adobe trademark "Display PostScript"(tm) is used to describe
this software, its functionality or for any other purpose, such use shall be
limited to a statement that this software works in conjunction with the Display
PostScript system.  Proper trademark attribution to reflect Adobe's ownership
of the trademark shall be given whenever any such reference to the Display
PostScript system is made.

ADOBE MAKES NO REPRESENTATIONS ABOUT THE SUITABILITY OF THE SOFTWARE FOR ANY
PURPOSE.  IT IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY.  ADOBE
DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-
INFRINGEMENT OF THIRD PARTY RIGHTS.  IN NO EVENT SHALL ADOBE BE LIABLE TO YOU
OR ANY OTHER PARTY FOR ANY SPECIAL, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY
DAMAGES WHATSOEVER WHETHER IN AN ACTION OF CONTRACT,NEGLIGENCE, STRICT
LIABILITY OR ANY OTHER ACTION ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.  ADOBE WILL NOT PROVIDE ANY TRAINING OR OTHER
SUPPORT FOR THE SOFTWARE.

Adobe, PostScript, and Display PostScript are trademarks of Adobe Systems
Incorporated which may be registered in certain jurisdictions.

Author:  Adobe Systems Incorporated

*/


#ifdef HAVE_DIX_CONFIG_H
#include <dix-config.h>
#endif

#include <X11/X.h>
#include <X11/Xmd.h>
#include "misc.h"
#include "windowstr.h"
#include "dixstruct.h"
#include "pixmapstr.h"
#include "gcstruct.h"
#include "scrnintstr.h"
#define  XK_LATIN1
#include <X11/keysymdef.h>
#include "xace.h"

/*
 * CompareTimeStamps returns -1, 0, or +1 depending on if the first
 * argument is less than, equal to or greater than the second argument.
 */

int
CompareTimeStamps(TimeStamp a, TimeStamp b)
{
    if (a.months < b.months)
	return EARLIER;
    if (a.months > b.months)
	return LATER;
    if (a.milliseconds < b.milliseconds)
	return EARLIER;
    if (a.milliseconds > b.milliseconds)
	return LATER;
    return SAMETIME;
}

/*
 * convert client times to server TimeStamps
 */

#define HALFMONTH ((unsigned long) 1<<31)
TimeStamp
ClientTimeToServerTime(CARD32 c)
{
    TimeStamp ts;
    if (c == CurrentTime)
	return currentTime;
    ts.months = currentTime.months;
    ts.milliseconds = c;
    if (c > currentTime.milliseconds)
    {
	if (((unsigned long) c - currentTime.milliseconds) > HALFMONTH)
	    ts.months -= 1;
    }
    else if (c < currentTime.milliseconds)
    {
	if (((unsigned long)currentTime.milliseconds - c) > HALFMONTH)
	    ts.months += 1;
    }
    return ts;
}

/*
 * ISO Latin-1 case conversion routine
 *
 * this routine always null-terminates the result, so
 * beware of too-small buffers
 */

static unsigned char
ISOLatin1ToLower (unsigned char source)
{
    unsigned char   dest;
    if ((source >= XK_A) && (source <= XK_Z))
       dest = source + (XK_a - XK_A);
    else if ((source >= XK_Agrave) && (source <= XK_Odiaeresis))
       dest = source + (XK_agrave - XK_Agrave);
    else if ((source >= XK_Ooblique) && (source <= XK_Thorn))
       dest = source + (XK_oslash - XK_Ooblique);
    else
       dest = source;
    return dest;
}


int
CompareISOLatin1Lowered(unsigned char *s1, int s1len, 
			unsigned char *s2, int s2len)
{
    unsigned char   c1, c2;
    
    for (;;) 
    {
	/* note -- compare against zero so that -1 ignores len */
	c1 = s1len-- ? *s1++ : '\0';
	c2 = s2len-- ? *s2++ : '\0';
	if (!c1 || 
	    (c1 != c2 && 
	     (c1 = ISOLatin1ToLower (c1)) != (c2 = ISOLatin1ToLower (c2))))
	    break;
    }
    return (int) c1 - (int) c2;
}

/*
 * dixLookupWindow and dixLookupDrawable:
 * Look up the window/drawable taking into account the client doing the
 * lookup, the type of drawable desired, and the type of access desired.
 * Return Success with *pDraw set if the window/drawable exists and the client
 * is allowed access, else return an error code with *pDraw set to NULL.  The
 * access mask values are defined in resource.h.  The type mask values are
 * defined in pixmap.h, with zero equivalent to M_DRAWABLE.
 */
int
dixLookupDrawable(DrawablePtr *pDraw, XID id, ClientPtr client,
		  Mask type, Mask access)
{
    DrawablePtr pTmp;
    int rc;

    *pDraw = NULL;
    client->errorValue = id;

    if (id == INVALID)
	return BadDrawable;

    rc = dixLookupResourceByClass((pointer *)&pTmp, id, RC_DRAWABLE, client, access);

    if (rc == BadValue)
	return BadDrawable;
    if (rc != Success)
	return rc;
    if (!((1 << pTmp->type) & (type ? type : M_DRAWABLE)))
	return BadMatch;

    *pDraw = pTmp;
    return Success;
}

int
dixLookupWindow(WindowPtr *pWin, XID id, ClientPtr client, Mask access)
{
    int rc;
    rc = dixLookupDrawable((DrawablePtr*)pWin, id, client, M_WINDOW, access);
    return (rc == BadDrawable) ? BadWindow : rc;
}

int
dixLookupGC(GCPtr *pGC, XID id, ClientPtr client, Mask access)
{
    return dixLookupResourceByType((pointer *)pGC, id, RT_GC, client, access);
}

int
dixLookupFontable(FontPtr *pFont, XID id, ClientPtr client, Mask access)
{
    int rc;
    GC *pGC;
    client->errorValue = id;		/* EITHER font or gc */
    rc = dixLookupResourceByType((pointer *) pFont, id, RT_FONT, client, access);
    if (rc != BadFont)
	return rc;
    rc = dixLookupResourceByType((pointer *) &pGC, id, RT_GC, client, access);
    if (rc == BadGC)
	return BadFont;
    if (rc == Success)
	*pFont = pGC->font;
    return rc;
}

int
dixLookupClient(ClientPtr *pClient, XID rid, ClientPtr client, Mask access)
{
    pointer pRes;
    int rc = BadValue, clientIndex = CLIENT_ID(rid);

    if (!clientIndex || !clients[clientIndex] || (rid & SERVER_BIT))
	goto bad;

    rc = dixLookupResourceByClass(&pRes, rid, RC_ANY, client, DixGetAttrAccess);
    if (rc != Success)
	goto bad;

    rc = XaceHook(XACE_CLIENT_ACCESS, client, clients[clientIndex], access);
    if (rc != Success)
	goto bad;

    *pClient = clients[clientIndex];
    return Success;
bad:
    if(client)
        client->errorValue = rid;
    *pClient = NULL;
    return rc;
}

int
AlterSaveSetForClient(ClientPtr client, WindowPtr pWin, unsigned mode,
                      Bool toRoot, Bool map)
{
    int numnow;
    SaveSetElt *pTmp = NULL;
    int j;

    numnow = client->numSaved;
    j = 0;
    if (numnow)
    {
	pTmp = client->saveSet;
	while ((j < numnow) && (SaveSetWindow(pTmp[j]) != (pointer)pWin))
	    j++;
    }
    if (mode == SetModeInsert)
    {
	if (j < numnow)         /* duplicate */
	   return Success;
	numnow++;
	pTmp = (SaveSetElt *)realloc(client->saveSet, sizeof(*pTmp) * numnow);
	if (!pTmp)
	    return BadAlloc;
	client->saveSet = pTmp;
       	client->numSaved = numnow;
	SaveSetAssignWindow(client->saveSet[numnow - 1], pWin);
	SaveSetAssignToRoot(client->saveSet[numnow - 1], toRoot);
	SaveSetAssignMap(client->saveSet[numnow - 1], map);
	return Success;
    }
    else if ((mode == SetModeDelete) && (j < numnow))
    {
	while (j < numnow-1)
	{
           pTmp[j] = pTmp[j+1];
	   j++;
	}
	numnow--;
        if (numnow)
	{
	    pTmp = (SaveSetElt *)realloc(client->saveSet, sizeof(*pTmp) * numnow);
	    if (pTmp)
		client->saveSet = pTmp;
	}
        else
        {
            free(client->saveSet);
	    client->saveSet = (SaveSetElt *)NULL;
	}
	client->numSaved = numnow;
	return Success;
    }
    return Success;
}

void
DeleteWindowFromAnySaveSet(WindowPtr pWin)
{
    int i;
    ClientPtr client;
    
    for (i = 0; i< currentMaxClients; i++)
    {    
	client = clients[i];
	if (client && client->numSaved)
	    (void)AlterSaveSetForClient(client, pWin, SetModeDelete, FALSE, TRUE);
    }
}

/* No-op Don't Do Anything : sometimes we need to be able to call a procedure
 * that doesn't do anything.  For example, on screen with only static
 * colormaps, if someone calls install colormap, it's easier to have a dummy
 * procedure to call than to check if there's a procedure 
 */
void
NoopDDA(void)
{
}

typedef struct _BlockHandler {
    BlockHandlerProcPtr BlockHandler;
    WakeupHandlerProcPtr WakeupHandler;
    pointer blockData;
    Bool    deleted;
} BlockHandlerRec, *BlockHandlerPtr;

static BlockHandlerPtr	handlers;
static int		numHandlers;
static int		sizeHandlers;
static Bool		inHandler;
static Bool		handlerDeleted;

/**
 * 
 *  \param pTimeout   DIX doesn't want to know how OS represents time
 *  \param pReadMask  nor how it represents the det of descriptors
 */
void
BlockHandler(pointer pTimeout, pointer pReadmask)
{
    int i, j;
    
    ++inHandler;
    for (i = 0; i < screenInfo.numScreens; i++)
	(* screenInfo.screens[i]->BlockHandler)(i, 
				screenInfo.screens[i]->blockData,
				pTimeout, pReadmask);
    for (i = 0; i < numHandlers; i++)
	(*handlers[i].BlockHandler) (handlers[i].blockData,
				     pTimeout, pReadmask);
    if (handlerDeleted)
    {
	for (i = 0; i < numHandlers;)
	    if (handlers[i].deleted)
	    {
	    	for (j = i; j < numHandlers - 1; j++)
		    handlers[j] = handlers[j+1];
	    	numHandlers--;
	    }
	    else
		i++;
	handlerDeleted = FALSE;
    }
    --inHandler;
}

/**
 *
 *  \param result    32 bits of undefined result from the wait
 *  \param pReadmask the resulting descriptor mask
 */
void
WakeupHandler(int result, pointer pReadmask)
{
    int i, j;

    ++inHandler;
    for (i = numHandlers - 1; i >= 0; i--)
	(*handlers[i].WakeupHandler) (handlers[i].blockData,
				      result, pReadmask);
    for (i = 0; i < screenInfo.numScreens; i++)
	(* screenInfo.screens[i]->WakeupHandler)(i, 
				screenInfo.screens[i]->wakeupData,
				result, pReadmask);
    if (handlerDeleted)
    {
	for (i = 0; i < numHandlers;)
	    if (handlers[i].deleted)
	    {
	    	for (j = i; j < numHandlers - 1; j++)
		    handlers[j] = handlers[j+1];
	    	numHandlers--;
	    }
	    else
		i++;
	handlerDeleted = FALSE;
    }
    --inHandler;
}

/**
 * Reentrant with BlockHandler and WakeupHandler, except wakeup won't
 * get called until next time
 */
Bool
RegisterBlockAndWakeupHandlers (BlockHandlerProcPtr blockHandler, 
                                WakeupHandlerProcPtr wakeupHandler, 
                                pointer blockData)
{
    BlockHandlerPtr new;

    if (numHandlers >= sizeHandlers)
    {
        new = (BlockHandlerPtr) realloc(handlers, (numHandlers + 1) *
				      	  sizeof (BlockHandlerRec));
    	if (!new)
	    return FALSE;
    	handlers = new;
	sizeHandlers = numHandlers + 1;
    }
    handlers[numHandlers].BlockHandler = blockHandler;
    handlers[numHandlers].WakeupHandler = wakeupHandler;
    handlers[numHandlers].blockData = blockData;
    handlers[numHandlers].deleted = FALSE;
    numHandlers = numHandlers + 1;
    return TRUE;
}

void
RemoveBlockAndWakeupHandlers (BlockHandlerProcPtr blockHandler, 
                              WakeupHandlerProcPtr wakeupHandler, 
                              pointer blockData)
{
    int	    i;

    for (i = 0; i < numHandlers; i++)
	if (handlers[i].BlockHandler == blockHandler &&
	    handlers[i].WakeupHandler == wakeupHandler &&
	    handlers[i].blockData == blockData)
	{
	    if (inHandler)
	    {
		handlerDeleted = TRUE;
		handlers[i].deleted = TRUE;
	    }
	    else
	    {
	    	for (; i < numHandlers - 1; i++)
		    handlers[i] = handlers[i+1];
	    	numHandlers--;
	    }
	    break;
	}
}

void
InitBlockAndWakeupHandlers (void)
{
    free(handlers);
    handlers = (BlockHandlerPtr) 0;
    numHandlers = 0;
    sizeHandlers = 0;
}

/*
 * A general work queue.  Perform some task before the server
 * sleeps for input.
 */

WorkQueuePtr		workQueue;
static WorkQueuePtr	*workQueueLast = &workQueue;

void
ProcessWorkQueue(void)
{
    WorkQueuePtr    q, *p;

    p = &workQueue;
    /*
     * Scan the work queue once, calling each function.  Those
     * which return TRUE are removed from the queue, otherwise
     * they will be called again.  This must be reentrant with
     * QueueWorkProc.
     */
    while ((q = *p))
    {
	if ((*q->function) (q->client, q->closure))
	{
	    /* remove q from the list */
	    *p = q->next;    /* don't fetch until after func called */
	    free(q);
	}
	else
	{
	    p = &q->next;    /* don't fetch until after func called */
	}
    }
    workQueueLast = p;
}

void
ProcessWorkQueueZombies(void)
{
    WorkQueuePtr    q, *p;

    p = &workQueue;
    while ((q = *p))
    {
	if (q->client && q->client->clientGone)
	{
	    (void) (*q->function) (q->client, q->closure);
	    /* remove q from the list */
	    *p = q->next;    /* don't fetch until after func called */
	    free(q);
	}
	else
	{
	    p = &q->next;    /* don't fetch until after func called */
	}
    }
    workQueueLast = p;
}

Bool
QueueWorkProc (
    Bool (*function)(ClientPtr /* pClient */, pointer /* closure */),
    ClientPtr client, pointer closure)
{
    WorkQueuePtr    q;

    q = malloc(sizeof *q);
    if (!q)
	return FALSE;
    q->function = function;
    q->client = client;
    q->closure = closure;
    q->next = NULL;
    *workQueueLast = q;
    workQueueLast = &q->next;
    return TRUE;
}

/*
 * Manage a queue of sleeping clients, awakening them
 * when requested, by using the OS functions IgnoreClient
 * and AttendClient.  Note that this *ignores* the troubles
 * with request data interleaving itself with events, but
 * we'll leave that until a later time.
 */

typedef struct _SleepQueue {
    struct _SleepQueue	*next;
    ClientPtr		client;
    ClientSleepProcPtr  function;
    pointer		closure;
} SleepQueueRec, *SleepQueuePtr;

static SleepQueuePtr	sleepQueue = NULL;

Bool
ClientSleep (ClientPtr client, ClientSleepProcPtr function, pointer closure)
{
    SleepQueuePtr   q;

    q = malloc(sizeof *q);
    if (!q)
	return FALSE;

    IgnoreClient (client);
    q->next = sleepQueue;
    q->client = client;
    q->function = function;
    q->closure = closure;
    sleepQueue = q;
    return TRUE;
}

Bool
ClientSignal (ClientPtr client)
{
    SleepQueuePtr   q;

    for (q = sleepQueue; q; q = q->next)
	if (q->client == client)
	{
	    return QueueWorkProc (q->function, q->client, q->closure);
	}
    return FALSE;
}

void
ClientWakeup (ClientPtr client)
{
    SleepQueuePtr   q, *prev;

    prev = &sleepQueue;
    while ( (q = *prev) )
    {
	if (q->client == client)
	{
	    *prev = q->next;
	    free(q);
	    if (client->clientGone)
		/* Oops -- new zombie cleanup code ensures this only
		 * happens from inside CloseDownClient; don't want to
		 * recurse here...
		 */
		/* CloseDownClient(client) */;
	    else
		AttendClient (client);
	    break;
	}
	prev = &q->next;
    }
}

Bool
ClientIsAsleep (ClientPtr client)
{
    SleepQueuePtr   q;

    for (q = sleepQueue; q; q = q->next)
	if (q->client == client)
	    return TRUE;
    return FALSE;
}

/*
 *  Generic Callback Manager
 */

/* ===== Private Procedures ===== */

static int numCallbackListsToCleanup = 0;
static CallbackListPtr **listsToCleanup = NULL;

static Bool
_AddCallback(
    CallbackListPtr *pcbl,
    CallbackProcPtr callback,
    pointer         data)
{
    CallbackPtr     cbr;

    cbr = malloc(sizeof(CallbackRec));
    if (!cbr)
	return FALSE;
    cbr->proc = callback;
    cbr->data = data;
    cbr->next = (*pcbl)->list;
    cbr->deleted = FALSE;
    (*pcbl)->list = cbr;
    return TRUE;
}

static Bool 
_DeleteCallback(
    CallbackListPtr *pcbl,
    CallbackProcPtr callback,
    pointer         data)
{
    CallbackListPtr cbl = *pcbl;
    CallbackPtr     cbr, pcbr;

    for (pcbr = NULL, cbr = cbl->list;
	 cbr != NULL;
	 pcbr = cbr, cbr = cbr->next)
    {
	if ((cbr->proc == callback) && (cbr->data == data))
	    break;
    }
    if (cbr != NULL)
    {
	if (cbl->inCallback)
	{
	    ++(cbl->numDeleted);
	    cbr->deleted = TRUE;
	}
	else
	{
	    if (pcbr == NULL)
		cbl->list = cbr->next;
	    else
		pcbr->next = cbr->next;
	    free(cbr);
	}
	return TRUE;
    }
    return FALSE;
}

static void 
_CallCallbacks(
    CallbackListPtr    *pcbl,
    pointer	    call_data)
{
    CallbackListPtr cbl = *pcbl;
    CallbackPtr     cbr, pcbr;

    ++(cbl->inCallback);
    for (cbr = cbl->list; cbr != NULL; cbr = cbr->next)
    {
	(*(cbr->proc)) (pcbl, cbr->data, call_data);
    }
    --(cbl->inCallback);

    if (cbl->inCallback) return;

    /* Was the entire list marked for deletion? */

    if (cbl->deleted)
    {
	DeleteCallbackList(pcbl);
	return;
    }

    /* Were some individual callbacks on the list marked for deletion?
     * If so, do the deletions.
     */

    if (cbl->numDeleted)
    {
	for (pcbr = NULL, cbr = cbl->list; (cbr != NULL) && cbl->numDeleted; )
	{
	    if (cbr->deleted)
	    {
		if (pcbr)
		{
		    cbr = cbr->next;
		    free(pcbr->next);
		    pcbr->next = cbr;
		} else
		{
		    cbr = cbr->next;
		    free(cbl->list);
		    cbl->list = cbr;
		}
		cbl->numDeleted--;
	    }
	    else /* this one wasn't deleted */
	    {
		pcbr = cbr;
		cbr = cbr->next;
	    }
	}
    }
}

static void
_DeleteCallbackList(
    CallbackListPtr    *pcbl)
{
    CallbackListPtr cbl = *pcbl;
    CallbackPtr     cbr, nextcbr;
    int i;

    if (cbl->inCallback)
    {
	cbl->deleted = TRUE;
	return;
    }

    for (i = 0; i < numCallbackListsToCleanup; i++)
    {
	if (listsToCleanup[i] == pcbl)
	{
	    listsToCleanup[i] = NULL;
	    break;
	}
    }

    for (cbr = cbl->list; cbr != NULL; cbr = nextcbr)
    {
	nextcbr = cbr->next;
	free(cbr);
    }
    free(cbl);
    *pcbl = NULL;
}

static Bool
CreateCallbackList(CallbackListPtr *pcbl)
{
    CallbackListPtr  cbl;
    int i;

    if (!pcbl) return FALSE;
    cbl = malloc(sizeof(CallbackListRec));
    if (!cbl) return FALSE;
    cbl->inCallback = 0;
    cbl->deleted = FALSE;
    cbl->numDeleted = 0;
    cbl->list = NULL;
    *pcbl = cbl;

    for (i = 0; i < numCallbackListsToCleanup; i++)
    {
	if (!listsToCleanup[i])
	{
	    listsToCleanup[i] = pcbl;
	    return TRUE;
	}    
    }

    listsToCleanup = (CallbackListPtr **)xnfrealloc(listsToCleanup,
		sizeof(CallbackListPtr *) * (numCallbackListsToCleanup+1));
    listsToCleanup[numCallbackListsToCleanup] = pcbl;
    numCallbackListsToCleanup++;
    return TRUE;
}

/* ===== Public Procedures ===== */

Bool
AddCallback(CallbackListPtr *pcbl, CallbackProcPtr callback, pointer data)
{
    if (!pcbl) return FALSE;
    if (!*pcbl)
    {	/* list hasn't been created yet; go create it */
	if (!CreateCallbackList(pcbl))
	    return FALSE;
    }
    return _AddCallback(pcbl, callback, data);
}

Bool
DeleteCallback(CallbackListPtr *pcbl, CallbackProcPtr callback, pointer data)
{
    if (!pcbl || !*pcbl) return FALSE;
    return _DeleteCallback(pcbl, callback, data);
}

void
CallCallbacks(CallbackListPtr *pcbl, pointer call_data)
{
    if (!pcbl || !*pcbl) return;
    _CallCallbacks(pcbl, call_data);
}

void
DeleteCallbackList(CallbackListPtr *pcbl)
{
    if (!pcbl || !*pcbl) return;
    _DeleteCallbackList(pcbl);
}

void
InitCallbackManager(void)
{
    int i;

    for (i = 0; i < numCallbackListsToCleanup; i++)
    {
	DeleteCallbackList(listsToCleanup[i]);
    }
    free(listsToCleanup);

    numCallbackListsToCleanup = 0;
    listsToCleanup = NULL;
}