File: FXEventDispatcher.cpp

package info (click to toggle)
gogglesmm 1.2.5-6
  • links: PTS
  • area: main
  • in suites: forky, sid
  • size: 16,812 kB
  • sloc: cpp: 231,960; ansic: 893; xml: 222; makefile: 33
file content (623 lines) | stat: -rw-r--r-- 21,547 bytes parent folder | download | duplicates (2)
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
/********************************************************************************
*                                                                               *
*                          E v e n t   D i s p a t c h e r                      *
*                                                                               *
*********************************************************************************
* Copyright (C) 2019,2022 by Jeroen van der Zijp.   All Rights Reserved.        *
********************************************************************************/
#include "xincs.h"
#include "fxver.h"
#include "fxdefs.h"
#include "fxmath.h"
#include "FXAtomic.h"
#include "FXElement.h"
#include "FXHash.h"
#include "FXCallback.h"
#include "FXAutoThreadStorageKey.h"
#include "FXThread.h"
#include "FXException.h"
#include "FXReactor.h"
#include "FXReactorCore.h"
#include "FXDispatcher.h"
#include "FXEventDispatcher.h"

/*
  Notes:

  - FXEventDispatcher processes I/O handles, timers, signals, and idle activities
    just like FXDispatcher, but also processes messages/events from the display
    connection.

  - FXRawEvents from display connection are passed to dispatchEvent().

  - FXEventDispatcher::dispatch() must re-implement FXReactor::dispatch() because
    display connection is special in some sense [having to do with message queue
    management].

  - FIXME link to chain of FXEventLoop items from this class, and add the modal
    loops here.

  - These may be useful additions:

      HANDLE CreateWaitableTimerEx(LPSECURITY_ATTRIBUTES lpTimerAttributes,LPCWSTR lpTimerName,
                                   DWORD dwFlags,DWORD dwDesiredAccess);
      BOOL SetWaitableTimer(HANDLE hTimer,const LARGE_INTEGER *lpDueTime,
                            LONG lPeriod,PTIMERAPCROUTINE pfnCompletionRoutine,LPVOID lpArgToCompletionRoutine,BOOL fResume);
      BOOL SetWaitableTimerEx(HANDLE hTimer,const LARGE_INTEGER *lpDueTime,
                              LONG lPeriod,PTIMERAPCROUTINE pfnCompletionRoutine,LPVOID lpArgToCompletionRoutine,
                              PREASON_CONTEXT WakeContext,ULONG TolerableDelay);
      BOOL CancelWaitableTimer(HANDLE hTimer);
      DWORD WaitForSingleObject(HANDLE hHandle,DWORD  dwMilliseconds);

      int timerfd_create(int clockid, int flags);
      int timerfd_settime(int fd,int flags,
                          const struct itimerspec* new_value,
                          struct itimerspec* old_value);
      int timerfd_gettime(int fd,struct itimerspec* curr_value);

*/


using namespace FX;

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

namespace FX {

// Units of time in nanoseconds
const FXTime seconds=1000000000;
const FXTime milliseconds=1000000;
const FXTime microseconds=1000;


// Construct event dispatcher object
FXEventDispatcher::FXEventDispatcher():display(nullptr){
  }


// Initialize dispatcher
FXbool FXEventDispatcher::init(FXptr dpy){
  if(FXDispatcher::init()){
    if(dpy){
#if !defined(WIN32)
      addHandle(ConnectionNumber((Display*)dpy),InputRead);
#endif
      display=dpy;
      return true;
      }
    }
  return false;
  }


// Initialize dispatcher
FXbool FXEventDispatcher::init(){
  if(FXDispatcher::init()){
    display=nullptr;
    return true;
    }
  return false;
  }


#if defined(WIN32) //////////////////////////////////////////////////////////////

// Dispatch driver
FXbool FXEventDispatcher::dispatch(FXTime blocking,FXuint flags){
  if(internals){
    FXTime now,due,delay,interval;
    FXuint sig,nxt,mode,ms;
    FXInputHandle hnd;
    FXRawEvent event;

    // Loop till we got something
    while(1){

      // Check for timeout
      delay=forever;
      if(flags&DispatchTimers){
        due=nextTimeout();
        if(due<forever){
          now=FXThread::time();
          delay=due-now;
          if(delay<microseconds){
            if(dispatchTimeout(due)) return true;       // Timer activity
            continue;
            }
          }
        }

      // Check for signal
      if(flags&DispatchSignals){
        sig=nxt=sigreceived;
        if(atomicSet(&internals->signotified[sig],0)){
          do{ nxt=(nxt+63)&63; }while(!internals->signotified[nxt] && nxt!=sig);
          sigreceived=nxt;
          if(dispatchSignal(sig)) return true;          // Signal activity
          continue;
          }
        }

      // Peek for messages.  This marks the message queue as unsignalled, so that
      // MsgWaitForMultipleObjects() would block even if there are unhandled messages.
      // The fix is to call MsgWaitForMultipleObjects() only AFTER having ascertained
      // that there are NO unhandled messages queued up.
      if(flags&DispatchEvents){
        if(PeekMessage(&event,nullptr,0,0,PM_REMOVE)){
          if(dispatchEvent(event)) return true;         // Event activity
          continue;
          }
        }

      // Check active handles
      if(0<=current && current<numhandles){
        hnd=internals->handles[current];                // Shuffle raised handle up in the list
        mode=internals->modes[current];                 // To give all handles equal play time
        nxt=(current+1)%numhandles;
        swap(internals->handles[current],internals->handles[nxt]);
        swap(internals->modes[current],internals->modes[nxt]);
        current=-1;
        if(dispatchHandle(hnd,mode,flags)) return true; // IO activity
        continue;
        }

      // Select active handles or events; don't block
      if(flags&DispatchEvents){
        current=MsgWaitForMultipleObjectsEx(numhandles,internals->handles,0,QS_ALLINPUT,MWMO_ALERTABLE);
        }
      else{
        current=WaitForMultipleObjectsEx(numhandles,internals->handles,false,0,true);
        }

      // No handles were active
      if(current==WAIT_TIMEOUT){

        // Idle callback if we're about to block
        if(flags&DispatchIdle){
          if(dispatchIdle()) return true;               // Idle activity
          }

        // We're not blocking
        if(blocking<=0) return false;

        // One more call to PeekMessage() here because the preceding idle processing
        // may have caused some more messages to be posted to the message queue.
        // A call to MsgWaitForMultipleObjects() when there are messages already in
        // the queue would block until the next message comes in.
        if(flags&DispatchEvents){
          if(PeekMessage(&event,nullptr,0,0,PM_REMOVE)){
           if(dispatchEvent(event)) return true;        // Event activity
           continue;
           }
         }

        // Indefinite wait
        ms=INFINITE;

        // If not blocking indefinitely, don't exceed maxwait time interval.
        interval=Math::imin(delay,blocking);
        if(interval<forever){
          interval=Math::imin(interval,maxwait);
          ms=(FXuint)(interval/milliseconds);
          }

        // Select active handles or events; wait for timeout or maximum block time
        if(flags&DispatchEvents){
          current=MsgWaitForMultipleObjectsEx(numhandles,internals->handles,ms,QS_ALLINPUT,MWMO_ALERTABLE);
          }
        else{
          current=WaitForMultipleObjectsEx(numhandles,internals->handles,false,ms,true);
          }

        // Return if there was no timeout within maximum block time
        if(current==WAIT_TIMEOUT){
          if(blocking<forever){                         // Next blocking period reduced by time already expired
            blocking-=interval;
            if(blocking<=0) return false;               // Nothing happened during blocking period!
            }
          continue;
          }
        }

      // I/O completion took place; maybe some i/o took place, causing
      // somestuff to have been changed; we must leave loop.
      if(current==WAIT_IO_COMPLETION) return false;

      // Bad stuff happened
      if(current==WAIT_FAILED || current>=WAIT_ABANDONED_0){
        throw FXFatalException("FXReactor::dispatch: error waiting on handles.");
        }
      }
    }
  return false;
  }

#elif defined(HAVE_EPOLL_CREATE1) ///////////////////////////////////////////////

// Dispatch driver
FXbool FXEventDispatcher::dispatch(FXTime blocking,FXuint flags){
  if(internals){
    FXTime now,due,delay,interval;
    FXuint sig,nxt,ms,mode,ticks;
    FXInputHandle hnd;
    FXRawEvent event,ev;

    // Loop till we got something
    while(1){

      // Check for timeout
      delay=forever;
      if(flags&DispatchTimers){
        due=nextTimeout();
        if(due<forever){
          now=FXThread::time();
          delay=due-now;
          if(delay<microseconds){
            if(dispatchTimeout(due)) return true;       // Timer activity
            continue;
            }
          }
        }

      // Check for signal
      if(flags&DispatchSignals){
        sig=nxt=sigreceived;
        if(atomicSet(&internals->signotified[sig],0)){
          do{ nxt=(nxt+63)&63; }while(!internals->signotified[nxt] && nxt!=sig);
          sigreceived=nxt;
          if(dispatchSignal(sig)) return true;          // Signal activity
          continue;
          }
        }

      // Handle events
      if(flags&DispatchEvents){
        if(XEventsQueued((Display*)display,QueuedAfterFlush)){
          XNextEvent((Display*)display,&event);
#if 0
#if 0
          // Event was filtered by input method; get next one
          if(xim && XFilterEvent(&event,None)){
            continue;
            }
          if(xim && getFocusWindow() && XFilterEvent(&event,(Window)getFocusWindow()->id())){    // FIXME
            continue;
            }
#endif
          // Passing in focuswindow to XFilterEvent just didn't work on Gnome3 with either scim or ibus
          if(xim && getFocusWindow() && XFilterEvent(&event,None)){      // [Patch from Roland Baudin] FIXME but also need to deal with keyboard grabs
            return false;
            }
#endif
          // Compress motion events
          if(event.xany.type==MotionNotify){
            while(XPending((Display*)display)){
              XPeekEvent((Display*)display,&ev);
              if((ev.xany.type!=MotionNotify) || (event.xmotion.window!=ev.xmotion.window) || (event.xmotion.state!=ev.xmotion.state)) break;
              XNextEvent((Display*)display,&event);
              }
            }

          // Compress wheel events
          else if((event.xany.type==ButtonPress) && (event.xbutton.button==Button4 || event.xbutton.button==Button5)){
            ticks=1;
            while(XPending((Display*)display)){
              XPeekEvent((Display*)display,&ev);
              if((ev.xany.type!=ButtonPress && ev.xany.type!=ButtonRelease) || (event.xany.window!=ev.xany.window) || (event.xbutton.button!=ev.xbutton.button)) break;
              ticks+=(ev.xany.type==ButtonPress);
              XNextEvent((Display*)display,&event);
              }
            event.xbutton.subwindow=(Window)ticks;      // Stick it here for later
            }

          // Compress configure events
          else if(event.xany.type==ConfigureNotify){
            while(XCheckTypedWindowEvent((Display*)display,event.xconfigure.window,ConfigureNotify,&ev)){
              event.xconfigure.width=ev.xconfigure.width;
              event.xconfigure.height=ev.xconfigure.height;
              if(ev.xconfigure.send_event){
                event.xconfigure.x=ev.xconfigure.x;
                event.xconfigure.y=ev.xconfigure.y;
                }
              }
            }

          // Event activity
          if(dispatchEvent(event)) return true;         // Event activity
          continue;
          }
        }

      // Check active handles
      if(0<numraised){
        mode=0;
        numraised--;
        current=(current+1)%numwatched;
        hnd=internals->events[current].data.fd;
        if(internals->events[current].events&EPOLLIN){ mode|=InputRead; }
        if(internals->events[current].events&EPOLLOUT){ mode|=InputWrite; }
        if(internals->events[current].events&EPOLLERR){ mode|=InputExcept; }

        // Display connection became active
        if(ConnectionNumber((Display*)display)==hnd) continue;

        // Regular handle became active
        if(dispatchHandle(hnd,mode,flags)) return true; // IO activity
        continue;
        }

      // Select active handles and check signals; don't block
      numwatched=epoll_pwait(internals->handle,internals->events,ARRAYNUMBER(internals->events),0,nullptr);

      // No active handles yet; need to wait
      if(numwatched==0){

        // Idle callback if we're about to block
        if(flags&DispatchIdle){
          if(dispatchIdle()) return true;               // Idle activity
          }

        // We're not blocking
        if(blocking<=0) return false;

        // Indefinite wait
        ms=-1;

        // If not blocking indefinitely, don't exceed maxwait time interval.
        interval=Math::imin(delay,blocking);
        if(interval<forever){
          interval=Math::imin(interval,maxwait);
          ms=(FXuint)(interval/milliseconds);
          }

        // Select active handles and check signals, waiting for timeout or maximum block time
        numwatched=epoll_pwait(internals->handle,internals->events,ARRAYNUMBER(internals->events),ms,nullptr);

        // Return if there was no timeout within maximum block time
        if(numwatched==0){
          if(blocking<forever){                         // Next blocking period reduced by time already expired
            blocking-=interval;
            if(blocking<=0) return false;               // Nothing happened during blocking period!
            }
          continue;
          }
        }

      // Bad stuff happened
      if(numwatched<0){
        if(errno!=EAGAIN && errno!=EINTR){ throw FXFatalException("FXReactor::dispatch: error waiting on handles."); }
        continue;
        }

      // Keep track of original set
      numraised=numwatched;
      }
    }
  return false;
  }

#else ///////////////////////////////////////////////////////////////////////////

// Dispatch driver
FXbool FXEventDispatcher::dispatch(FXTime blocking,FXuint flags){
  if(internals){
    FXTime now,due,delay,interval;
    FXuint sig,nxt,mode,ticks;
    FXRawEvent event,ev;
#if (_POSIX_C_SOURCE >= 200112L)
    struct timespec delta;
#else
    struct timeval delta;
#endif

    // Loop till we got something
    while(1){

      // Check for timeout
      delay=forever;
      if(flags&DispatchTimers){
        due=nextTimeout();
        if(due<forever){
          now=FXThread::time();
          delay=due-now;
          if(delay<microseconds){
            if(dispatchTimeout(due)) return true;       // Timer activity
            continue;
            }
          }
        }

      // Check for signal
      if(flags&DispatchSignals){
        sig=nxt=sigreceived;
        if(atomicSet(&internals->signotified[sig],0)){
          do{ nxt=(nxt+63)&63; }while(!internals->signotified[nxt] && nxt!=sig);
          sigreceived=nxt;
          if(dispatchSignal(sig)) return true;          // Signal activity
          continue;
          }
        }

      // Handle events
      if(flags&DispatchEvents){
        if(XEventsQueued((Display*)display,QueuedAfterFlush)){
          XNextEvent((Display*)display,&event);
#if 0
#if 0
          // Event was filtered by input method; get next one
          if(xim && XFilterEvent(&event,None)){
            continue;
            }
          if(xim && getFocusWindow() && XFilterEvent(&event,(Window)getFocusWindow()->id())){    // FIXME
            continue;
            }
#endif
          // Passing in focuswindow to XFilterEvent just didn't work on Gnome3 with either scim or ibus
          if(xim && getFocusWindow() && XFilterEvent(&event,None)){      // [Patch from Roland Baudin] FIXME but also need to deal with keyboard grabs
            return false;
            }
#endif
          // Compress motion events
          if(event.xany.type==MotionNotify){
            while(XPending((Display*)display)){
              XPeekEvent((Display*)display,&ev);
              if((ev.xany.type!=MotionNotify) || (event.xmotion.window!=ev.xmotion.window) || (event.xmotion.state!=ev.xmotion.state)) break;
              XNextEvent((Display*)display,&event);
              }
            }

          // Compress wheel events
          else if((event.xany.type==ButtonPress) && (event.xbutton.button==Button4 || event.xbutton.button==Button5)){
            ticks=1;
            while(XPending((Display*)display)){
              XPeekEvent((Display*)display,&ev);
              if((ev.xany.type!=ButtonPress && ev.xany.type!=ButtonRelease) || (event.xany.window!=ev.xany.window) || (event.xbutton.button!=ev.xbutton.button)) break;
              ticks+=(ev.xany.type==ButtonPress);
              XNextEvent((Display*)display,&event);
              }
            event.xbutton.subwindow=(Window)ticks;   // Stick it here for later
            }

          // Compress configure events
          else if(event.xany.type==ConfigureNotify){
            while(XCheckTypedWindowEvent((Display*)display,event.xconfigure.window,ConfigureNotify,&ev)){
              event.xconfigure.width=ev.xconfigure.width;
              event.xconfigure.height=ev.xconfigure.height;
              if(ev.xconfigure.send_event){
                event.xconfigure.x=ev.xconfigure.x;
                event.xconfigure.y=ev.xconfigure.y;
                }
              }
            }

          // Event activity
          if(dispatchEvent(event)) return true;         // Event activity
          continue;
          }
        }

      // Check active handles
      if(0<numraised){
        mode=0;
        do{
          current=(current+1)%numwatched;
          if(FD_ISSET(current,&internals->watched[0])){
            FD_CLR(current,&internals->watched[0]);
            numraised--;
            mode|=InputRead;
            }
          if(FD_ISSET(current,&internals->watched[1])){
            FD_CLR(current,&internals->watched[1]);
            numraised--;
            mode|=InputWrite;
            }
          if(FD_ISSET(current,&internals->watched[2])){
            FD_CLR(current,&internals->watched[2]);
            numraised--;
            mode|=InputExcept;
            }
          }
        while(mode==0);

        // Display connection became active
        if(ConnectionNumber((Display*)display)==current) continue;

        // IO handle became active
        if(dispatchHandle(current,mode,flags)) return true;     // IO activity
        continue;
        }

      // Prepare handles to check
      internals->watched[0]=internals->handles[0];
      internals->watched[1]=internals->handles[1];
      internals->watched[2]=internals->handles[2];

      // Select active handles and check signals; don't block
#if (_POSIX_C_SOURCE >= 200112L)
      numraised=pselect(numhandles,&internals->watched[0],&internals->watched[1],&internals->watched[2],nullptr,nullptr);
#else
      numraised=select(numhandles,&internals->watched[0],&internals->watched[1],&internals->watched[2],nullptr);
#endif

      // No handles were active
      if(numraised==0){

        // Idle callback if we're about to block
        if(flags&DispatchIdle){
          if(dispatchIdle()) return true;               // Idle activity
          }

        // We're not blocking
        if(blocking<=0) return false;

        // Prepare handles to check
        internals->watched[0]=internals->handles[0];
        internals->watched[1]=internals->handles[1];
        internals->watched[2]=internals->handles[2];

        // Nanoseconds to wait
        interval=Math::imin(delay,blocking);
        if(interval<forever){
          interval=Math::imin(interval,maxwait);
          }

        // Select active handles and check signals, waiting for timeout or maximum block time
#if (_POSIX_C_SOURCE >= 200112L)
        delta.tv_sec=interval/seconds;
        delta.tv_nsec=(interval-seconds*delta.tv_sec);
        numraised=pselect(numhandles,&internals->watched[0],&internals->watched[1],&internals->watched[2],&delta,nullptr);
#else
        delta.tv_sec=interval/seconds;
        delta.tv_usec=(interval-seconds*delta.tv_sec)/microseconds;
        numraised=select(numhandles,&internals->watched[0],&internals->watched[1],&internals->watched[2],&delta);
#endif

        // Return if there was no timeout within maximum block time
        if(numraised==0){
          if(blocking<forever){                         // Next blocking period reduced by time already expired
            blocking-=interval;
            if(blocking<=0) return false;               // Nothing happened during blocking period!
            }
          continue;
          }
        }

      // Bad stuff happened
      if(numraised<0){
        if(errno!=EAGAIN && errno!=EINTR){ throw FXFatalException("FXReactor::dispatch: error waiting on handles."); }
        continue;
        }

      // Keep track of original set
      numwatched=numhandles;
      }
    }
  return false;
  }

#endif //////////////////////////////////////////////////////////////////////////


// Dispatch platform-dependent event
FXbool FXEventDispatcher::dispatchEvent(FXRawEvent& event){
  return true;
  }

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

// Exit dispatcher
FXbool FXEventDispatcher::exit(){
  if(FXDispatcher::exit()){
    display=nullptr;
    return true;
    }
  return false;
  }


// Destroy event dispatcher object
FXEventDispatcher::~FXEventDispatcher(){
  exit();
  }

}