~vanvugt/compiz/fix-1009320

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
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
/*
 * Copyright © 2008 Dennis Kasprzyk
 * Copyright © 2007 Novell, Inc.
 *
 * 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, and that the name of
 * Dennis Kasprzyk not be used in advertising or publicity pertaining to
 * distribution of the software without specific, written prior permission.
 * Dennis Kasprzyk makes no representations about the suitability of this
 * software for any purpose. It is provided "as is" without express or
 * implied warranty.
 *
 * DENNIS KASPRZYK DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN
 * NO EVENT SHALL DENNIS KASPRZYK 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.
 *
 * Authors: Dennis Kasprzyk <onestone@compiz-fusion.org>
 *          David Reveman <davidr@novell.com>
 */

#ifndef _PRIVATESCREEN_H
#define _PRIVATESCREEN_H

#include <core/screen.h>
#include <core/size.h>
#include <core/point.h>
#include <core/timer.h>
#include <core/plugin.h>
#include <core/servergrab.h>
#include <time.h>
#include <boost/shared_ptr.hpp>

#include <glibmm/main.h>

#include "privatetimeoutsource.h"
#include "privateiosource.h"
#include "privateeventsource.h"
#include "privatesignalsource.h"

#include "core_options.h"

#include <set>

namespace compiz { namespace private_screen
{

class OutputDevices
{
public:
    OutputDevices();

    void setCurrentOutput(unsigned int outputNum);

    CompOutput& getCurrentOutputDev() { return outputDevs[currentOutputDev]; }

    bool hasOverlappingOutputs() const { return overlappingOutputs; }

    void computeWorkAreas(CompRect& workArea, bool& workAreaChanged,
	    CompRegion& allWorkArea, const CompWindowList& windows);

    const CompOutput& getOutputDev(unsigned int outputNum) const
    { return outputDevs[outputNum]; }

    // TODO breaks encapsulation horribly ought to be const at least
    // Even better, use begin() and end() return const_iterators
    // BUT this is exported directly through API - which makes changing
    // it a PITA.
    CompOutput::vector& getOutputDevs() { return outputDevs; }

    int outputDeviceForGeometry(const CompWindow::Geometry& gm, int strategy,
	    CompScreen* screen) const;
    void updateOutputDevices(CoreOptions& coreOptions, CompScreen* screen);

private:
    void setGeometryOnDevice(unsigned int nOutput, int x, int y,
	    const int width, const int height);
    void adoptDevices(unsigned int nOutput);

    static CompRect computeWorkareaForBox(const CompRect& box,
	    const CompWindowList& windows);

    CompOutput::vector outputDevs;
    bool               overlappingOutputs;
    int	           currentOutputDev;
};

}} //::compiz::private_screen

CompPlugin::VTable * getCoreVTable ();

class CoreWindow;

extern bool shutDown;
extern bool restartSignal;

extern bool	  useDesktopHints;

extern std::list <CompString> initialPlugins;


typedef struct _CompDelayedEdgeSettings
{
    CompAction::CallBack initiate;
    CompAction::CallBack terminate;

    unsigned int edge;
    unsigned int state;

    CompOption::Vector options;
} CompDelayedEdgeSettings;


struct CompScreenEdge {
    Window	 id;
    unsigned int count;
};

struct CompGroup {
    unsigned int      refCnt;
    Window	      id;
};

struct CompStartupSequence {
    SnStartupSequence		*sequence;
    unsigned int		viewportX;
    unsigned int		viewportY;
};

namespace compiz
{
namespace core
{
namespace screen
{
    inline int wraparound_mod (int a, int b)
    {
	if (a < 0)
	    return (b - ((-a - 1) % (b))) - 1;
	else
	    return a % b;
    };
}
}
}

namespace compiz
{
namespace private_screen
{
class History;

class WindowManager : boost::noncopyable
{
    public:

	typedef CompWindow::ForEach Functor;

	WindowManager();

	CompGroup * addGroup (Window id);
	void removeGroup (CompGroup *group);
	CompGroup * findGroup (Window id);

	void eraseWindowFromMap (Window id);
	void removeDestroyed ();

	void updateClientList (PrivateScreen& ps);

	void addToDestroyedWindows(CompWindow * cw)
	    { destroyedWindows.push_back (cw); }

	void incrementPendingDestroys() { pendingDestroys++; }
	const CompWindowVector& getClientList () const
	    { return clientList; }
	const CompWindowVector& getClientListStacking () const
	    { return clientListStacking; }

	CompWindow * findWindow (Window id) const;
	Window getTopWindow() const;


	void removeFromFindWindowCache(CompWindow* w)
	{
	    if (w == lastFoundWindow)
		lastFoundWindow = 0;
	}

	void addWindowToMap(CompWindow* w)
	{
	    if (w->id () != 1)
		windowsMap[w->id ()] = w;
	}

	void validateServerWindows();

	void invalidateServerWindows();

	void insertWindow (CompWindow* w, Window aboveId);
	void unhookWindow (CompWindow *w);
	CompWindowList& getWindows()	{ return windows; }

	CompWindowList& getDestroyedWindows()	{ return destroyedWindows; }

	void insertServerWindow(CompWindow* w, Window aboveId);
	void unhookServerWindow(CompWindow *w);
	CompWindowList& getServerWindows()	{ return serverWindows; }

	typedef CompWindowList::const_iterator iterator;
	typedef CompWindowList::const_reverse_iterator reverse_iterator;

	iterator begin() const { return windows.begin(); }
	iterator end() const { return windows.end(); }
	reverse_iterator rbegin() const { return windows.rbegin(); }
	reverse_iterator rend() const { return windows.rend(); }

	void clearFullscreenHints() const;
	void showOrHideForDesktop(unsigned int desktop) const;
	void setWindowActiveness(::compiz::private_screen::History& history) const;
	void setNumberOfDesktops (unsigned int nDesktop) const;
	void updateWindowSizes() const;

	void forEachWindow(Functor const& f) const
	{
	    std::for_each(windows.begin(), windows.end(), f);
	}

    private:
	CompWindowList windows;
	CompWindowList serverWindows;
	CompWindowList destroyedWindows;
	bool           stackIsFresh;

	CompWindow::Map windowsMap;
	std::list<CompGroup *> groups;

	CompWindowVector clientList;            /* clients in mapping order */
	CompWindowVector clientListStacking;    /* clients in stacking order */

	std::vector<Window> clientIdList;        /* client ids in mapping order */
	std::vector<Window> clientIdListStacking;/* client ids in stacking order */

	unsigned int pendingDestroys;

	mutable CompWindow* lastFoundWindow;
};

unsigned int windowStateFromString (const char *str);

class PluginManager
{
    public:
	PluginManager();

	void updatePlugins (CompScreen* screen, CompOption::Value::Vector const& extraPluginsRequested);

	void setPlugins(CompOption::Value::Vector const& vList)
	{
	    plugin.set (CompOption::TypeString, vList);
	}

	bool isDirtyPluginList () const { return dirtyPluginList; }
	void setDirtyPluginList () { dirtyPluginList = true; }

	CompOption::Value::Vector mergedPluginList(CompOption::Value::Vector const& extraPluginsRequested) const;

    private:
	CompOption::Value plugin;
	bool	          dirtyPluginList;
	typedef std::set<CompString> CompStringSet;
	CompStringSet blacklist;
};

class GrabList
{
    // TODO: std::list<Grab *> is almost certainly the wrong data
    // structure. Probably better as std::vector<Grab> - many fewer
    // memory allocations and releases.
    typedef std::list<Grab *> GrabPtrList;

public:
    typedef GrabPtrList::iterator GrabIterator;

    bool grabsEmpty() const { return grabs.empty(); }
    void grabsPush(Grab* grab) { grabs.push_back (grab); }
    GrabIterator grabsBegin() { return grabs.begin(); }
    GrabIterator grabsEnd() { return grabs.end(); }
    void grabsRemove(Grab* grab);
    bool grabExist (const char *grab);
    Grab* grabsBack() { return grabs.back (); }

private:
    GrabPtrList grabs;
};

class EventManager :
    public GrabList
{
    public:
	EventManager ();
	~EventManager ();

	void init ();

	void handleSignal (int signum);
	bool triggerPress   (CompAction         *action,
			     CompAction::State   state,
			     CompOption::Vector &arguments);
	bool triggerRelease (CompAction         *action,
	                     CompAction::State   state,
	                     CompOption::Vector &arguments);

	void startEventLoop(Display* dpy);
	void quit() { mainloop->quit(); }

	CompWatchFdHandle addWatchFd (
	    int             fd,
	    short int       events,
	    FdWatchCallBack callBack);

	void removeWatchFd (CompWatchFdHandle handle);

	CompFileWatch* addFileWatch (
	    const char        *path,
	    int               mask,
	    FileWatchCallBack callBack);

	CompFileWatch* removeFileWatch (CompFileWatchHandle handle);

	const CompFileWatchList& getFileWatches () const;

	void grabNotified() { grabbed = true; }
	void ungrabNotified() { grabbed = false; }
	bool isGrabbed() const { return grabbed; }

	void setSupportingWmCheck (Display* dpy, Window root);
	bool notGrabWindow(Window w) const { return w != grabWindow; }
	void createGrabWindow (Display* dpy, Window root, XSetWindowAttributes* attrib);
	void destroyGrabWindow (Display* dpy) { XDestroyWindow (dpy, grabWindow); }
	Time getCurrentTime (Display* dpy) const;
	Window const& getGrabWindow() const { return grabWindow; }
	void resetPossibleTap() { possibleTap = 0; }

    private:
        void *possibleTap;

	Glib::RefPtr <Glib::MainLoop>  mainloop;

	/* We cannot use RefPtrs. See
	 * https://bugzilla.gnome.org/show_bug.cgi?id=561885
	 */
	CompEventSource * source;
	CompTimeoutSource * timeout;
	CompSignalSource * sighupSource;
	CompSignalSource * sigtermSource;
	CompSignalSource * sigintSource;
	Glib::RefPtr <Glib::MainContext> ctx;

	CompFileWatchList   fileWatch;
	CompFileWatchHandle lastFileWatchHandle;

	// TODO - almost certainly the wrong data structure
	// Why not a std::map<CompWatchFdHandle, CompWatchFd>?
	std::list< CompWatchFd * > watchFds;
	CompWatchFdHandle        lastWatchFdHandle;

        bool	grabbed;   /* true once we receive a GrabNotify
			      on FocusOut and false on
			      UngrabNotify from FocusIn */
	Window  grabWindow;
};

class KeyGrab {
    public:
	int          keycode;
	unsigned int modifiers;
	int          count;
};

class ButtonGrab {
    public:
	int          button;
	unsigned int modifiers;
	int          count;
};

struct Grab {
	Grab(Cursor cursor, const char *name) : cursor(cursor), name(name) {}
	Cursor     cursor;
	const char *name;
};

// data members that don't belong (these probably belong
// in CompScreenImpl as PrivateScreen doesn't use them)
struct OrphanData : boost::noncopyable
{
    OrphanData();
    ~OrphanData();

    Window activeWindow;
    Window nextActiveWindow;
};

class GrabManager : boost::noncopyable
{
public:
    GrabManager(CompScreen *screen);

    bool addPassiveKeyGrab (CompAction::KeyBinding &key);
    void removePassiveKeyGrab (CompAction::KeyBinding &key);
    bool addPassiveButtonGrab (CompAction::ButtonBinding &button);
    void removePassiveButtonGrab (CompAction::ButtonBinding &button);

    void grabUngrabOneKey (unsigned int modifiers,
			   int          keycode,
			   bool         grab);
    bool grabUngrabKeys (unsigned int modifiers,
			 int          keycode,
			 bool         grab);
    void updatePassiveKeyGrabs ();
    void updatePassiveButtonGrabs(Window serverFrame);

private:
    CompScreen  * const screen;
    std::list<ButtonGrab> buttonGrabs;
    std::list<KeyGrab>    keyGrabs;
};

class History : public virtual ::compiz::History,
    boost::noncopyable
{
    public:
	History();

	void setCurrentActiveWindowHistory (int x, int y);

	void addToCurrentActiveWindowHistory (Window id);

	CompActiveWindowHistory* currentHistory ();

	unsigned int nextActiveNum () { return activeNum_++; }
	unsigned int activeNum () const;

    private:
	CompActiveWindowHistory history[ACTIVE_WINDOW_HISTORY_NUM];
	int                     currentHistory_;
	unsigned int activeNum_;
};

class ViewportRetrievalInterface
{
    public:

	virtual ~ViewportRetrievalInterface () {}

	virtual const CompPoint & getCurrentViewport () const = 0;
	virtual const CompSize & viewportDimentions () const = 0;
};

// Apart from a use by StartupSequence::addSequence this data
// is only used by CompScreenImpl - like the OrphanData struct
struct ViewPort :
    public ViewportRetrievalInterface
{
    public:

	ViewPort();
	CompPoint    vp;
	CompSize     vpSize;

    private:

	const CompPoint & getCurrentViewport () const { return vp; }
	const CompSize & viewportDimentions () const { return vpSize; }
};

namespace viewports
{
    void viewportForGeometry (const CompWindow::Geometry &gm,
			      CompPoint                   &viewport,
			      ViewportRetrievalInterface *viewports,
			      const CompSize &screenSize);
}

class StartupSequence : boost::noncopyable
{
    public:
	StartupSequence();
	void addSequence (SnStartupSequence *sequence, CompPoint const& vp);
	void removeSequence (SnStartupSequence *sequence);
	void removeAllSequences ();
	void applyStartupProperties (CompScreen* screen, CompWindow *window);
	bool handleStartupSequenceTimeout ();
	virtual void updateStartupFeedback () = 0;
	bool emptySequence() const { return startupSequences.empty(); }
    private:
	std::list<CompStartupSequence *> startupSequences;
	CompTimer                        startupSequenceTimer;
};

// Implemented as a separate class to break dependency on PrivateScreen & XWindows
class StartupSequenceImpl : public StartupSequence
{
    public:
	StartupSequenceImpl(PrivateScreen* priv) : priv(priv) {}

	virtual void updateStartupFeedback ();
    private:
	PrivateScreen* const priv;
};

class Extension
{
public:
    Extension() : is_enabled(), extension() {}

    template<Bool ExtensionQuery (Display*, int*, int*)>
    bool init(Display * dpy)
    {
	int error;
	is_enabled = ExtensionQuery(dpy, &extension, &error);
	return is_enabled;
    }

    template<Bool ExtensionQuery(Display*, int*, int*, int*, int*, int*)>
    bool init(Display * dpy)
    {
	int opcode;
	int error;
	is_enabled = ExtensionQuery(dpy, &opcode, &extension, &error, NULL, NULL);

	if (!is_enabled) extension = -1;

	return is_enabled;
    }

    int isEnabled () const { return is_enabled; }
    int get () const { return extension; }

private:
    bool is_enabled;
    int extension;
};

class Ping :
public virtual ::compiz::Ping
{
public:
    Ping() : lastPing_(1) {}
    bool handlePingTimeout (WindowManager::iterator begin, WindowManager::iterator end, Display* dpy);
    unsigned int lastPing () const { return lastPing_; }

private:
    unsigned int lastPing_;
};

class DesktopWindowCount :
    public virtual ::compiz::DesktopWindowCount
{
public:
    DesktopWindowCount();
    virtual void incrementDesktopWindowCount();
    virtual void decrementDesktopWindowCount();
    virtual int desktopWindowCount();
private:
    int       count;
};

class MapNum :
    public virtual ::compiz::MapNum
{
public:
    MapNum();
    virtual unsigned int nextMapNum();

private:
    unsigned int mapNum;
};

class XWindowInfo :
    public virtual ::compiz::XWindowInfo
{
public:
    XWindowInfo(Display* const& dpy) :
	dpy(dpy) {}

    virtual int getWmState (Window id);
    virtual void setWmState (int state, Window id) const;
    virtual void getMwmHints (Window id,
		      unsigned int *func,
		      unsigned int *decor) const;
    virtual unsigned int getProtocols (Window id);
    virtual unsigned int getWindowType (Window id);
    virtual unsigned int getWindowState (Window id);
private:
    Display* const& dpy;
};




unsigned int windowStateMask (Atom state);

}} // namespace compiz::private_screen

class FetchXEventInterface
{
    public:

	virtual ~FetchXEventInterface () {}

	virtual bool getNextXEvent (XEvent &) = 0;
};

class FetchEventInterface
{
    public:

	virtual ~FetchEventInterface () {}
	virtual bool getNextEvent (XEvent &) = 0;
};

class PrivateScreen :
    public CoreOptions,
    public FetchXEventInterface,
    public FetchEventInterface
{

    public:
	PrivateScreen (CompScreen *screen, compiz::private_screen::WindowManager& windowManager);
	~PrivateScreen ();

	bool initDisplay (
		const char *name,
		compiz::private_screen::History& history,
		unsigned int showingDesktopMask);

	bool setOption (const CompString &name, CompOption::Value &value);

	bool getNextEvent (XEvent &);
	bool getNextXEvent (XEvent &);
	void processEvents ();

	bool triggerButtonPressBindings (CompOption::Vector &options,
					 XButtonEvent       *event,
					 CompOption::Vector &arguments);

	bool triggerButtonReleaseBindings (CompOption::Vector &options,
					   XButtonEvent       *event,
					   CompOption::Vector &arguments);

	bool triggerKeyPressBindings (CompOption::Vector &options,
				      XKeyEvent          *event,
				      CompOption::Vector &arguments);

	bool triggerKeyReleaseBindings (CompOption::Vector &options,
					XKeyEvent          *event,
					CompOption::Vector &arguments);

	bool triggerStateNotifyBindings (CompOption::Vector  &options,
					 XkbStateNotifyEvent *event,
					 CompOption::Vector  &arguments);

	bool triggerEdgeEnter (unsigned int       edge,
			       CompAction::State  state,
			       CompOption::Vector &arguments);

	void setAudibleBell (bool audible);

	bool handleActionEvent (XEvent *event);

	void handleSelectionRequest (XEvent *event);

	void handleSelectionClear (XEvent *event);

	bool desktopHintEqual (unsigned long *data,
			       int           size,
			       int           offset,
			       int           hintSize);

	void setDesktopHints ();

	void setVirtualScreenSize (int hsize, int vsize);

	void updateScreenEdges ();

	void reshape (int w, int h);

	void getDesktopHints (unsigned int showingDesktopMask);

	void updateScreenInfo ();

	Window getActiveWindow (Window root);

	void setWindowState (unsigned int state, Window id);

	bool readWindowProp32 (Window         id,
			       Atom           property,
			       unsigned short *returnValue);

	void configure (XConfigureEvent *ce);

	void setNumberOfDesktops (unsigned int nDesktop);

	void setCurrentDesktop (unsigned int desktop);

	void enableEdge (int edge);

	void disableEdge (int edge);

	void setDefaultWindowAttributes (XWindowAttributes *);

	static void compScreenSnEvent (SnMonitorEvent *event,
			   void           *userData);

	int  getXkbEvent() const { return xkbEvent.get(); }
	std::vector<XineramaScreenInfo>& getScreenInfo () { return screenInfo; }
	SnDisplay* getSnDisplay () const { return snDisplay; }
	const char* displayString() const
    {
	return displayString_;
    }

    const CompRegion& getRegion() const
    {
	return region;
    }

    const XWindowAttributes& getAttrib() const
    {
	return attrib;
    }

    Window rootWindow() const
    {
	return root;
    }

    void identifyEdgeWindow(Window id);
    void setPlugins(const CompOption::Value::Vector& vList);
    void initPlugins();

    void updateClientList()
    {
	windowManager.updateClientList(*this);
    }

    void detectOutputDevices(CoreOptions& coreOptions);
    void updateOutputDevices(CoreOptions& coreOptions);

    void setPingTimerCallback(CompTimer::CallBack const& callback)
    { pingTimer.setCallback(callback); }

public:
    Display* dpy;
    compiz::private_screen::Extension xSync;
    compiz::private_screen::Extension xRandr;
    compiz::private_screen::Extension xShape;
    compiz::private_screen::ViewPort viewPort;
    compiz::private_screen::StartupSequenceImpl startupSequence;
    compiz::private_screen::EventManager eventManager;
    compiz::private_screen::OrphanData orphanData;
    compiz::private_screen::OutputDevices outputDevices;

    Colormap colormap;
    int screenNum;
    unsigned int nDesktop;
    unsigned int currentDesktop;

    CompOutput fullscreenOutput;
    CompScreenEdge screenEdge[SCREEN_EDGE_NUM];

    Window wmSnSelectionWindow;

    Cursor normalCursor;
    Cursor busyCursor;
    Cursor invisibleCursor;
    CompRect workArea;

    bool initialized;

private:
    CompScreen* screen;
    compiz::private_screen::Extension xkbEvent;

    //TODO? Pull these two out as a class?
    bool xineramaExtension;
    std::vector<XineramaScreenInfo> screenInfo;

    SnDisplay* snDisplay;
    char displayString_[256];
    KeyCode escapeKeyCode;
    KeyCode returnKeyCode;

    CompRegion region;
    Window root;
    XWindowAttributes attrib;

    SnMonitorContext* snContext;

    Atom wmSnAtom;
    Time wmSnTimestamp;

    unsigned long *desktopHintData;
    int desktopHintSize;

    Window edgeWindow;
    CompTimer pingTimer;
    CompTimer edgeDelayTimer;
    CompDelayedEdgeSettings edgeDelaySettings;
    Window xdndWindow;
    compiz::private_screen::PluginManager pluginManager;
    compiz::private_screen::WindowManager& windowManager;
};

class CompManager
{
    public:

	CompManager ();

	bool init ();
	void run ();
	void fini ();

	bool parseArguments (int, char **);
	void usage ();

	static bool initPlugin (CompPlugin *p);
	static void finiPlugin (CompPlugin *p);

    private:

	bool		       disableSm;
	char		       *clientId;
	char		       *displayName;
};

/**
 * A wrapping of the X display screen. This takes care of communication to the
 * X server.
 */
class CompScreenImpl : public CompScreen,
    public ServerGrabInterface,
    ::compiz::private_screen::DesktopWindowCount,
    ::compiz::private_screen::MapNum,
    ::compiz::private_screen::Ping,
    ::compiz::private_screen::XWindowInfo,
    ::compiz::private_screen::History
{
    public:
	CompScreenImpl ();
	~CompScreenImpl ();

	bool init (const char *name);

	void eventLoop ();

	CompFileWatchHandle addFileWatch (const char        *path,
					  int               mask,
					  FileWatchCallBack callBack);

	void removeFileWatch (CompFileWatchHandle handle);

	const CompFileWatchList& getFileWatches () const;

	CompWatchFdHandle addWatchFd (int             fd,
				      short int       events,
				      FdWatchCallBack callBack);

	void removeWatchFd (CompWatchFdHandle handle);

	void storeValue (CompString key, CompPrivate value);
	bool hasValue (CompString key);
	CompPrivate getValue (CompString key);
	void eraseValue (CompString key);

	Display * dpy ();

	CompOption::Vector & getOptions ();

	bool setOption (const CompString &name, CompOption::Value &value);

	bool XRandr ();

	int randrEvent ();

	bool XShape ();

	int shapeEvent ();

	int syncEvent ();

	SnDisplay * snDisplay ();

	Window activeWindow ();

	Window autoRaiseWindow ();

	const char * displayString ();


	CompWindow * findWindow (Window id);

	CompWindow * findTopLevelWindow (Window id,
					 bool   override_redirect = false);

	bool readImageFromFile (CompString &name,
				CompString &pname,
				CompSize   &size,
				void       *&data);

	bool writeImageToFile (CompString &path,
			       const char *format,
			       CompSize   &size,
			       void       *data);

	unsigned int getWindowProp (Window       id,
				    Atom         property,
				    unsigned int defaultValue);


	void setWindowProp (Window       id,
			    Atom         property,
			    unsigned int value);


	unsigned short getWindowProp32 (Window         id,
					Atom           property,
					unsigned short defaultValue);


	void setWindowProp32 (Window         id,
			      Atom           property,
			      unsigned short value);

	Window root ();

	int xkbEvent ();

	XWindowAttributes attrib ();

	int screenNum ();

	CompWindowList & windows ();
	CompWindowList & serverWindows ();
	CompWindowList & destroyedWindows ();

	void warpPointer (int dx, int dy);

	Time getCurrentTime ();

	Window selectionWindow ();

	void forEachWindow (CompWindow::ForEach);

	void focusDefaultWindow ();

	void insertWindow (CompWindow *w, Window aboveId);
	void unhookWindow (CompWindow *w);

	void insertServerWindow (CompWindow *w, Window aboveId);
	void unhookServerWindow (CompWindow *w);

	Cursor normalCursor ();

	Cursor invisibleCursor ();

	/* Adds an X Pointer and Keyboard grab to the stack. Since
	 * compiz as a client only need to grab once, multiple clients
	 * can call this and all get events, but the pointer will
	 * be grabbed once and the actual grab refcounted */
	GrabHandle pushGrab (Cursor cursor, const char *name);

	/* Allows you to change the pointer of your grab */
	void updateGrab (GrabHandle handle, Cursor cursor);

	/* Removes your grab from the stack. Once the internal refcount
	 * reaches zero, the X Pointer and Keyboard are both ungrabbed
	 */
	void removeGrab (GrabHandle handle, CompPoint *restorePointer);

	/* Returns true if a grab other than the grabs specified here
	 * exists */
	bool otherGrabExist (const char *, ...);

	/* Returns true if the specified grab exists */
	bool grabExist (const char *);

	/* Returns true if the X Pointer and / or Keyboard is grabbed
	 * by anything (another application, pluigins etc) */
	bool grabbed ();

	const CompWindowVector & clientList (bool stackingOrder);

	bool addAction (CompAction *action);

	void removeAction (CompAction *action);

	void updateWorkarea ();

	void toolkitAction (Atom   toolkitAction,
			    Time   eventTime,
			    Window window,
			    long   data0,
			    long   data1,
			    long   data2);

	void runCommand (CompString command);

	void moveViewport (int tx, int ty, bool sync);

	void sendWindowActivationRequest (Window id);

	int outputDeviceForPoint (int x, int y);
	int outputDeviceForPoint (const CompPoint &point);

	CompRect getCurrentOutputExtents ();

	const CompRect & getWorkareaForOutput (unsigned int outputNum) const;

	void viewportForGeometry (const CompWindow::Geometry &gm,
				  CompPoint                   &viewport);

	int outputDeviceForGeometry (const CompWindow::Geometry& gm);

	const CompPoint & vp () const;

	const CompSize  & vpSize () const;

	CompOutput::vector & outputDevs ();
	CompOutput & currentOutputDev () const;

	const CompRect & workArea () const;

	unsigned int currentDesktop ();

	unsigned int nDesktop ();

	bool shouldSerializePlugins () ;

	const CompRegion & region () const;

	bool hasOverlappingOutputs ();

	CompOutput & fullscreenOutput ();

	std::vector<XineramaScreenInfo> & screenInfo ();

	CompIcon *defaultIcon () const;

	bool updateDefaultIcon ();

	void updateSupportedWmHints ();

	unsigned int showingDesktopMask() const;
	virtual bool grabsEmpty() const;
	virtual void sizePluginClasses(unsigned int size);
	virtual void setWindowState (unsigned int state, Window id);
	virtual void addToDestroyedWindows(CompWindow * cw);
	virtual void processEvents ();
	virtual void alwaysHandleEvent (XEvent *event);

	virtual ServerGrabInterface * serverGrabInterface ();

	virtual void updatePassiveKeyGrabs () const;
	virtual void updatePassiveButtonGrabs(Window serverFrame);

	virtual bool displayInitialised() const;
	virtual void applyStartupProperties (CompWindow *window);
	virtual void updateClientList();
	virtual Window getTopWindow() const;
	virtual CoreOptions& getCoreOptions();
	virtual Colormap colormap() const;
	virtual void setCurrentDesktop (unsigned int desktop);
	virtual Window activeWindow() const;
	virtual bool grabWindowIsNot(Window w) const;
	virtual void incrementPendingDestroys();
	virtual void setNextActiveWindow(Window id);
	virtual Window getNextActiveWindow() const;
	virtual CompWindow * focusTopMostWindow ();

    public :

	static bool showDesktop (CompAction         *action,
				 CompAction::State  state,
				 CompOption::Vector &options);

	static bool windowMenu (CompAction         *action,
				CompAction::State  state,
				CompOption::Vector &options);

	static bool closeWin (CompAction         *action,
			      CompAction::State  state,
			      CompOption::Vector &options);

	static bool unmaximizeWin (CompAction         *action,
				   CompAction::State  state,
				   CompOption::Vector &options);

	static bool minimizeWin (CompAction         *action,
				 CompAction::State  state,
				 CompOption::Vector &options);

	static bool maximizeWin (CompAction         *action,
				 CompAction::State  state,
				 CompOption::Vector &options);

	static bool maximizeWinHorizontally (CompAction         *action,
					     CompAction::State  state,
					     CompOption::Vector &options);

	static bool maximizeWinVertically (CompAction         *action,
					   CompAction::State  state,
					   CompOption::Vector &options);

	static bool raiseWin (CompAction         *action,
			      CompAction::State  state,
			      CompOption::Vector &options);

	static bool lowerWin (CompAction         *action,
			      CompAction::State  state,
			      CompOption::Vector &options);

	static bool toggleWinMaximized (CompAction         *action,
					CompAction::State  state,
					CompOption::Vector &options);

	static bool toggleWinMaximizedHorizontally (CompAction         *action,
						    CompAction::State  state,
						    CompOption::Vector &options);

	static bool toggleWinMaximizedVertically (CompAction         *action,
					          CompAction::State  state,
					          CompOption::Vector &options);

	static bool shadeWin (CompAction         *action,
			      CompAction::State  state,
			      CompOption::Vector &options);

	bool createFailed () const;


    private:
        virtual bool _setOptionForPlugin(const char *, const char *, CompOption::Value &);
        virtual bool _initPluginForScreen(CompPlugin *);
        virtual void _finiPluginForScreen(CompPlugin *);
        virtual void _handleEvent(XEvent *event);
        virtual void _logMessage(const char *, CompLogLevel, const char*);
        virtual void _enterShowDesktopMode();
        virtual void _leaveShowDesktopMode(CompWindow *);
        virtual void _addSupportedAtoms(std::vector<Atom>& atoms);

        // These are stubs - but allow mocking of AbstractCompWindow
        virtual void _fileWatchAdded(CompFileWatch *);
        virtual void _fileWatchRemoved(CompFileWatch *);
        virtual void _sessionEvent(CompSession::Event, CompOption::Vector &);
        virtual void _handleCompizEvent(const char *, const char *, CompOption::Vector &);
        virtual bool _fileToImage(CompString &, CompSize &, int &, void *&);
        virtual bool _imageToFile(CompString &, CompString &, CompSize &, int, void *);
        virtual CompMatch::Expression * _matchInitExp(const CompString&);
        virtual void _matchExpHandlerChanged();
        virtual void _matchPropertyChanged(CompWindow *);
        virtual void _outputChangeNotify();

	void grabServer ();
	void ungrabServer ();
	void syncServer ();

        bool handlePingTimeout();

        Window below;
	CompTimer autoRaiseTimer_;
	Window    autoRaiseWindow_;
	CompIcon *defaultIcon_;
	compiz::private_screen::GrabManager mutable grabManager;
    	ValueHolder valueHolder;
        bool 	eventHandled;
        PrivateScreen privateScreen;
        compiz::private_screen::WindowManager windowManager;
        unsigned int showingDesktopMask_;
};

#endif