summaryrefslogtreecommitdiff
path: root/lib/ds/plevent.c
blob: e337d7fb85a938c73de80f07de0b3d0066e08204 (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
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/*
 * The contents of this file are subject to the Netscape Public License
 * Version 1.1 (the "NPL"); you may not use this file except in
 * compliance with the NPL.  You may obtain a copy of the NPL at
 * http://www.mozilla.org/NPL/
 * 
 * Software distributed under the NPL is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
 * for the specific language governing rights and limitations under the
 * NPL.
 * 
 * The Initial Developer of this code under the NPL is Netscape
 * Communications Corporation.  Portions created by Netscape are
 * Copyright (C) 1998 Netscape Communications Corporation.  All Rights
 * Reserved.
 */
#if defined(XP_OS2)
#define INCL_WIN
#include <os2.h>
#define DefWindowProc WinDefWindowProc
typedef MPARAM WPARAM,LPARAM;
#endif /* XP_OS2 */

#include "plevent.h"
#include "prmem.h"
#include "prcmon.h"
#include "prlog.h"

#if !defined(WIN32)
#include <errno.h>
#include <stddef.h>
#if !defined(XP_OS2)
#include <unistd.h>
#endif /* !XP_OS2 */
#endif /* !Win32 */

#if defined(XP_UNIX)
/* for fcntl */
#include <sys/types.h>
#include <fcntl.h>
#endif

#if defined(XP_MAC)
#include <AppleEvents.h>
#include "pprthred.h"
#include "primpl.h"
#else
#include "private/pprthred.h"
#include "private/primpl.h"
#endif /* XP_MAC */

#if defined(VMS)
/*
** If MOTIF is being used then XtAppAddInput is used as the notification
** method and so event flags must be used, so you need to define
** VMS_EVENTS_USE_EF. If gdk is being used then select is used for
** notification, and then VMS_EVENTS_USE_SOCKETS should be defined.
*/
#undef VMS_EVENTS_USE_EF
#define VMS_EVENTS_USE_SOCKETS
#endif

#if defined(VMS_EVENTS_USE_EF)
/*
** On OpenVMS, XtAppAddInput doesn't want a regular fd, instead it 
** wants an event flag. So, we don't create and use a pipe for 
** notification of when an event queue has something ready, instead
** we use an event flag. Shouldn't be a problem if we only have
** a few event queues.
*/
#include <lib$routines.h>
#include <starlet.h>
#include <stsdef.h>
#endif /* VMS_EVENTS_USE_EF */

#if defined(VMS_EVENTS_USE_SOCKETS)
#include <socket.h>
#endif /* VMS_EVENTS_USE_SOCKETS */


static PRLogModuleInfo *event_lm = NULL;

/*******************************************************************************
 * Private Stuff
 ******************************************************************************/

/*
** EventQueueType -- Defines notification type for an event queue
**
*/
typedef enum 
{
    EventQueueIsNative = 1,
    EventQueueIsMonitored = 2
} EventQueueType;


struct PLEventQueue {
    char*        name;
    PRCList      queue;
    PRMonitor*   monitor;
    PRThread*    handlerThread;
    EventQueueType type;
    PRBool       processingEvents;
#if defined(VMS_EVENTS_USE_EF)
    int		 efn;
    int		 notifyCount;
#elif defined(XP_UNIX)
    PRInt32      eventPipe[2];
	int          notifyCount;
#elif defined(_WIN32) || defined(WIN16)
    HWND         eventReceiverWindow;
#elif defined(XP_OS2)
    HWND         eventReceiverWindow;
#elif defined(XP_BEOS)
    port_id      eventport;
#endif
};

#define PR_EVENT_PTR(_qp) \
    ((PLEvent*) ((char*) (_qp) - offsetof(PLEvent, link)))

static PRStatus    _pl_SetupNativeNotifier(PLEventQueue* self);
static void        _pl_CleanupNativeNotifier(PLEventQueue* self);
static PRStatus    _pl_NativeNotify(PLEventQueue* self);
static PRStatus    _pl_AcknowledgeNativeNotify(PLEventQueue* self);
static void        _md_CreateEventQueue( PLEventQueue *eventQueue );


#if defined(_WIN32) || defined(WIN16) || defined(XP_OS2)
#if defined(XP_OS2)
ULONG _pr_PostEventMsgId;
static char *_pr_eventWindowClass = "NSPR:EventWindow";
#else
UINT _pr_PostEventMsgId;
static char *_pr_eventWindowClass = "NSPR:EventWindow";
#endif /* OS2 */
#endif /* Win32, Win16, OS2 */

/*******************************************************************************
 * Event Queue Operations
 ******************************************************************************/

/*
** _pl_CreateEventQueue() -- Create the event queue
**
**
*/
static PLEventQueue *
    _pl_CreateEventQueue(
        char *name,
        PRThread *handlerThread,
        EventQueueType  qtype
)
{
    PRStatus err;
    PLEventQueue* self = NULL;
    PRMonitor* mon = NULL;

    if (event_lm == NULL)
        event_lm = PR_NewLogModule("event");

    self = PR_NEWZAP(PLEventQueue);
    if (self == NULL) return NULL;

    mon = PR_NewNamedMonitor(name);
    if (mon == NULL) goto error;

    self->name = name;
    self->monitor = mon;
    self->handlerThread = handlerThread;
    self->processingEvents = PR_FALSE;
    self->type = qtype;
    PR_INIT_CLIST(&self->queue);
    if ( qtype == EventQueueIsNative )
    {
        err = _pl_SetupNativeNotifier(self);
        if (err) goto error;
    }
    _md_CreateEventQueue( self );
    return self;

  error:
    if (mon != NULL)
    PR_DestroyMonitor(mon);
    PR_DELETE(self);
    return NULL;
} /* end _pl_CreateEventQueue() */


PR_IMPLEMENT(PLEventQueue*)
PL_CreateEventQueue(char* name, PRThread* handlerThread)
{
    return( _pl_CreateEventQueue( name, handlerThread, EventQueueIsNative ));
}

PR_EXTERN(PLEventQueue *) 
    PL_CreateNativeEventQueue(
        char *name, 
        PRThread *handlerThread
    )
{
    return( _pl_CreateEventQueue( name, handlerThread, EventQueueIsNative ));
} /* --- end PL_CreateNativeEventQueue() --- */

PR_EXTERN(PLEventQueue *) 
    PL_CreateMonitoredEventQueue(
        char *name,
        PRThread *handlerThread
    )
{
    return( _pl_CreateEventQueue( name, handlerThread, EventQueueIsMonitored ));
} /* --- end PL_CreateMonitoredEventQueue() --- */



PR_IMPLEMENT(PRMonitor*)
PL_GetEventQueueMonitor(PLEventQueue* self)
{
    return self->monitor;
}

static void PR_CALLBACK
_pl_destroyEvent(PLEvent* event, void* data, PLEventQueue* queue)
{
#ifdef XP_MAC
#pragma unused (data, queue)
#endif
    PL_DequeueEvent(event, queue);
    PL_DestroyEvent(event);
}

PR_IMPLEMENT(void)
PL_DestroyEventQueue(PLEventQueue* self)
{
    PR_EnterMonitor(self->monitor);

    /* destroy undelivered events */
    PL_MapEvents(self, _pl_destroyEvent, NULL);

    if ( self->type == EventQueueIsNative )
        _pl_CleanupNativeNotifier(self);

    /* destroying the monitor also destroys the name */
    PR_ExitMonitor(self->monitor);
    PR_DestroyMonitor(self->monitor);
    PR_DELETE(self);

}

PR_IMPLEMENT(PRStatus)
PL_PostEvent(PLEventQueue* self, PLEvent* event)
{
    PRStatus err = PR_SUCCESS;
    PRMonitor* mon;

    if (self == NULL)
    return PR_FAILURE;

    mon = self->monitor;
    PR_EnterMonitor(mon);

    /* insert event into thread's event queue: */
    if (event != NULL) {
    PR_APPEND_LINK(&event->link, &self->queue);
    }

    /* notify even if event is NULL */
    if ( self->type == EventQueueIsNative )
        err = _pl_NativeNotify(self);

    /*
     * This may fall on deaf ears if we're really notifying the native 
     * thread, and no one has called PL_WaitForEvent (or PL_EventLoop):
     */
    err = PR_Notify(mon);
    PR_ExitMonitor(mon);
    return err;
}

PR_IMPLEMENT(void*)
PL_PostSynchronousEvent(PLEventQueue* self, PLEvent* event)
{
    void* result;

    if (self == NULL)
    return NULL;

    PR_ASSERT(event != NULL);
    PR_CEnterMonitor(event);

    if (PR_CurrentThread() == self->handlerThread) {
	/* Handle the case where the thread requesting the event handling
	   is also the thread that's supposed to do the handling. */
	result = event->handler(event);
    }
    else {
	int inEventQueueMon = PR_GetMonitorEntryCount(self->monitor);
	int i, entryCount = self->monitor->entryCount;

	event->synchronousResult = (void*)PR_TRUE;
	PL_PostEvent(self, event);
	/* We need to temporarily give up our event queue monitor if
	   we're holding it, otherwise, the thread we're going to wait
	   for notification from won't be able to enter it to process
	   the event. */
	if (inEventQueueMon) {
	    for (i = 0; i < entryCount; i++)
		PR_ExitMonitor(self->monitor);
	}
	PR_CWait(event, PR_INTERVAL_NO_TIMEOUT);	/* wait for event to be handled or destroyed */
	if (inEventQueueMon) {
	    for (i = 0; i < entryCount; i++)
		PR_EnterMonitor(self->monitor);
	}
    	result = event->synchronousResult;
	event->synchronousResult = NULL;
    }

    PR_CExitMonitor(event);

    /* For synchronous events, they're destroyed here on the caller's
       thread before the result is returned. See PL_HandleEvent. */
    PL_DestroyEvent(event);

    return result;
}

PR_IMPLEMENT(PLEvent*)
PL_GetEvent(PLEventQueue* self)
{
    PLEvent* event = NULL;
    PRStatus err = PR_SUCCESS;
    PRMonitor* mon;

    if (self == NULL)
    return NULL;

    mon = self->monitor;
    if (mon) {
      PR_EnterMonitor(mon);
    }

    if ( self->type == EventQueueIsNative )
        err = _pl_AcknowledgeNativeNotify(self);

    if (err) goto done;

    if (!PR_CLIST_IS_EMPTY(&self->queue)) {
    /* then grab the event and return it: */
    event = PR_EVENT_PTR(self->queue.next);
    PR_REMOVE_AND_INIT_LINK(&event->link);
    }

  done:
    if (mon) {
      PR_ExitMonitor(mon);
    }
    return event;
}

PR_IMPLEMENT(PRBool)
PL_EventAvailable(PLEventQueue* self)
{
    PRBool result = PR_FALSE;

    if (self == NULL)
    return PR_FALSE;

    PR_EnterMonitor(self->monitor);

    if (!PR_CLIST_IS_EMPTY(&self->queue)) 
    result = PR_TRUE;

    PR_ExitMonitor(self->monitor);
    return result;
}

PR_IMPLEMENT(void)
PL_MapEvents(PLEventQueue* self, PLEventFunProc fun, void* data)
{
    PRCList* qp;

    if (self == NULL)
    return;

    PR_EnterMonitor(self->monitor);
    qp = self->queue.next;
    while (qp != &self->queue) {
    PLEvent* event = PR_EVENT_PTR(qp);
    qp = qp->next;
    (*fun)(event, data, self);
    }
    PR_ExitMonitor(self->monitor);
}

static void PR_CALLBACK
_pl_DestroyEventForOwner(PLEvent* event, void* owner, PLEventQueue* queue)
{
    PR_ASSERT(PR_GetMonitorEntryCount(queue->monitor) > 0);
    if (event->owner == owner) {
    PR_LOG(event_lm, PR_LOG_DEBUG,
           ("$$$ \tdestroying event %0x for owner %0x", event, owner));
    PL_DequeueEvent(event, queue);
    if (event->synchronousResult == (void*)PR_TRUE) {
        PR_CEnterMonitor(event);
        event->synchronousResult = NULL;
        PR_CNotify(event);
        PR_CExitMonitor(event);
    }
    else {
        PL_DestroyEvent(event);
    }
    }
    else {
    PR_LOG(event_lm, PR_LOG_DEBUG,
           ("$$$ \tskipping event %0x for owner %0x", event, owner));
    }
}

PR_IMPLEMENT(void)
PL_RevokeEvents(PLEventQueue* self, void* owner)
{
    if (self == NULL)
    return;

    PR_LOG(event_lm, PR_LOG_DEBUG,
         ("$$$ revoking events for owner %0x", owner));

    /*
    ** First we enter the monitor so that no one else can post any events
    ** to the queue:
    */
    PR_EnterMonitor(self->monitor);
    PR_LOG(event_lm, PR_LOG_DEBUG, ("$$$ owner %0x, entered monitor", owner));

    /*
    ** Discard any pending events for this owner:
    */
    PL_MapEvents(self, _pl_DestroyEventForOwner, owner);

#ifdef DEBUG
    {
	PRCList* qp = self->queue.next;
	while (qp != &self->queue) {
	    PLEvent* event = PR_EVENT_PTR(qp);
	    qp = qp->next;
	    PR_ASSERT(event->owner != owner);
	}
    }
#endif /* DEBUG */

    PR_ExitMonitor(self->monitor);

    PR_LOG(event_lm, PR_LOG_DEBUG,
           ("$$$ revoking events for owner %0x", owner));
}

PR_IMPLEMENT(void)
PL_ProcessPendingEvents(PLEventQueue* self)
{
    if (self == NULL)
    return;

  if (PR_FALSE != self->processingEvents) return;

    self->processingEvents = PR_TRUE;
#if !defined(WIN32)
    while (PR_TRUE) {
    PLEvent* event = PL_GetEvent(self);
        if (event == NULL) break;

    PR_LOG(event_lm, PR_LOG_DEBUG, ("$$$ processing event"));
    PL_HandleEvent(event);
    PR_LOG(event_lm, PR_LOG_DEBUG, ("$$$ done processing event"));
    }
#else
    /* Only process the events that are already in the queue, and
     * not any new events that get added. Do this by making a copy of
     * the queue
     */
    PR_EnterMonitor(self->monitor);
    if (PR_CLIST_IS_EMPTY(&self->queue)) {
      PR_ExitMonitor(self->monitor);
    } else {
      struct PLEventQueue  tmpQueue;
      /* Copy the events to a temporary queue */
      memcpy(&tmpQueue, self, sizeof(tmpQueue));
      tmpQueue.queue.next->prev = &tmpQueue.queue;
      tmpQueue.queue.prev->next = &tmpQueue.queue;
      tmpQueue.monitor = 0; /* don't waste time locking this queue when getting events */
      PR_INIT_CLIST(&self->queue);
      PR_ExitMonitor(self->monitor);
      /* Now process the existing events */
      while (PR_TRUE) {
      PLEvent* event = PL_GetEvent(&tmpQueue);
          if (event == NULL) break;
      PR_LOG(event_lm, PR_LOG_DEBUG, ("$$$ processing event"));
      PL_HandleEvent(event);
      PR_LOG(event_lm, PR_LOG_DEBUG, ("$$$ done processing event"));
      }
    }
#endif
    self->processingEvents = PR_FALSE;
}

/*******************************************************************************
 * Event Operations
 ******************************************************************************/

PR_IMPLEMENT(void)
PL_InitEvent(PLEvent* self, void* owner,
         PLHandleEventProc handler,
         PLDestroyEventProc destructor)
{
    PR_INIT_CLIST(&self->link);
    self->handler = handler;
    self->destructor = destructor;
    self->owner = owner;
    self->synchronousResult = NULL;
}

PR_IMPLEMENT(void*)
PL_GetEventOwner(PLEvent* self)
{
    return self->owner;
}

PR_IMPLEMENT(void)
PL_HandleEvent(PLEvent* self)
{
    void* result;

    if (self == NULL)
        return;

    /* This event better not be on an event queue anymore. */
    PR_ASSERT(PR_CLIST_IS_EMPTY(&self->link));

    result = (*self->handler)(self);
    if (NULL != self->synchronousResult) {
    PR_CEnterMonitor(self);
    self->synchronousResult = result;
    PR_CNotify(self);    /* wake up the guy waiting for the result */
    PR_CExitMonitor(self);
    }
    else {
    /* For asynchronous events, they're destroyed by the event-handler
       thread. See PR_PostSynchronousEvent. */
    PL_DestroyEvent(self);
    }
}

PR_IMPLEMENT(void)
PL_DestroyEvent(PLEvent* self)
{
    if (self == NULL)
    return;

    /* This event better not be on an event queue anymore. */
    PR_ASSERT(PR_CLIST_IS_EMPTY(&self->link));

    (*self->destructor)(self);
}

PR_IMPLEMENT(void)
PL_DequeueEvent(PLEvent* self, PLEventQueue* queue)
{
#ifdef XP_MAC
#pragma unused (queue)
#endif
    if (self == NULL)
    return;

    /* Only the owner is allowed to dequeue events because once the 
       client has put it in the queue, they have no idea whether it's 
       been processed and destroyed or not. */
/*    PR_ASSERT(queue->handlerThread == PR_CurrentThread());*/

    PR_EnterMonitor(queue->monitor);

    PR_ASSERT(!PR_CLIST_IS_EMPTY(&self->link));
    PR_REMOVE_AND_INIT_LINK(&self->link);

    PR_ExitMonitor(queue->monitor);
}

/*******************************************************************************
 * Pure Event Queues
 *
 * For when you're only processing PLEvents and there is no native
 * select, thread messages, or AppleEvents.
 ******************************************************************************/

PR_IMPLEMENT(PLEvent*)
PL_WaitForEvent(PLEventQueue* self)
{
    PLEvent* event;
    PRMonitor* mon;

    if (self == NULL)
    return NULL;

    mon = self->monitor;
    PR_EnterMonitor(mon);

    while ((event = PL_GetEvent(self)) == NULL) {
        PRStatus err;
        PR_LOG(event_lm, PR_LOG_DEBUG, ("$$$ waiting for event"));
        err = PR_Wait(mon, PR_INTERVAL_NO_TIMEOUT);
        if ((err == PR_FAILURE)
            && (PR_PENDING_INTERRUPT_ERROR == PR_GetError())) break;
    }

    PR_ExitMonitor(mon);
    return event;
}

PR_IMPLEMENT(void)
PL_EventLoop(PLEventQueue* self)
{
    if (self == NULL)
    return;

    while (PR_TRUE) {
    PLEvent* event = PL_WaitForEvent(self);
    if (event == NULL) {
        /* This can only happen if the current thread is interrupted */
        return;
    }

        PR_LOG(event_lm, PR_LOG_DEBUG, ("$$$ processing event"));
    PL_HandleEvent(event);
    PR_LOG(event_lm, PR_LOG_DEBUG, ("$$$ done processing event"));
    }
}

/*******************************************************************************
 * Native Event Queues
 *
 * For when you need to call select, or WaitNextEvent, and yet also want
 * to handle PLEvents.
 ******************************************************************************/

static PRStatus
_pl_SetupNativeNotifier(PLEventQueue* self)
{
#if defined(XP_MAC)
#pragma unused (self)
#endif

#if defined(VMS_EVENTS_USE_EF)
    {
#ifdef VMS_USE_GETEF
        unsigned int status;
        status = LIB$GET_EF(&self->efn);
        if (!$VMS_STATUS_SUCCESS(status))
            return PR_FAILURE;
#else
        static int next_event_flag = 2;
        if (next_event_flag <= 23) {
            self->efn = next_event_flag++;
        }
        else {
            printf("ERROR: Out of event flags\n");
            return PR_FAILURE;
        }
#endif
	return PR_SUCCESS;
    }
#elif defined(XP_UNIX)
    int err;
    int flags;

#if defined(VMS_EVENTS_USE_SOCKETS)
    err = socketpair(AF_UNIX,SOCK_STREAM,0,self->eventPipe);
#else
    err = pipe(self->eventPipe);
#endif
    if (err != 0) {
        return PR_FAILURE;
    }

    /* make the pipe nonblocking */
    flags = fcntl(self->eventPipe[0], F_GETFL, 0);
    if (flags == -1) {
        goto failed;
    }
    err = fcntl(self->eventPipe[0], F_SETFL, flags | O_NONBLOCK);
    if (err == -1) {
        goto failed;
    }
    flags = fcntl(self->eventPipe[1], F_GETFL, 0);
    if (flags == -1) {
        goto failed;
    }
    err = fcntl(self->eventPipe[1], F_SETFL, flags | O_NONBLOCK);
    if (err == -1) {
        goto failed;
    }
    return PR_SUCCESS;

failed:
    close(self->eventPipe[0]);
    close(self->eventPipe[1]);
    return PR_FAILURE;
#elif defined(XP_BEOS)
	/* hook up to the nsToolkit queue, however the appshell
	 * isn't necessairly started, so we might have to create
	 * the queue ourselves
	 */
	char		portname[64];
	char		semname[64];
	sprintf(portname, "event%lx", self->handlerThread);
	sprintf(semname, "sync%lx", self->handlerThread);

	if((self->eventport = find_port(portname)) < 0)
	{
		/* create port
		 */
		self->eventport = create_port(100, portname);

		/* We don't use the sem, but it has to be there
		 */
		create_sem(0, semname);
	}

    return PR_SUCCESS;
#else
    return PR_SUCCESS;
#endif
}

static void
_pl_CleanupNativeNotifier(PLEventQueue* self)
{
#if defined(XP_MAC)
#pragma unused (self)
#endif

#if defined(VMS_EVENTS_USE_EF)
#ifdef VMS_USE_GETEF
    {
        unsigned int status;
        status = LIB$FREE_EF(&self->efn);
    }
#endif /* VMS_USE_GETEF */
#elif defined(XP_UNIX)
    close(self->eventPipe[0]);
    close(self->eventPipe[1]);
#endif
}

#if defined(_WIN32) || defined(WIN16)
static PRStatus
_pl_NativeNotify(PLEventQueue* self)
{
	PostMessage( self->eventReceiverWindow, _pr_PostEventMsgId,
	    (WPARAM)0, (LPARAM)self);
    return PR_SUCCESS;
}/* --- end _pl_NativeNotify() --- */
#endif

#if defined(XP_OS2)
static PRStatus
_pl_NativeNotify(PLEventQueue* self)
{
    BOOL rc = WinPostMsg( self->eventReceiverWindow, _pr_PostEventMsgId,
                       0, MPFROMP(self));
    return (rc == TRUE) ? PR_SUCCESS : PR_FAILURE;
}/* --- end _pl_NativeNotify() --- */
#endif /* XP_OS2 */

#if defined(VMS_EVENTS_USE_EF)
/* Just set the event flag */
static PRStatus
_pl_NativeNotify(PLEventQueue* self)
{
        unsigned int status;
        status = SYS$SETEF(self->efn);
        self->notifyCount++;
        if ($VMS_STATUS_SUCCESS(status))
            return PR_SUCCESS;
        else
            return PR_FAILURE;
}/* --- end _pl_NativeNotify() --- */
#elif defined(XP_UNIX)
static PRStatus
_pl_NativeNotify(PLEventQueue* self)
{
#define NOTIFY_TOKEN    0xFA
    PRInt32 count;
    unsigned char buf[] = { NOTIFY_TOKEN };

    count = write(self->eventPipe[1], buf, 1);
	if (count == 1) {
		self->notifyCount++;
		return PR_SUCCESS;
	} else if ((count == -1) && ((errno == EAGAIN) || (errno == EWOULDBLOCK))) {
		return PR_SUCCESS;
	} else
		return PR_FAILURE;
}/* --- end _pl_NativeNotify() --- */
#endif /* XP_UNIX */

#if defined(XP_BEOS)
struct ThreadInterfaceData
{
	void	*data;
	int32	sync;
};

static PRStatus
_pl_NativeNotify(PLEventQueue* self)
{
	struct ThreadInterfaceData	 id;
	id.data = self;
	id.sync = false;
	write_port(self->eventport, 'natv', &id, sizeof(id));

    return PR_SUCCESS;    /* Is this correct? */
}
#endif /* XP_BEOS */

#if defined(XP_MAC)
static PRStatus
_pl_NativeNotify(PLEventQueue* self)
{
#pragma unused (self)
    return PR_SUCCESS;    /* XXX can fail? */
}
#endif /* XP_MAC */

static PRStatus
_pl_AcknowledgeNativeNotify(PLEventQueue* self)
{
#if defined(VMS_EVENTS_USE_EF)
/* Clear the event flag if we're all done */
/* NOTE that we might want to always clear the event flag, even if the */
/* notifyCount says we shouldn't. */
    if (self->notifyCount <= 0) return PR_SUCCESS;
    self->notifyCount--;
    if (self->notifyCount == 0) {
        unsigned int status;
        status = SYS$CLREF(self->efn);
        if (!$VMS_STATUS_SUCCESS(status))
            return PR_FAILURE;
    }
    return PR_SUCCESS;
#elif defined(XP_UNIX)

    PRInt32 count;
    unsigned char c;

	if (self->notifyCount <= 0) return PR_SUCCESS;
    /* consume the byte NativeNotify put in our pipe: */
    count = read(self->eventPipe[0], &c, 1);
	if ((count == 1) && (c == NOTIFY_TOKEN)) {
		self->notifyCount--;
		return PR_SUCCESS;
	} else if ((count == -1) && ((errno == EAGAIN) || (errno == EWOULDBLOCK))) {
		return PR_SUCCESS;
	} else
		return PR_FAILURE;
#else

#if defined(XP_MAC)
#pragma unused (self)
#endif

    /* nothing to do on the other platforms */
    return PR_SUCCESS;
#endif
}

PR_IMPLEMENT(PRInt32)
PL_GetEventQueueSelectFD(PLEventQueue* self)
{
    if (self == NULL)
    return -1;

#if defined(VMS_EVENTS_USE_EF)
    return self->efn;
#elif defined(XP_UNIX)
    return self->eventPipe[0];
#else
    return -1;    /* other platforms don't handle this (yet) */
#endif
}

PR_IMPLEMENT(PRBool)
PL_IsQueueOnCurrentThread( PLEventQueue *queue )
{
    PRThread *me = PR_GetCurrentThread();
    if ( me == queue->handlerThread )
        return PR_TRUE;
    else
        return PR_FALSE;
} /* end PL_IsQueueOnCurrentThread() */

#if defined(WIN16) || defined(_WIN32)
/*
** Global Instance handle...
** In Win32 this is the module handle of the DLL.
**
*/
static HINSTANCE _pr_hInstance;
#endif

#if defined(WIN16)
/*
** Function LibMain() is required by Win16
**
*/
int CALLBACK LibMain( HINSTANCE hInst, WORD wDataSeg, 
                      WORD cbHeapSize, LPSTR lpszCmdLine )
{
    _pr_hInstance = hInst;
    return TRUE;
}
#endif /* WIN16 */

#if defined(_WIN32)

/*
** Initialization routine for the NSPR DLL...
*/

BOOL WINAPI DllMain (HINSTANCE hDLL, DWORD dwReason, LPVOID lpReserved)
{
  switch (dwReason)
  {
    case DLL_PROCESS_ATTACH:
      _pr_hInstance = hDLL;
      break;

    case DLL_THREAD_ATTACH:
      break;

    case DLL_THREAD_DETACH:
      break;

    case DLL_PROCESS_DETACH:
      _pr_hInstance = NULL;
      break;
  }

    return TRUE;
}
#endif


#if defined(WIN16) || defined(_WIN32) || defined(XP_OS2)
#ifdef XP_OS2
MRESULT EXPENTRY
_md_EventReceiverProc(HWND hwnd, ULONG uMsg, MPARAM wParam, MPARAM lParam)
#else
LRESULT CALLBACK 
#if defined(WIN16)
__loadds
#endif
_md_EventReceiverProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
#endif
{
    if (_pr_PostEventMsgId == uMsg )
    {
		PREventQueue *queue = (PREventQueue *)lParam;
    
    	PR_ProcessPendingEvents(queue);
#ifdef XP_OS2
            return MRFROMLONG(TRUE);
#else
            return TRUE;
#endif
        }
    return DefWindowProc(hwnd, uMsg, wParam, lParam);
}


static PRBool   isInitialized;
static PRCallOnceType once;
static PRLock   *initLock;

/*
** InitWinEventLib() -- Create the Windows initialization lock
**
*/
static PRStatus InitEventLib( void )
{
    PR_ASSERT( initLock == NULL );
    
    initLock = PR_NewLock();
    if ( NULL == initLock )
        return PR_FAILURE;
    else
        return PR_SUCCESS;
} /* end InitWinEventLib() */

#endif /* Win16, Win32, OS2 */

#if defined(_WIN32) || defined(WIN16) || defined(XP_OS2)

#endif

#if defined(_WIN32) || defined(WIN16)
/*
** _md_CreateEventQueue() -- ModelDependent initializer
*/
static void _md_CreateEventQueue( PLEventQueue *eventQueue )
{
    WNDCLASS wc;
    
    /*
    ** If this is the first call to PL_InitializeEventsLib(),
    ** make the call to InitWinEventLib() to create the initLock.
    **
    ** Then lock the initializer lock to insure that
    ** we have exclusive control over the initialization sequence.
    **
    */


    /* Register the windows message for NSPR Event notification */
    _pr_PostEventMsgId = RegisterWindowMessage("NSPR_PostEvent");

    /* Register the class for the event receiver window */
    if (!GetClassInfo(_pr_hInstance, _pr_eventWindowClass, &wc)) {
        wc.style         = 0;
        wc.lpfnWndProc   = _md_EventReceiverProc;
        wc.cbClsExtra    = 0;
        wc.cbWndExtra    = 0;
        wc.hInstance     = _pr_hInstance;
        wc.hIcon         = NULL;
        wc.hCursor       = NULL;
        wc.hbrBackground = (HBRUSH) NULL;
        wc.lpszMenuName  = (LPCSTR) NULL;
        wc.lpszClassName = _pr_eventWindowClass;
        RegisterClass(&wc);
        }
        
    /* Create the event receiver window */
    eventQueue->eventReceiverWindow = CreateWindow(_pr_eventWindowClass,
                                        "NSPR:EventReceiver",
                                            0, 0, 0, 10, 10,
                                            NULL, NULL, _pr_hInstance,
                                            NULL);
    PR_ASSERT(eventQueue->eventReceiverWindow);

    return;    
} /* end _md_CreateEventQueue() */
#endif /* Winxx */

#if defined(XP_OS2)
/*
** _md_CreateEventQueue() -- ModelDependent initializer
*/
static void _md_CreateEventQueue( PLEventQueue *eventQueue )
{
    /* Must have HMQ for this & can't assume we already have appshell */
    if( FALSE == WinQueryQueueInfo( HMQ_CURRENT, NULL, 0))
    {
       HAB hab = WinInitialize( 0);
       WinCreateMsgQueue( hab, 0);
    }

    if( !_pr_PostEventMsgId)
    {
       WinRegisterClass( 0 /* hab_current */,
                         _pr_eventWindowClass,
                         _md_EventReceiverProc,
                         0, 0);

       _pr_PostEventMsgId = WinAddAtom( WinQuerySystemAtomTable(),
                                        "NSPR_PostEvent");
    }

    eventQueue->eventReceiverWindow = WinCreateWindow( HWND_DESKTOP,
                                                       _pr_eventWindowClass,
                                                       "", 0,
                                                       0, 0, 0, 0,
                                                       HWND_DESKTOP,
                                                       HWND_TOP,
                                                       0,
                                                       NULL,
                                                       NULL);
    PR_ASSERT(eventQueue->eventReceiverWindow);

    return;    
} /* end _md_CreateEventQueue() */
#endif /* XP_OS2 */

#if defined(XP_UNIX) || defined(XP_MAC) || defined(XP_BEOS)
/*
** _md_CreateEventQueue() -- ModelDependent initializer
*/
static void _md_CreateEventQueue( PLEventQueue *eventQueue )
{
#ifdef XP_MAC 
#pragma unused(eventQueue) 
#endif 

    /* there's really nothing special to do here,
    ** the guts of the unix stuff is in the setupnativenotify
    ** and related functions.
    */
    return;    
} /* end _md_CreateEventQueue() */
#endif /* XP_UNIX */
/* --- end plevent.c --- */