summaryrefslogtreecommitdiff
path: root/src/Manager.cpp
blob: 4db53ef1d0b5d6958a8539c899086dc816172552 (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
/* $Id: Manager.cpp,v 1.26 2007/01/07 05:00:56 whot Exp $ */

/*--
 --*/

#include "Manager.h"
#include <cairo.h>
#include <cairo-xlib.h>

int MPWM_ErrorHandler(Display* dpy, XErrorEvent* ev)
{
    char *buffer = new char[1024];
    
    XGetErrorText(dpy, ev->error_code, buffer, 1024);
    DBG("%s, request: %d, id: %x\n", buffer, ev->request_code, 
            (unsigned int)ev->resourceid);
    delete buffer;

    return 0;
}


/**
 * Start up and initialize internal variables.
 */
Manager::Manager()
{
    x11 = NULL;
    stop = false;
    dock = NULL;
    time = 0;
}

/**
 * Clean up.
 */
Manager::~Manager()
{
    XCloseDisplay(x11->dpy);
}

/**
 * Connect to the X display, decorate all existing windows and set up MPGXlib.
 * @param display String with the name of the display.
 */
void Manager::init(char* display)
{
    initX11(display);

    dock = new Dock(x11);
    initXi();
    queryInitial();
}

/**
 * Connect to the X display and register as WM at the root window.
 * @param display The display to connect to (i.e. "host:0").
 */
void Manager::initX11(char* display)
{
    x11 = new XConn(display);

    Config::init(x11);

    XSetWindowAttributes attr;
    attr.background_pixmap = None;
    attr.background_pixel = x11->white;
    attr.event_mask = SubstructureRedirectMask | SubstructureNotifyMask |
        ColormapChangeMask | PropertyChangeMask | ExposureMask; 
    XChangeWindowAttributes(x11->dpy, x11->root, 
            CWBackPixmap | CWBackPixel | CWEventMask, &attr);

    XSync(x11->dpy, False);

    XGCValues vals;
    root_gc = XCreateGC(x11->dpy, x11->root, 0, &vals);

    if (!root_gc)
        ERR("Could not create canvas on root window\n");
    else
        XFillRectangle(x11->dpy, x11->root, root_gc, 0, 0, x11->width,
                x11->height);

    pxBackground = XCreatePixmap(x11->dpy, x11->root, 
                                 x11->width, x11->height, x11->depth);
    cairo_surface_t* cr_sf = cairo_xlib_surface_create(x11->dpy, pxBackground,
            x11->vis, x11->width, x11->height);
    cairo_t* cr = cairo_create(cr_sf);
    /*
        FIXME: For whatever reason this code stopped working. I don't have the time to
        debug it, so for now it's just a white background. Tough luck.

    TRACE("Create background from %s\n",Config::getInstance()->imgBackground);
    cairo_surface_t* cr_png_sf = cairo_image_surface_create_from_png(
                                      Config::getInstance()->imgBackground);
    int pngwidth, pngheight;
    pngwidth = cairo_image_surface_get_width(cr_png_sf);
    pngheight = cairo_image_surface_get_height(cr_png_sf);
    TRACE("Scaling image: %dx%d ---> %dx%d\n", pngwidth, pngheight, 
                                               x11->width, x11->height);
    cairo_scale(cr, (double)x11->width/pngwidth, (double)x11->height/pngheight);
    cairo_set_source_surface(cr, cr_png_sf, 0, 0);
    */
    cairo_set_source_rgb(cr, 1, 1, 1);
    cairo_paint(cr);
    cairo_surface_destroy(cr_sf);
    //cairo_surface_destroy(cr_png_sf);
    cairo_destroy(cr);

    XCopyArea(x11->dpy, pxBackground, x11->root, root_gc, 0, 0, x11->width,
            x11->height, 0, 0);
    XSetErrorHandler(MPWM_ErrorHandler);
}

/**
 * Set up the X Input Extension.
 */
void Manager::initXi()
{
    XDeviceInfo* devices;
    int devicecount;

    devices = XListInputDevices(x11->dpy, &devicecount);

    if (devicecount <= 0)
        throw new DeviceError(DeviceError::NO_DEVICES);

    while(devicecount)
    {
        XDeviceInfo* currDevice;

        currDevice = &devices[--devicecount];
        /* ignore slave devices, only masters are interesting */
        if ((currDevice->use == IsXPointer))
        {
            try
            {
                PointerDevice *p = new PointerDevice(currDevice, x11, this);
                pointers.push_back(p);

            } catch (DeviceError* e)
            {
                ERR("%s\n", e->message.c_str());
            }
        } else if ((currDevice->use == IsXKeyboard))
        {
            try
            {
                KeyboardDevice *k = new KeyboardDevice(currDevice, x11, this);
                keyboards.push_back(k);
                //dock->appendKeyboard(k);
            } catch (DeviceError* e)
            {
                ERR("%s\n", e->message.c_str());
            }
        }
    }

    dock->setPointerEvents(&pointers);
    XFreeDeviceList(devices);

    rescanPairings();

    XSelectExtensionEvent(x11->dpy, x11->root, &x11->presence_class, 1);
}

void Manager::rescanPairings()
{
    vector<KeyboardDevice*>::const_iterator it = keyboards.begin();
    XID ptr_id;
    while(it != keyboards.end())
    {
        if (XGetPairedPointer(x11->dpy, (*it)->getDevice(), &ptr_id))
        {
            (*it)->setPaired(idToPointerDevice(ptr_id));
        }
        it++;
    }

}

/**
 * Disconnect from X and bring down any allocated memory.
 */
void Manager::takedown()
{
    XCloseDisplay(x11->dpy);
}

/**
 * Add a new window.
 * 
 */
void Manager::addNewClient()
{

}

/**
 * Query the root window for the initial set of windows and create decorations
 * for all of them.
 */
void Manager::queryInitial()
{
   windows = queryWindows(); 
   vector<WMWindow*>::const_iterator it = windows.begin();

   while(it != windows.end())
   {
       (*it)->decorate();
       (*it)->extractPID();
       (*it)->manage();
       it++;
   }

   XSync(x11->dpy, False);
}
   
/**
 * Query the root window's top-level childs.
 */
vector<WMWindow*> Manager::queryWindows()
{
    Window rootWindow;
    Window parent;
    Window *children;
    Window *clientChildren;
    unsigned int childcount, clientchildcount;
    vector<WMWindow*> windowList;

    XQueryTree(x11->dpy, x11->root, &rootWindow, &parent, &children,
            &childcount);

    // for each window found we query whether the window is a WM window, just
    // to be sure. If the window isn't, it is a new client window.
    for (unsigned int i = 0; i < childcount; i++)
    {
        XQueryTree(x11->dpy, children[i], &rootWindow, &parent,
                &clientChildren, &clientchildcount);
        XFree(clientChildren);

        if (parent != x11->root || isWMWindow(children[i]))
        {
            continue;
        }

        WMWindow* win = new WMWindow(this, children[i], x11);
        windowList.push_back(win);
    }
    XFree(children);

    return windowList;
}

/**
 * @return true if the given window belongs to a WM window (that is,
 * container, decoration or other).
 */
bool Manager::isWMWindow(Window win)
{
    WMWindow* window = windowToWMWindow(win);
    if (window)
        return true;

    
    if (dock->hasWindow(win))
        return true;

    return false;
}

bool Manager::isWMDecoration(Window win)
{
    WMWindow* window = windowToWMWindow(win);
    if (window && !window->isClientWindow(win))
        return true;

    return false;
}

/**
 * @returns A pointer to the WMWindow this window belongs to.
 */
WMWindow* Manager::windowToWMWindow(Window w)
{
    // iterate through windows
    vector<WMWindow*>::reverse_iterator it = windows.rbegin();

    while(it != windows.rend())
    {
        if ((*it)->hasWindow(w))
            return *it;
        it++;
    }

    return NULL;
}


/**
 * Main loop. Waits for events and processes them accordingly.
 */
void Manager::loop()
{
    XEvent ev;

    while(!stop)
    {
        XNextEvent(x11->dpy, &ev);
        switch(ev.type)
        {
            /* WM events */
            case CreateNotify:
                handleCreateNotify(&ev.xcreatewindow);
                break;
            case MapRequest:
                handleMapRequest(&ev.xmap);
                break;
            case MapNotify:
                handleMapNotify(&ev.xmap);
                break;
            case ConfigureRequest:
                handleConfigureRequest(&ev.xconfigurerequest);
                break;
            case ReparentNotify:
                handleReparentNotify(&ev.xreparent);
                break;
            case DestroyNotify:
                handleDestroyNotify(&ev.xdestroywindow);
                break;
            case UnmapNotify:
                handleUnmapNotify(&ev.xunmap);
                break;
            case ConfigureNotify:
                break;
            case Expose:
                if (ev.xexpose.window == x11->root)
                    paintBackground(&(ev.xexpose));
                else
                {
                    WMWindow* client = windowToWMWindow(ev.xexpose.window);
                    if (client)
                        client->expose(&ev.xexpose);
                    else
                        dock->handleExpose(&ev.xexpose);
                }
                break;
            case PropertyNotify:
                handlePropertyNotify(&(ev.xproperty));
                break;
                /* XInput device events */
            default:
                handleOtherEvents(&ev);
                break;
        }
    }
}

/**
 * Handle create notify. A create notify causes the WM to allocate the
 * necessary structures for the window borders but does not reparent the
 * window yet. If we reparent, we would not get the MapRequest.
 */
void Manager::handleCreateNotify(XCreateWindowEvent* ev)
{
    TRACE("Create notify for window %x\n", (unsigned int)ev->window);

    if (isWMWindow(ev->window))
    {
        TRACE(" -- No action. WM window\n");
        return;
    }

    if (ev->parent != x11->root)
    {
        TRACE(" -- No action, parent is not root\n");
        return;
    }

    try {
        WMWindow* w = new WMWindow(this, ev->window, x11);
        w->decorate();
        windows.push_back(w);
    } catch (XError err)
    {
        ERR("%s\n", err.message.c_str());
    }
}

/**
 * A map request is issued by the client when it wants to map something to the
 * root window. We are a WM, so we get the request and instead of the client
 * mapping the window, we have to map it.
 */
void Manager::handleMapRequest(XMapEvent* ev)
{
    WMWindow* w = windowToWMWindow(ev->window);
    if (w == NULL)
    {
        DBG("w is null\n");
        return;
    }

    if (w->getState() == WithdrawnState)
    {
        w->manage();
        w->setState(NormalState);
        TRACE("Managing window %x\n", (unsigned int)ev->window);
    }

    w->mapAll();

    // In some cases we miss the PID. If we haven't got it yet, try to get it
    // now.
    w->extractPID();

    TRACE("Client %x mapped\n", (unsigned int)ev->window);
}

void Manager::handleMapNotify(XMapEvent* ev)
{
    TRACE("Map notify for %x\n", (unsigned int)ev->window);
    if (isWMWindow(ev->window))
    {
        TRACE(" - is WM window\n");
        return;
    }

    WMWindow* w = windowToWMWindow((unsigned int)ev->window);
    if (w == NULL)
    {
        TRACE(" - non client window\n");
        return;
    }

    TRACE(" - mapping all\n");
    w->mapAll(); 

    // In some cases we miss the PID. If we haven't got it yet, try to get it
    // now.
    w->extractPID();
}

void Manager::handleConfigureRequest(XConfigureRequestEvent* ev)
{
    TRACE("Configure for %x\n", (unsigned int)ev->window);

    WMWindow* w = windowToWMWindow(ev->window);

    if (w != NULL)
        w->reconfigure(ev);

}

void Manager::handleReparentNotify(XReparentEvent* ev)
{
    TRACE("ReparentNotify for client %x. Now on parent %x.\n", (unsigned int)ev->window, (unsigned int)ev->parent);

    XMapWindow(x11->dpy, ev->window);
    

    WMWindow* w = windowToWMWindow(ev->window);
    if (w == NULL)
    {
        TRACE(" - no client for window.");
        return;
    }

    if (w->getState() == IsViewable) 
        w->mapAll();
    XFlush(x11->dpy);
}

void Manager::handleDestroyNotify(XDestroyWindowEvent* ev)
{
    WMWindow* w = windowToWMWindow(ev->window);


    TRACE("Destroy notify for %x\n", (unsigned int)ev->window);

    if (w == NULL)
    {
        TRACE(" - not a client window\n");
        return;
    }

    if (w->isClientWindow(ev->window))
    {
        vector<WMWindow*>::iterator it = windows.begin();
        while(it != windows.end())
        {
            if ((*it) == w)
            {
                windows.erase(it);
                break;
            }
            it++;
        }
        delete w;
    }
}


/**
 * Unmaps the client window's container window if the client's window has
 * unmapped.
 * @param ev The Unmap event caused by the X server.
 */
void Manager::handleUnmapNotify(XUnmapEvent* ev)
{
    TRACE("Unmap notify for %x\n", (unsigned int)ev->window);
    if (isWMDecoration(ev->window))
    {
        TRACE("-- is WM decoration\n");
        return;
    }

    WMWindow* w = windowToWMWindow(ev->window);

    if (w == NULL)
    {
        TRACE("-- is unknown window\n");
        return;
    }

    if (!w->isResizing())
        XUnmapWindow(x11->dpy, w->container);
}


/**
 * Handles extension events and all other events.
 * Input extension events are not core events. Thus each input extension
 * event will pass through this function. However, other core events that are
 * not handled in the loop may also pass through here.
 * @param ev The event gathered in the X event loop.
 */

void Manager::handleOtherEvents(XEvent *ev)
{
    if (ev->type == PointerDevice::XI_MotionNotify)
    {
        handleMotionEvent((XDeviceMotionEvent*)ev);
    } else if (ev->type == PointerDevice::XI_ButtonPress)
    {
        handleButtonPress((XDeviceButtonEvent*)ev);
    } else if (ev->type == PointerDevice::XI_ButtonRelease)
    {
        handleButtonRelease((XDeviceButtonEvent*)ev);
    } else if (ev->type == EnterNotify || ev->type == LeaveNotify)
    {
        handleEnterLeaveNotify(&ev->xcrossing);
    } else if (ev->type == x11->XI_presence)
    {
        handlePresenceNotify((XDevicePresenceNotifyEvent*)ev);
    }
}

/**
 * Handles all Input Extension motion events. 
 */
void Manager::handleMotionEvent(XDeviceMotionEvent* mev)
{
    time = mev->time;

    PointerDevice* dev = idToPointerDevice(mev->deviceid);

    if (dev == NULL)
    {
        ERR("Device %d is null\n", (int)mev->deviceid);
        return;
    }

    // There may be a drag event.
    if (dev->isDragging())
        dev->dragTo(mev->x_root, mev->y_root);

    // Resizing is slow. We check if there are other events in the queue cos
    // if there are, we don't resize.
    if (dev->isResizing())
    {
        XDeviceMotionEvent ev;
        if (!XCheckTypedEvent(x11->dpy, 
                              PointerDevice::XI_MotionNotify,
                              (XEvent*) &ev))
        {
            if (mev->deviceid == ev.deviceid && mev->state == ev.state)
            {
                // skip
            } else 
            {
                XPutBackEvent(x11->dpy, (XEvent*)&ev);
                dev->resizeTo(mev->x_root, mev->y_root);
            }
        } else
            dev->resizeTo(mev->x_root, mev->y_root);
    }

    WMWindow* win = xyToWMWindow(mev->x_root, mev->y_root);

    if (win && win->hasOverlay())
        win->handleOverlayMotion(mev,
                idToPointerDevice(mev->deviceid));
       
}

/**
 * Handles all InputExtension button presses.
 */
void Manager::handleButtonPress(XDeviceButtonEvent* bev)
{
    time = bev->time;

    PointerDevice* dev = idToPointerDevice(bev->deviceid);

    if (dev == NULL)
    {
        ERR("Device %d is null\n", (int)bev->deviceid);
        return;
    }

    TRACE("DeviceButtonPress for device %s on %d/%d\n",
            dev->getName().c_str(), bev->x_root, bev->y_root);

    DockItem* di = dock->getDockItem(bev->window);
    if (di)
    {
        di->handleButtonEvent(dev, bev);
        return;
    }

    WMWindow* wmwindow = windowToWMWindow(bev->window);

    if (!wmwindow)
    {
        ERR(" - WMWindow not found for %x\n", (int)bev->window);
        return;
    }

    if (wmwindow->isResizeBar(bev->window) || 
            wmwindow->isWindowBar(bev->window) ||
            wmwindow->isClientWindow(bev->window))
    {
        XSetClientPointer(x11->dpy, wmwindow->getClientWindow(),
                dev->getDevice());
        vector<KeyboardDevice*>::const_iterator it = keyboards.begin();
        while(it != keyboards.end())
        {
            if ((*it)->getPaired() == dev)
                XSetDeviceFocus(x11->dpy, (*it)->getDevice(),
                        wmwindow->getClientWindow(), PointerRoot, CurrentTime);
            it++;
        }

        if (wmwindow->isClientWindow(bev->window))
        {
            XSetClientPointer(x11->dpy, wmwindow->getClientWindow(), 
                    dev->getDevice());
        }
        else
            raiseWindow(wmwindow);
    }

    if (wmwindow->isWindowBar(bev->window))
    {
        if (dev->dragOn(wmwindow, bev->x, bev->y))
            TRACE(" - Drag on for %x\n", (int)bev->window);
        wmwindow->changeOwnership(dev);
    }


    if (wmwindow->isResizeButton(bev->window))
    {
        if (dev->resizeOn(wmwindow, bev->window, bev->x_root, bev->y_root))
            TRACE(" - Resize on for %x\n", (int)bev->window);
    }

    if (wmwindow->isFloorControlWindow(bev->window))
    {
        wmwindow->floorControlButtonPress(bev, dev);
    }

    if (wmwindow->isButtonMinimize(bev->window))
    {
        wmwindow->setMinimize(true);
        dock->appendProcess(wmwindow);
        dock->setPointerEvents(&pointers);
    }
    XAllowDeviceEvents(x11->dpy, dev->getDevice(), 
                    ReplayThisDevice, CurrentTime);
    XAllowDeviceEvents(x11->dpy, dev->getDevice(), 
                    AsyncOtherDevices, CurrentTime);
}

void Manager::handleButtonRelease(XDeviceButtonEvent* bev)
{
    time = bev->time;

    PointerDevice* dev = idToPointerDevice(bev->deviceid);

    if (dev == NULL)
    {
        ERR("Device %d is null\n", (int)bev->deviceid);
        return;
    }

    TRACE("DeviceButtonRelease for device %s\n", dev->getName().c_str());
    TRACE("--- release has window %x\n", (int)bev->window);
    TRACE("--- release has subwindow %x\n", (int)bev->subwindow);


    if (dev->isResizing())
    {
        dev->resizeOff();
        TRACE(" - resize stopped\n");
        return;
    }

    // check for button clicks
    WMWindow* win = windowToWMWindow(bev->window);

    if (win == NULL)
    {
        ERR(" - WMWindow for %x not found\n", (int)bev->window);
        return;
    }

    if (win->isButtonClose(bev->window))
    {
        win->destroy();
        return;
    }

    // leftclick on button: lock window to pointer
    // rightclick on button: display floor control gui
    if (win->isButtonFloor(bev->window))
    {
        if (bev->button == Button3)
        {
            win->toggleFloorControl();
        } else
            if (win->isLocked())
                win->release(dev);
            else
            {
                if (win->restrictTo(dev))
                    TRACE("Window %x limited to device %s\n",
                            (int)win->getClientWindow(), dev->getName().c_str());
                else
                    ERR("Could not limit window\n");
            }
    }

    if (win->isButtonOverlay(bev->subwindow))
    {
        if (bev->device_state & Button1Mask)
            win->toggleOverlay(bev->deviceid);
        else if (bev->device_state & Button3Mask)
            win->clearOverlay(bev->deviceid);
    }

    if (dev->isDragging())
    {
        dev->dragOff();
        TRACE(" - dragging stopped\n");
        return;
    }
}

void Manager::handleEnterLeaveNotify(XCrossingEvent* ev)
{
    WMWindow* client =  windowToWMWindow(ev->window);
    if (client)
        client->handleEnterLeaveNotify(ev);
}

void Manager::handlePresenceNotify(XDevicePresenceNotifyEvent* ev)
{
    TRACE("Device presence event\n");
    /* whoohey, the events don't have any useful data. query the device list
     * again and see if we spot something new. 
     */
    XDeviceInfo* devices;
    int ndevices;
    devices = XListInputDevices(x11->dpy, &ndevices);
    while(ndevices)
    {
        XDeviceInfo* current;
        current = &devices[--ndevices];
        if (!idToPointerDevice(current->id))
        {
            TRACE("New device '%s' id %d\n", current->name, (int)current->id);
            if (current->use == IsXPointer)
            {
                try {
                    PointerDevice *p = new PointerDevice(current, x11,
                            this); 
                    pointers.push_back(p);
                    // add new events to all windows.
                    vector<WMWindow*>::const_iterator it = windows.begin();
                    while(it != windows.end())
                    {
                        p->setWMEvents(*it);
                        it++;
                    }

                    dock->setPointerEvents(&pointers);



                } catch (DeviceError* e)
                {
                    ERR("%s\n", e->message.c_str());
                }
            }
        }

        if (!idToKeyboardDevice(current->id))
        {
            if (current->use == IsXKeyboard)
            {
                try
                {
                    KeyboardDevice *k = new KeyboardDevice(current, x11, this);
                    keyboards.push_back(k);
                    //dock->appendKeyboard(k);
                    dock->setPointerEvents(&pointers);
                    rescanPairings();
                } catch (DeviceError* e)
                {
                    ERR("%s\n", e->message.c_str());
                }
            }

        }
    }

    XFreeDeviceList(devices);
}


/**
 * @return the PointerDevice that has the given ID.
 */
PointerDevice* Manager::idToPointerDevice(int id)
{
    vector<PointerDevice*>::const_iterator it = pointers.begin();

    while(it != pointers.end())
    {
        if ((*it)->getID() == id)
            return *it;
        it++;
    }
    return NULL;
}

KeyboardDevice* Manager::idToKeyboardDevice(int id)
{
    vector<KeyboardDevice*>::const_iterator it = keyboards.begin();
    while(it != keyboards.end())
    {
        if ((*it)->getID() == id)
            return *it;
        it++;
    }
    return NULL;
}


/**
 * @return The list of pointers registered at the manager.
 */
vector<PointerDevice*>* Manager::getPointers()
{
    return &pointers;
}


bool Manager::hasShapeExtension()
{
    static bool queried = false;
    static bool hasShape = false;

    if (!queried)
    {
        int eventop, errorop;
        hasShape = XShapeQueryExtension(x11->dpy, &eventop, &errorop);
        if (!hasShape)
            ERR("No shape extension. Will not use pretty cursors.\n");

        queried = true;
    }

    return hasShape;
}

/**
 * Changes the root window color to white.
 */
void Manager::paintBackground(XExposeEvent* ev)
{
    XCopyArea(x11->dpy, pxBackground, x11->root, root_gc, ev->x, ev->y, 
            ev->width, ev->height, ev->x, ev->y);
}

void Manager::handlePropertyNotify(XPropertyEvent* ev)
{
    WMWindow* win = windowToWMWindow(ev->window);
    if (win == NULL)
        return;

    if (win->isClientWindow(ev->window))
        win->extractPID();

}

/**
 * Returns the wm-window on the given coordinates or NULL if there is none.
 * FIXME: this will not work well when there's more than two windows on the
 * same spot. We need to integrate stacking order here.
 */
WMWindow* Manager::xyToWMWindow(int x, int y)
{
    vector<WMWindow*>::reverse_iterator it = windows.rbegin();
    while(it != windows.rend())
    {
        WMWindow* current = *it;
        if (current->onPosition(x, y))
            return current;
        it++;
    }
    return NULL;
}

/**
 * Sets the ButtonPress mask for all devices.
 */
void Manager::setButtonPressMask(Window win)
{
    vector<PointerDevice*>::iterator it = pointers.begin();

    while(it != pointers.end())
    {
        (*it)->setButtonPressEventMask(win);
        it++;
    }
}

void Manager::raiseWindow(WMWindow* wmwindow)
{
    vector<WMWindow*>::reverse_iterator it = windows.rbegin();

    while(it != windows.rend())
    {
        if (*it == wmwindow)
        {
            // why ++it see http://www.ddj.com/dept/cpp/184401406
            windows.erase((++it).base());
            windows.push_back(wmwindow);
            break;
        }
        it++;
    }

    wmwindow->raise();
}