File: PsychWindowGlue.c

package info (click to toggle)
psychtoolbox-3 3.0.9%2Bsvn2579.dfsg1-1
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 63,408 kB
  • sloc: ansic: 73,310; cpp: 11,139; objc: 3,129; sh: 1,669; python: 382; php: 272; makefile: 172; java: 113
file content (1662 lines) | stat: -rwxr-xr-x 74,228 bytes parent folder | download
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
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
/*
	PsychToolbox3/Source/Linux/Screen/PsychWindowGlue.c
	
	PLATFORMS:	
	
		This is the Linux/X11 version only.  
				
	AUTHORS:
	
		Allen Ingling		awi		Allen.Ingling@nyu.edu
                Mario Kleiner           mk              mario.kleiner at tuebingen.mpg.de

	HISTORY:
	
	        2/20/06                 mk              Created - Derived from Windows version.

	DESCRIPTION:
	
		Functions in this file comprise an abstraction layer for probing and controlling window state, except for window content.  
		
		Each C function which implements a particular Screen subcommand should be platform neutral.  For example, the source to SCREENPixelSizes() 
		should be platform-neutral, despite that the calls in OS X and Linux to detect available pixel sizes are different.  The platform 
		specificity is abstracted out in C files which end it "Glue", for example PsychScreenGlue, PsychWindowGlue, PsychWindowTextClue.

	NOTES:
	
	TO DO: 
	 
*/

#include "Screen.h"

/* These are needed for realtime scheduling control: */
#include <sched.h>
#include <errno.h>

/* XAtom support for setup of transparent windows: */
#include <X11/Xatom.h>

// Use dedicated x-display handles for each onscreen window?
static psych_bool usePerWindowXConnections = FALSE;

// Use GLX version 1.3 setup code? Enabled INTEL_SWAP_EVENTS and other goodies...
static psych_bool useGLX13;

// Event base for GLX extension:
static int glx_error_base, glx_event_base;

// Number of currently open onscreen windows:
static int x11_windowcount = 0;

// Typedef and fcn-pointer for optional Mesa get swap interval call:
typedef int (*PFNGLXGETSWAPINTERVALMESAPROC)(void);
PFNGLXGETSWAPINTERVALMESAPROC glXGetSwapIntervalMESA = NULL;

#ifndef GLX_BUFFER_SWAP_COMPLETE_INTEL_MASK
#define GLX_BUFFER_SWAP_COMPLETE_INTEL_MASK	0x04000000
#endif

#ifndef GLX_BufferSwapComplete
#define GLX_BufferSwapComplete	1
#endif

typedef struct GLXBufferSwapComplete {
    int type;
    unsigned long serial;	/* # of last request processed by server */
    Bool send_event;		/* true if this came from a SendEvent request */
    Display *display;		/* Display the event was read from */
    GLXDrawable drawable;	/* drawable on which event was requested in event mask */
    int event_type;
    int64_t ust;
    int64_t msc;
    int64_t sbc;
} GLXBufferSwapComplete;

/** PsychRealtimePriority: Temporarily boost priority to highest available priority on Linux.
    PsychRealtimePriority(true) enables realtime-scheduling (like Priority(>0) would do in Matlab).
    PsychRealtimePriority(false) restores scheduling to the state before last invocation of PsychRealtimePriority(true),
    it undos whatever the previous switch did.

    We switch to RT scheduling during PsychGetMonitorRefreshInterval() and a few other timing tests in
    PsychOpenWindow() to reduce measurement jitter caused by possible interference of other tasks.
*/
psych_bool PsychRealtimePriority(psych_bool enable_realtime)
{
    static psych_bool old_enable_realtime = FALSE;
    static int   oldPriority = SCHED_OTHER;
    const  int   realtime_class = SCHED_FIFO;
    struct sched_param param;
    static struct sched_param oldparam;

    if (old_enable_realtime == enable_realtime) {
        // No transition with respect to previous state -> Nothing to do.
        return(true);
    }
    
    // Transition requested:    
    if (enable_realtime) {
      // Transition to realtime requested:
      
      // Get current scheduling policy and back it up for later restore:
      pthread_getschedparam(pthread_self(), &oldPriority, &oldparam);

      // Check if realtime scheduling isn't already active.
      // If we are already in RT mode (e.g., Priority(2) call in Matlab), we skip the switch...
      if (oldPriority != realtime_class) {
	// RT scheduling not yet active -> Switch to it.
	// We use the smallest realtime priority that's available for realtime_class.
	// This way, other processes like watchdogs can preempt us, if needed.
	param.sched_priority = sched_get_priority_min(realtime_class);
	if (pthread_setschedparam(pthread_self(), realtime_class, &param)) {
	  // Failed!
	  if(!PsychPrefStateGet_SuppressAllWarnings()) {
	    printf("PTB-INFO: Failed to enable realtime-scheduling [%s]!\n", strerror(errno));
	    if (errno==EPERM) {
	      printf("PTB-INFO: You need to run Matlab or Octave with root-privileges, or run the script PsychLinuxConfiguration once for this to work.\n");
	      printf("PTB-INFO: See /usr/share/doc/psychtoolbox-3-common/README.Debian to make this work.\n");
	    }
	  }
	  errno=0;
	}
      }
    }
    else {
      // Transition from RT to whatever-it-was-before scheduling requested: We just reestablish the backed-up old
      // policy: If the old policy wasn't Non-RT, then we don't switch back...
      if (oldPriority != realtime_class) oldparam.sched_priority = 0;

      if (pthread_setschedparam(pthread_self(), oldPriority, &oldparam)) {
	// Failed!
	if(!PsychPrefStateGet_SuppressAllWarnings()) {
	  printf("PTB-INFO: Failed to disable realtime-scheduling [%s]!\n", strerror(errno));
	  if (errno==EPERM) {
	    printf("PTB-INFO: You need to run Matlab or Octave with root-privileges or run the script PsychLinuxConfiguration once for this to work.\n");
	    printf("PTB-INFO: See /usr/share/doc/psychtoolbox-3-common/README.Debian to make this work.\n");
	  }
	}
	errno=0;
      }
    }

    //printf("PTB-INFO: Realtime scheduling %sabled\n", enable_realtime ? "en" : "dis");

    // Success.
    old_enable_realtime = enable_realtime;
    return(TRUE);
}

/*
    PsychOSOpenOnscreenWindow()
    
    Creates the pixel format and the context objects and then instantiates the context onto the screen.
    
    -The pixel format and the context are stored in the target specific field of the window recored.  Close
    should clean up by destroying both the pixel format and the context.
    
    -We mantain the context because it must be be made the current context by drawing functions to draw into 
    the specified window.
    
    -We maintain the pixel format object because there seems to be now way to retrieve that from the context.
    
    -To tell the caller to clean up PsychOSOpenOnscreenWindow returns FALSE if we fail to open the window. It 
    would be better to just issue an PsychErrorExit() and have that clean up everything allocated outside of
    PsychOpenOnscreenWindow().
*/
psych_bool PsychOSOpenOnscreenWindow(PsychScreenSettingsType *screenSettings, PsychWindowRecordType *windowRecord, int numBuffers, int stereomode, int conserveVRAM)
{
  PsychRectType             screenrect;
  CGDirectDisplayID         dpy;
  int scrnum;
  XSetWindowAttributes attr;
  unsigned long mask;
  Window root;
  Window win;
  GLXContext ctx;
  GLXFBConfig *fbconfig = NULL;
  GLXWindow glxwindow;
  XVisualInfo *visinfo = NULL;
  int i, x, y, width, height, nrdummy;
  GLenum glerr;
  psych_bool fullscreen = FALSE;
  int attrib[41];
  int attribcount=0;
  int stereoenableattrib=0;
  int depth, bpc;
  int windowLevel;
  int major, minor;

  // Retrieve windowLevel, an indicator of where non-fullscreen windows should
  // be located wrt. to other windows. 0 = Behind everything else, occluded by
  // everything else. 1 - 999 = At layer windowLevel -> Occludes stuff on layers "below" it.
  // 1000 - 1999 = At highest level, but partially translucent / alpha channel allows to make
  // regions transparent. 2000 or higher: Above everything, fully opaque, occludes everything.
  // 2000 is the default.
  windowLevel = PsychPrefStateGet_WindowShieldingLevel();
  
  // Init userspace GL context to safe default:
  windowRecord->targetSpecific.glusercontextObject = NULL;
  windowRecord->targetSpecific.glswapcontextObject = NULL;
    	 
  // Which display depth is requested?
  depth = PsychGetValueFromDepthStruct(0, &(screenSettings->depth));

  // Map the logical screen number to the corresponding X11 display connection handle
  // for the corresponding X-Server connection.
  PsychGetCGDisplayIDFromScreenNumber(&dpy, screenSettings->screenNumber);
  scrnum = PsychGetXScreenIdForScreen(screenSettings->screenNumber);

  // Default to use of one shared x-display connection "dpy" for all onscreen windows
  // on a given x-display and x-screen:
  windowRecord->targetSpecific.privDpy = dpy;

  // Override with per-window x-display connection if requested by environment variable:
  usePerWindowXConnections = (getenv("PTB_USEPERWINDOWXCONNECTIONS")) ? TRUE : FALSE;
  if (usePerWindowXConnections) {
    // Open a dedicated X-Display connection for this onscreen window. This is meant to
    // avoid parallel ops on multiple onscreen windows, e.g., async swaps via flip-threads,
    // from blocking on a single shared x-display connection.
    // The dedicated handle is a clone of the x-display handle/connection for
    // the parent-screen associated with this onscreen window:
    //
    // NOTICE: As of September 2011 and X-Server 1.9.x and 1.10.x, this doesn't work
    //         well at all! It is entirely useless in its current form, just left for
    //         documentation, and in case we find some better - and actually working -
    //         use case for per-window x-display connections in the future.
    //
    // Problems with the current approach:
    //
    // * If we create each onscreen window (== GLXDrawable) and associated OpenGL
    //   contexts on a separate x-display connection, the OpenGL contexts apparently
    //   can't share resources like texture objects, FBO's, PBO's, VBO's, display lists
    //   or shaders. This is an absolute no-go for PTB's rendering architecture!
    //
    // * If we use the master dpy connection for OpenGL ops and only dedicated connections
    //   for non-OpenGL GLX ops, e.g., the OML_sync_control functions, then those functions
    //   fail with BadContext errors and i couldn't find any way or hack around it.
    //
    // * Other than those cases, there isn't any real use for dedicated x-display connections
    //   at the moment.
    //
    // It is unclear if these problems are due to bugs in the X-Server / DRI2 infrastructure,
    // really weird and subtile bugs in our code, or if we simply tried doing something that
    // is unsupported and forbidden by design of the X-Window system / X11-Protocol.
    //
    // Anyway leave the setup code here, it is disabled by default anyway, so no harm done,
    // and maybe useful for testing if it is our bug, their bug or unsupported behaviour...
    windowRecord->targetSpecific.privDpy = XOpenDisplay(DisplayString(dpy));
    if (NULL == windowRecord->targetSpecific.privDpy) {
      // Failed! We are sooo done :-(
      printf("\nPTB-ERROR[XOpenDisplay() failed]: Couldn't get a dedicated x-display connection for this window to X-Server.\n\n");
      return(FALSE);
    }
  }

  // Init GLX extension, get its version, determine if at least V1.3 supported:
  useGLX13 = (glXQueryExtension(dpy, &glx_error_base, &glx_event_base) &&
              glXQueryVersion(dpy, &major, &minor) && ((major > 1) || ((major == 1) && (minor >= 3))));

  // Initialze GLX-1.3 protocol support. Use if possible:
  glXChooseFBConfig = (PFNGLXCHOOSEFBCONFIGPROC) glXGetProcAddressARB("glXChooseFBConfig");
  glXGetVisualFromFBConfig = (PFNGLXGETVISUALFROMFBCONFIGPROC) glXGetProcAddressARB("glXGetVisualFromFBConfig");
  glXCreateWindow = (PFNGLXCREATEWINDOWPROC) glXGetProcAddressARB("glXCreateWindow");
  glXCreateNewContext = (PFNGLXCREATENEWCONTEXTPROC) glXGetProcAddressARB("glXCreateNewContext");
  glXDestroyWindow = (PFNGLXDESTROYWINDOWPROC) glXGetProcAddressARB("glXDestroyWindow");
  glXSelectEvent = (PFNGLXSELECTEVENTPROC) glXGetProcAddressARB("glXSelectEvent");
  glXGetSelectedEvent = (PFNGLXGETSELECTEDEVENTPROC) glXGetProcAddressARB("glXGetSelectedEvent");

  // Check if everything we need from GLX-1.3 is supported:
  if (!useGLX13 || !glXChooseFBConfig || !glXGetVisualFromFBConfig || !glXCreateWindow || !glXCreateNewContext ||
      !glXDestroyWindow || !glXSelectEvent || !glXGetSelectedEvent) {
    useGLX13 = FALSE;
    printf("PTB-INFO: Not using GLX-1.3 extension. Unsupported? Some features may be disabled.\n");
  } else {
    useGLX13 = TRUE;
  }

  // Check if this should be a fullscreen window, and if not, what its dimensions
  // should be:
  PsychGetScreenRect(screenSettings->screenNumber, screenrect);
  if (PsychMatchRect(screenrect, windowRecord->rect)) {
    // This is supposed to be a fullscreen window with the dimensions of
    // the current display/desktop:
    x=0;
    y=0;
    width=PsychGetWidthFromRect(screenrect);
    height=PsychGetHeightFromRect(screenrect);      
    
    // Switch system to fullscreen-mode without changing any settings:
    fullscreen = TRUE;

	// Mark this window as fullscreen window:
	windowRecord->specialflags |= kPsychIsFullscreenWindow;
	
	// Copy absolute screen location and area of window to 'globalrect',
	// so functions like Screen('GlobalRect') can still query the real
	// bounding gox of a window onscreen:
	PsychGetGlobalScreenRect(screenSettings->screenNumber, windowRecord->globalrect);
  }
  else {
    // Window size different from current screen size:
    // A regular desktop window with borders and control icons is requested, e.g., for debugging:
    // Extract settings:
    x=windowRecord->rect[kPsychLeft];
    y=windowRecord->rect[kPsychTop];
    width=PsychGetWidthFromRect(windowRecord->rect);
    height=PsychGetHeightFromRect(windowRecord->rect);
    fullscreen = FALSE;
	
	// Copy absolute screen location and area of window to 'globalrect',
	// so functions like Screen('GlobalRect') can still query the real
	// bounding gox of a window onscreen:
    PsychCopyRect(windowRecord->globalrect, windowRecord->rect);
  }

  // Select requested depth per color component 'bpc' for each channel:
  bpc = 8; // We default to 8 bpc == RGBA8
  if (windowRecord->depth == 30)  { bpc = 10; printf("PTB-INFO: Trying to enable at least 10 bpc fixed point framebuffer.\n"); }
  if (windowRecord->depth == 64)  { bpc = 16; printf("PTB-INFO: Trying to enable 16 bpc fixed point framebuffer.\n"); }
  if (windowRecord->depth == 128) { bpc = 32; printf("PTB-INFO: Trying to enable 32 bpc fixed point framebuffer.\n"); }
  
  // Setup pixelformat descriptor for selection of GLX visual:
  if (useGLX13) {
    attrib[attribcount++]= GLX_RENDER_TYPE; // Use RGBA true-color visual.
    attrib[attribcount++]= GLX_RGBA_BIT;    // Use RGBA true-color visual.
  } else {
    attrib[attribcount++]= GLX_RGBA;        // Use RGBA true-color visual.
  }

  attrib[attribcount++]= GLX_RED_SIZE;    // Setup requested minimum depth of each color channel:
  attrib[attribcount++]= (depth > 16) ? bpc : 1;
  attrib[attribcount++]= GLX_GREEN_SIZE;
  attrib[attribcount++]= (depth > 16) ? bpc : 1;
  attrib[attribcount++]= GLX_BLUE_SIZE;
  attrib[attribcount++]= (depth > 16) ? bpc : 1;
  attrib[attribcount++]= GLX_ALPHA_SIZE;
  // Alpha channel needs special treatment:
  if (bpc != 10) {
	// Non 10 bpc drawable: Request a 'bpc' alpha channel if the underlying framebuffer
	// is in true-color mode ( >= 24 cpp format). If framebuffer is in 16 bpp mode, we
	// don't have/request an alpha channel at all:
	attrib[attribcount++]= (depth > 16) ? bpc : 0; // In 16 bit mode, we don't request an alpha-channel.
  }
  else {
	// 10 bpc drawable: We have a 32 bpp pixel format with R10G10B10 10 bpc per color channel.
	// There are at most 2 bits left for the alpha channel, so we request an alpha channel with
	// minimum size 1 bit --> Will likely translate into a 2 bit alpha channel:
	attrib[attribcount++]= 1;
  }
  
  // Stereo display support: If stereo display output is requested with OpenGL native stereo,
  // we request a stereo-enabled rendering context.
  if(stereomode==kPsychOpenGLStereo) {
    attrib[attribcount++]= GLX_STEREO;
    stereoenableattrib = attribcount;
    attrib[attribcount++]= True;
  }

  // Multisampling support:
  if (windowRecord->multiSample > 0) {
    // Request a multisample buffer:
    attrib[attribcount++]= GLX_SAMPLE_BUFFERS_ARB;
    attrib[attribcount++]= 1;
    // Request at least multiSample samples per pixel:
    attrib[attribcount++]= GLX_SAMPLES_ARB;
    attrib[attribcount++]= windowRecord->multiSample;
  }

  // Support for OpenGL 3D rendering requested?
  if (PsychPrefStateGet_3DGfx()) {
    // Yes. Allocate and attach a 24 bit depth buffer and 8 bit stencil buffer:
    attrib[attribcount++]= GLX_DEPTH_SIZE;
    attrib[attribcount++]= 24;
    attrib[attribcount++]= GLX_STENCIL_SIZE;
    attrib[attribcount++]= 8;

	// Alloc an accumulation buffer as well?
	if (PsychPrefStateGet_3DGfx() & 2) {
		// Yes: Alloc accum buffer, request 64 bpp, aka 16 bits integer per color component if possible:
		attrib[attribcount++] = GLX_ACCUM_RED_SIZE;
		attrib[attribcount++] = 16;
		attrib[attribcount++] = GLX_ACCUM_GREEN_SIZE;
		attrib[attribcount++] = 16;
		attrib[attribcount++] = GLX_ACCUM_BLUE_SIZE;
		attrib[attribcount++] = 16;
		attrib[attribcount++] = GLX_ACCUM_ALPHA_SIZE;
		attrib[attribcount++] = 16;
	}
  }

  // Double buffering requested?
  if(numBuffers>=2) {
    // Enable double-buffering:
    attrib[attribcount++]= GLX_DOUBLEBUFFER;
    attrib[attribcount++]= True;

    // AUX buffers for Flip-Operations needed?
    if ((conserveVRAM & kPsychDisableAUXBuffers) == 0) {
      // Allocate one or two (mono vs. stereo) AUX buffers for new "don't clear" mode of Screen('Flip'):
      // Not clearing the framebuffer after "Flip" is implemented by storing a backup-copy of
      // the backbuffer to AUXs before flip and restoring the content from AUXs after flip.
      attrib[attribcount++]= GLX_AUX_BUFFERS;
      attrib[attribcount++]=(stereomode==kPsychOpenGLStereo || stereomode==kPsychCompressedTLBRStereo || stereomode==kPsychCompressedTRBLStereo) ? 2 : 1;
    }
  }

  // It's important that GLX_AUX_BUFFERS is the last entry in the attrib array, see code for glXChooseVisual below...

  // Finalize attric array:
  attrib[attribcount++]= None;

  root = RootWindow( dpy, scrnum );

  // Select matching visual for our pixelformat:
  if (useGLX13) {
    fbconfig = glXChooseFBConfig(dpy, scrnum, attrib, &nrdummy);
  } else {
    visinfo = glXChooseVisual(dpy, scrnum, attrib );
  }

  if (!visinfo && !fbconfig && (stereoenableattrib > 0)) {
	// Failed to find matching visual and OpenGL native quad-buffered frame-sequential
	// stereo requested. Probably the GPU does not support it. Disable it as we have a
	// fallback implementation for this case.
	attrib[stereoenableattrib] = False;

	// Retry:
	if (useGLX13) {
		fbconfig = glXChooseFBConfig(dpy, scrnum, attrib, &nrdummy);
	} else {
		visinfo = glXChooseVisual(dpy, scrnum, attrib );
	}
  }

  if (!visinfo && !fbconfig) {
	  // Failed to find matching visual: Could it be related to request for unsupported native 10 bpc framebuffer?
	  if ((windowRecord->depth == 30) && (bpc == 10)) {
		  // 10 bpc framebuffer requested: Let's see if we can get a visual by lowering our demand to 8 bpc:
		  for (i=0; i<attribcount && attrib[i]!=GLX_RED_SIZE; i++);
		  attrib[i+1] = 8;
		  for (i=0; i<attribcount && attrib[i]!=GLX_GREEN_SIZE; i++);
		  attrib[i+1] = 8;
		  for (i=0; i<attribcount && attrib[i]!=GLX_BLUE_SIZE; i++);
		  attrib[i+1] = 8;
		  for (i=0; i<attribcount && attrib[i]!=GLX_ALPHA_SIZE; i++);
		  attrib[i+1] = 1;
		  
		  // Retry:
		  if (useGLX13) {
			  fbconfig = glXChooseFBConfig(dpy, scrnum, attrib, &nrdummy);
		  } else {
			  visinfo = glXChooseVisual(dpy, scrnum, attrib );
		  }
	  }
  }
  
  if (!visinfo && !fbconfig) {
	  // Failed to find matching visual: Could it be related to multisampling?
	  if (windowRecord->multiSample > 0) {
		  // Multisampling requested: Let's see if we can get a visual by
		  // lowering our demand:
		  for (i=0; i<attribcount && attrib[i]!=GLX_SAMPLES_ARB; i++);
		  while(!visinfo && !fbconfig && windowRecord->multiSample > 0) {
			  attrib[i+1]--;
			  windowRecord->multiSample--;

			  if (useGLX13) {
				  fbconfig = glXChooseFBConfig(dpy, scrnum, attrib, &nrdummy);
			  } else {
				  visinfo = glXChooseVisual(dpy, scrnum, attrib );
			  }
		  }
		  
		  // Either we have a valid visual at this point or we still fail despite
		  // requesting zero samples.
		  if (!visinfo && !fbconfig) {
			  // We still fail. Disable multisampling by requesting zero multisample buffers:
			  for (i=0; i<attribcount && attrib[i]!=GLX_SAMPLE_BUFFERS_ARB; i++);
			  windowRecord->multiSample = 0;
			  attrib[i+1]=0;

			  if (useGLX13) {
				  fbconfig = glXChooseFBConfig(dpy, scrnum, attrib, &nrdummy);
			  } else {
				  visinfo = glXChooseVisual(dpy, scrnum, attrib );
			  }
		  }
	  }

    // Break out of this if we finally got one...
    if (!visinfo && !fbconfig) {
      // Failed to find matching visual: This can happen if we request AUX buffers on a system
      // that doesn't support AUX-buffers. In that case we retry without requesting AUX buffers
      // and output a proper warning instead of failing. For 99% of all applications one can
      // do without AUX buffers anyway...
      //printf("PTB-WARNING: Couldn't enable AUX buffers on onscreen window due to limitations of your gfx-hardware or driver. Some features may be disabled or limited...\n");
      //fflush(NULL);
      
      // Terminate attrib array where the GLX_AUX_BUFFERS entry used to be...
      attrib[attribcount-3] = None;
      
      // Retry...
      if (useGLX13) {
	      fbconfig = glXChooseFBConfig(dpy, scrnum, attrib, &nrdummy);
      } else {
	      visinfo = glXChooseVisual(dpy, scrnum, attrib );
      }

      if (!visinfo && !fbconfig && PsychPrefStateGet_3DGfx()) {
	// Ok, retry with a 16 bit depth buffer...
	for (i=0; i<attribcount && attrib[i]!=GLX_DEPTH_SIZE; i++);
	if (attrib[i]==GLX_DEPTH_SIZE && i<attribcount) attrib[i+1]=16;
	printf("PTB-WARNING: Have to use 16 bit depth buffer instead of 24 bit buffer due to limitations of your gfx-hardware or driver. Accuracy of 3D-Gfx may be limited...\n");
	fflush(NULL);
	
	if (useGLX13) {
		fbconfig = glXChooseFBConfig(dpy, scrnum, attrib, &nrdummy);
	} else {
		visinfo = glXChooseVisual(dpy, scrnum, attrib );
	}
	if (!visinfo && !fbconfig) {
	  // Failed again. Retry with disabled stencil buffer:
	  printf("PTB-WARNING: Have to disable stencil buffer due to limitations of your gfx-hardware or driver. Some 3D Gfx algorithms may fail...\n");
	  fflush(NULL);
	  for (i=0; i<attribcount && attrib[i]!=GLX_STENCIL_SIZE; i++);
	  if (attrib[i]==GLX_STENCIL_SIZE && i<attribcount) attrib[i+1]=0;
	  if (useGLX13) {
		  fbconfig = glXChooseFBConfig(dpy, scrnum, attrib, &nrdummy);
	  } else {
		  visinfo = glXChooseVisual(dpy, scrnum, attrib );
	  }
	}
      }
    }
  }

  if (!visinfo && !fbconfig) {
    printf("\nPTB-ERROR[glXChooseVisual() failed]: Couldn't get any suitable visual from X-Server.\n\n");
    return(FALSE);
  }

  // If this setup is fbconfig based, get associated visual:
  if (fbconfig) visinfo = glXGetVisualFromFBConfig(dpy, fbconfig[0]);

  // Set window to non-fullscreen mode if it is a transparent or otherwise special window.
  // This will prevent setting the override_redirect attribute, which would lock out the
  // desktop window compositor:
  if (windowLevel < 2000) fullscreen = FALSE;

  // Also disable fullscreen mode for GUI-like windows:
  if (windowRecord->specialflags & kPsychGUIWindow) fullscreen = FALSE;  

  // Setup window attributes:
  attr.background_pixel = 0;  // Background color defaults to black.
  attr.border_pixel = 0;      // Border color as well.
  attr.colormap = XCreateColormap( dpy, root, visinfo->visual, AllocNone);  // Dummy colormap assignment.
  attr.event_mask = KeyPressMask | StructureNotifyMask; // | ExposureMask;  // We're only interested in keypress events for GetChar() and StructureNotify to wait for Windows to be mapped.
  attr.override_redirect = (fullscreen) ? 1 : 0;                            // Lock out window manager if fullscreen window requested.
  mask = CWOverrideRedirect | CWBackPixel | CWBorderPixel | CWColormap | CWEventMask;

  // Create our onscreen window:
  win = XCreateWindow( dpy, root, x, y, width, height,
		       0, visinfo->depth, InputOutput,
		       visinfo->visual, mask, &attr );

  // Set hints and properties:
  {
    XSizeHints sizehints;
    sizehints.x = x;
    sizehints.y = y;
    sizehints.width  = width;
    sizehints.height = height;
    sizehints.flags = USSize | USPosition;
    XSetNormalHints(dpy, win, &sizehints);
    XSetStandardProperties(dpy, win, "PTB Onscreen window", "PTB Onscreen window",
			   None, (char **)NULL, 0, &sizehints);
  }

  if (fbconfig) {
	glxwindow = glXCreateWindow(dpy, fbconfig[0], win, NULL);
  }

  // Create associated GLX OpenGL rendering context: We use ressource
  // sharing of textures, display lists, FBO's and shaders if 'slaveWindow'
  // is assigned for that purpose as master-window. We request a direct
  // rendering context (True) if possible:
  if (fbconfig) {
    ctx = glXCreateNewContext(dpy, fbconfig[0], GLX_RGBA_TYPE, ((windowRecord->slaveWindow) ? windowRecord->slaveWindow->targetSpecific.contextObject : NULL), True);
  } else {
    ctx = glXCreateContext(dpy, visinfo, ((windowRecord->slaveWindow) ? windowRecord->slaveWindow->targetSpecific.contextObject : NULL), True );
  }

  if (!ctx) {
    printf("\nPTB-ERROR:[glXCreateContext() failed] OpenGL context creation failed!\n\n");
    return(FALSE);
  }

  // Store the handles:

  // windowHandle is a GLXWindow. Fallback path assigns a Window. Both are typedef'd
  // to XID, so this cast and storage is safe to do:
  windowRecord->targetSpecific.windowHandle = (fbconfig) ? glxwindow : (GLXWindow) win;

  // xwindowHandle stores the underlying X-Window:
  windowRecord->targetSpecific.xwindowHandle = win;

  windowRecord->targetSpecific.deviceContext = dpy;
  windowRecord->targetSpecific.contextObject = ctx;

  // Create rendering context for async flips with identical visual and display as main context, share all heavyweight ressources with it:
  if (fbconfig) {
      windowRecord->targetSpecific.glswapcontextObject = glXCreateNewContext(dpy, fbconfig[0], GLX_RGBA_TYPE, windowRecord->targetSpecific.contextObject, True);
  } else {
      windowRecord->targetSpecific.glswapcontextObject = glXCreateContext(dpy, visinfo, windowRecord->targetSpecific.contextObject, True);
  }
  
  if (windowRecord->targetSpecific.glswapcontextObject == NULL) {
      printf("\nPTB-ERROR[SwapContextCreation failed]: Creating a private OpenGL context for async flips failed for unknown reasons.\n\n");
      return(FALSE);
  }
  
  // External 3D graphics support enabled?
  if (PsychPrefStateGet_3DGfx()) {
    // Yes. We need to create an extra OpenGL rendering context for the external
    // OpenGL code to provide optimal state-isolation. The context shares all
    // heavyweight ressources likes textures, FBOs, VBOs, PBOs, display lists and
    // starts off as an identical copy of PTB's context as of here.

    // Create rendering context with identical visual and display as main context, share all heavyweight ressources with it:
    if (fbconfig) {
	windowRecord->targetSpecific.glusercontextObject = glXCreateNewContext(dpy, fbconfig[0], GLX_RGBA_TYPE, windowRecord->targetSpecific.contextObject, True);
    } else {
	windowRecord->targetSpecific.glusercontextObject = glXCreateContext(dpy, visinfo, windowRecord->targetSpecific.contextObject, True);
    }

    if (windowRecord->targetSpecific.glusercontextObject == NULL) {
      printf("\nPTB-ERROR[UserContextCreation failed]: Creating a private OpenGL context for Matlab OpenGL failed for unknown reasons.\n\n");
      return(FALSE);
    }    
  }
  
  // Release visual info:
  XFree(visinfo);

  // Release fbconfig array, if any:
  if (fbconfig) XFree(fbconfig);

  // Setup window transparency:
  if ((windowLevel >= 1000) && (windowLevel < 2000)) {
	  // For windowLevels between 1000 and 1999, make the window background transparent, so standard GUI
	  // would be visible, wherever nothing is drawn, i.e., where alpha channel is zero:
	  
	  // Levels 1000 - 1499 and 1500 to 1999 map to a master opacity level of 0.0 - 1.0:	  
	  unsigned int opacity = (unsigned int) (0xffffffff * (((float) (windowLevel % 500)) / 499.0));
	  
	  // Get handle on opacity property of X11:
	  Atom atom_window_opacity = XInternAtom(dpy, "_NET_WM_WINDOW_OPACITY", False);
	  
	  // Assign new value for property:
	  XChangeProperty(dpy, win, atom_window_opacity, XA_CARDINAL, 32, PropModeReplace, (unsigned char *) &opacity, 1);
  }

  // Show our new window:
  XMapWindow(dpy, win);

  // Spin-Wait for it to be really mapped:
  while (1) {
      XEvent ev;
      XNextEvent(dpy, &ev);
      if (ev.type == MapNotify)
          break;

      PsychYieldIntervalSeconds(0.001);
  }
  
  // Setup window transparency for user input (keyboard and mouse events):
  if (windowLevel < 1500) {
	// Need to try to be transparent for keyboard events and mouse clicks:
	XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);	
  }

  // Activate the associated rendering context:
  PsychOSSetGLContext(windowRecord);

  // Ok, the OpenGL rendering context is up and running. Auto-detect and bind all
  // available OpenGL extensions via GLEW:
  glerr = glewInit();
  if (GLEW_OK != glerr) {
    /* Problem: glewInit failed, something is seriously wrong. */
    printf("\nPTB-ERROR[GLEW init failed: %s]: Please report this to the forum. Will try to continue, but may crash soon!\n\n", glewGetErrorString(glerr));
    fflush(NULL);
  }
  else {
    if (PsychPrefStateGet_Verbosity() > 3) printf("PTB-INFO: Using GLEW version %s for automatic detection of OpenGL extensions...\n", glewGetString(GLEW_VERSION));
  }
  
  fflush(NULL);

  // Increase our own open window counter:
  x11_windowcount++;

  // Disable X-Windows screensavers:
  if (x11_windowcount==1) {
    // First window. Disable future use of screensaver:
    XSetScreenSaver(dpy, 0, 0, DefaultBlanking, DefaultExposures);
    // If the screensaver is currently running, forcefully shut it down:
    XForceScreenSaver(dpy, ScreenSaverReset);
  }

  // Some info for the user regarding non-fullscreen and ATI hw:
  if (!(windowRecord->specialflags & kPsychIsFullscreenWindow) && (strstr(glGetString(GL_VENDOR), "ATI"))) {
    printf("PTB-INFO: Some ATI graphics cards may not support proper syncing to vertical retrace when\n");
    printf("PTB-INFO: running in windowed mode (non-fullscreen). If PTB aborts with 'Synchronization failure'\n");
    printf("PTB-INFO: you can disable the sync test via call to Screen('Preference', 'SkipSyncTests', 1); .\n");
    printf("PTB-INFO: You won't get proper stimulus onset timestamps though, so windowed mode may be of limited use.\n");
  }
  fflush(NULL);

  // Check for availability of VSYNC extension:
  
  // First we try if the MESA variant of the swap control extensions is available. It has two advantages:
  // First, it also provides a function to query the current swap interval. Second it allows to set a
  // zero swap interval to dynamically disable sync to retrace, just as on OS/X and Windows:
  if (strstr(glXQueryExtensionsString(dpy, scrnum), "GLX_MESA_swap_control")) {
	// Bingo! Bind Mesa variant of setup call to sgi setup call, just to simplify the code
	// that actually uses the setup call -- no special cases or extra code needed there :-)
	// This special glXSwapIntervalSGI() call will simply accept an input value of zero for
	// disabling vsync'ed bufferswaps as a valid input parameter:
	glXSwapIntervalSGI = (PFNGLXSWAPINTERVALSGIPROC) glXGetProcAddressARB("glXSwapIntervalMESA");
	
	// Additionally bind the Mesa query call:
	glXGetSwapIntervalMESA = (PFNGLXGETSWAPINTERVALMESAPROC) glXGetProcAddressARB("glXGetSwapIntervalMESA");
	if (PsychPrefStateGet_Verbosity() > 3) printf("PTB-INFO: Using GLX_MESA_swap_control extension for control of vsync.\n");
  }
  else {
	// Unsupported. Disable the get call:
	glXGetSwapIntervalMESA = NULL;
  }

  // Special case: Buggy ATI driver: Supports the VSync extension and glXSwapIntervalSGI, but provides the
  // wrong extension namestring "WGL_EXT_swap_control" (from MS-Windows!), so GLEW doesn't auto-detect and
  // bind the extension. If this special case is present, we do it here manually ourselves:
  if ( (glXSwapIntervalSGI == NULL) && (strstr(glGetString(GL_EXTENSIONS), "WGL_EXT_swap_control") != NULL) ) {
	// Looks so: Bind manually...
	glXSwapIntervalSGI = (PFNGLXSWAPINTERVALSGIPROC) glXGetProcAddressARB("glXSwapIntervalSGI");
  }

  // Extension finally supported?
  if (glXSwapIntervalSGI==NULL || ( strstr(glXQueryExtensionsString(dpy, scrnum), "GLX_SGI_swap_control")==NULL &&
	  strstr(glGetString(GL_EXTENSIONS), "WGL_EXT_swap_control")==NULL && strstr(glXQueryExtensionsString(dpy, scrnum), "GLX_MESA_swap_control")==NULL )) {
	  // No, total failure to bind extension:
	  glXSwapIntervalSGI = NULL;
	  if (PsychPrefStateGet_Verbosity() > 1) { 
		  printf("PTB-WARNING: Your graphics driver doesn't allow me to control syncing wrt. vertical retrace!\n");
		  printf("PTB-WARNING: Please update your display graphics driver as soon as possible to fix this.\n");
		  printf("PTB-WARNING: Until then, you can manually enable syncing to VBL somehow in a manner that is\n");
		  printf("PTB-WARNING: dependent on the type of gfx-card and driver. Google is your friend...\n");
	  }
  }
  fflush(NULL);

  // First opened onscreen window? If so, we try to map GPU MMIO registers
  // to enable beamposition based timestamping and other special goodies:
  if (x11_windowcount == 1) PsychScreenMapRadeonCntlMemory();

  // Ok, we should be ready for OS independent setup...
  fflush(NULL);

  // Wait for X-Server to settle...
  XSync(dpy, 1);

  // Wait 250 msecs extra to give desktop compositor a chance to settle:
  PsychYieldIntervalSeconds(0.25);

  // Retrieve modeline of current video mode on primary crtc for the screen to which
  // this onscreen window is assigned. Could also query useful info about crtc, but let's not
  // overdo it in the first iteration...
  XRRCrtcInfo *crtc_info = NULL;
  XRRModeInfo *mode = PsychOSGetModeLine(screenSettings->screenNumber, 0, &crtc_info);
  if (mode) {
    // Assign modes display height aka vactive or vdisplay as startline of vblank interval:
    windowRecord->VBL_Startline = mode->height;
    // Assign vbl endline as vtotal - 1:
    windowRecord->VBL_Endline   = mode->vTotal - 1;

    // Check for output display rotation enabled. Will likely impair timing/timestamping
    // because it uses copy-swaps via an intermediate shadow framebuffer to do rotation
    // during copy-swap blit, instead of via rotated crtc scanout, as most crtc's don't
    // support this in hardware:
    if ((crtc_info->rotation != RR_Rotate_0) && (PsychPrefStateGet_Verbosity() > 1)) {
	printf("PTB-WARNING: Your primary output display has hardware rotation enabled. It is not displaying in upright orientation.\n");
	printf("PTB-WARNING: On many graphics cards, this will cause unreliable stimulus presentation timing and timestamping.\n");
	printf("PTB-WARNING: If you want non-upright stimulus presentation, look at 'help PsychImaging' on how to achieve this in\n");
	printf("PTB-WARNING: a way that doesn't impair timing. The subfunctions 'FlipHorizontal' and 'FlipVertical' are what you probably need.\n");
    }

    XRRFreeCrtcInfo(crtc_info);
  }
  
  // Well Done!
  return(TRUE);
}


/*
    PsychOSOpenOffscreenWindow()
    
    Accept specifications for the offscreen window in the platform-neutral structures, convert to native CoreGraphics structures,
    create the surface, allocate a window record and record the window specifications and memory location there.
	
	TO DO:  We need to walk down the screen number and fill in the correct value for the benefit of TexturizeOffscreenWindow
*/
psych_bool PsychOSOpenOffscreenWindow(double *rect, int depth, PsychWindowRecordType **windowRecord)
{
  // This function is obsolete and does nothing.
  return(FALSE);
}

/*
    PsychOSGetPostSwapSBC() -- Internal method for now, used in close window path.
 */
static psych_int64 PsychOSGetPostSwapSBC(PsychWindowRecordType *windowRecord)
{
	psych_int64 ust, msc, sbc;
	sbc = 0;

	#ifdef GLX_OML_sync_control
	// Extension unsupported or known to be defective? Return "damage neutral" 0 in that case:
	if ((NULL == glXWaitForSbcOML) || (windowRecord->specialflags & kPsychOpenMLDefective)) return(0);

	// Extension supported: Perform query and error check.
	if (!glXWaitForSbcOML(windowRecord->targetSpecific.privDpy, windowRecord->targetSpecific.windowHandle, 0, &ust, &msc, &sbc)) {
		// Failed! Return a "damage neutral" result:
		return(0);
	}
	#endif
	return(sbc);
}

void PsychOSCloseWindow(PsychWindowRecordType *windowRecord)
{
  Display* dpy = windowRecord->targetSpecific.deviceContext;

  // Check if we are trying to close the window after it had an "odd" (== non-even)
  // number of bufferswaps. If so, we execute one last bufferswap to make the count
  // even. This means that if this window was swapped via page-flipping, the system
  // should end with the same backbuffer-frontbuffer assignment as the one prior
  // to opening the window. This may help sidestep certain bugs in compositing desktop
  // managers (e.g., Compiz).
  if (PsychOSGetPostSwapSBC(windowRecord) % 2) {
	// Uneven count. Submit a swapbuffers request and wait for it to truly finish:

	// We have to rebind the OpenGL context for this swapbuffers call to work around some
	// mesa bug for intel drivers which would cause a crash without context:
	glXMakeCurrent(dpy, windowRecord->targetSpecific.windowHandle, windowRecord->targetSpecific.contextObject);

	PsychOSFlipWindowBuffers(windowRecord);
	PsychOSGetPostSwapSBC(windowRecord);
  }

  if (PsychPrefStateGet_Verbosity() > 5) {
	printf("PTB-DEBUG:PsychOSCloseWindow: Closing with a final swapbuffers count of %i.\n", (int) PsychOSGetPostSwapSBC(windowRecord));
  }

  // Detach OpenGL rendering context again - just to be safe!
  glXMakeCurrent(dpy, None, NULL);

  // Delete rendering context:
  glXDestroyContext(dpy, windowRecord->targetSpecific.contextObject);
  windowRecord->targetSpecific.contextObject=NULL;

  // Delete swap context:
  glXDestroyContext(dpy, windowRecord->targetSpecific.glswapcontextObject);
  windowRecord->targetSpecific.glswapcontextObject=NULL;

  // Delete userspace context, if any:
  if (windowRecord->targetSpecific.glusercontextObject) {
    glXDestroyContext(dpy, windowRecord->targetSpecific.glusercontextObject);
    windowRecord->targetSpecific.glusercontextObject = NULL;
  }

  // Wait for X-Server to settle...
  XSync(dpy, 0);

  if (useGLX13) glXDestroyWindow(dpy, windowRecord->targetSpecific.windowHandle);
  windowRecord->targetSpecific.windowHandle = 0;

  // Close & Destroy the window:
  XUnmapWindow(dpy, windowRecord->targetSpecific.xwindowHandle);

  // Wait for X-Server to settle...
  XSync(dpy, 0);

  XDestroyWindow(dpy, windowRecord->targetSpecific.xwindowHandle);
  windowRecord->targetSpecific.xwindowHandle=0;

  // Wait for X-Server to settle...
  XSync(dpy, 0);

  // Release device context: We just release the reference. The connection to the display is
  // closed below.
  windowRecord->targetSpecific.deviceContext=NULL;

  // Decrement global count of open onscreen windows:
  x11_windowcount--;

  // Was this the last window?
  if (x11_windowcount<=0) {
    x11_windowcount=0;

    // (Re-)enable X-Windows screensavers if they were enabled before opening windows:
    // Set screensaver to previous settings, potentially enabling it:
    XSetScreenSaver(dpy, -1, 0, DefaultBlanking, DefaultExposures);
    
    // Unmap/release possibly mapped device memory: Defined in PsychScreenGlue.c
    PsychScreenUnmapDeviceMemory();
  }

  // Release dedicated x-display connection for the dead window:
  if (usePerWindowXConnections) {
    XCloseDisplay(windowRecord->targetSpecific.privDpy);
  }

  // Done.
  return;
}

/*
    PsychOSGetVBLTimeAndCount()

    Returns absolute system time of last VBL and current total count of VBL interrupts since
    startup of gfx-system for the given screen. Returns a time of -1 and a count of 0 if this
    feature is unavailable on the given OS/Hardware configuration.
*/
double  PsychOSGetVBLTimeAndCount(PsychWindowRecordType *windowRecord, psych_uint64* vblCount)
{
	unsigned int	vsync_counter = 0;
	psych_uint64	ust, msc, sbc;
	
	#ifdef GLX_OML_sync_control
	// Ok, this will return VBL count and last VBL time via the OML GetSyncValuesOML call
	// if that extension is supported on this setup. As of mid 2009 i'm not aware of any
	// affordable graphics card that would support this extension, but who knows??
	if ((NULL != glXGetSyncValuesOML) && !(windowRecord->specialflags & kPsychOpenMLDefective) && (glXGetSyncValuesOML(windowRecord->targetSpecific.privDpy, windowRecord->targetSpecific.windowHandle, (int64_t*) &ust, (int64_t*) &msc, (int64_t*) &sbc))) {
		*vblCount = msc;
		if ((PsychGetKernelTimebaseFrequencyHz() > 10000) && !(windowRecord->specialflags & kPsychNeedOpenMLWorkaround1)) {
			// Convert ust into regular GetSecs timestamp:
			// At least we hope this conversion is correct...
			return( PsychOSMonotonicToRefTime(((double) ust) / PsychGetKernelTimebaseFrequencyHz()) );
		}
		else {
			// Last VBL timestamp unavailable:
			return(-1);
		}
	}
	#else
	#warning GLX_OML_sync_control unsupported! Compile with -std=gnu99 to enable it!
	#endif

	// Do we have SGI video sync extensions?
	if (NULL != glXGetVideoSyncSGI) {
		// Retrieve absolute count of vbl's since startup:
		glXGetVideoSyncSGI(&vsync_counter);
		*vblCount = (psych_uint64) vsync_counter;
		
		// Retrieve absolute system time of last retrace, convert into PTB standard time system and return it:
		// Not yet supported on Linux:
		return(-1);
	}
	else {
		// Unsupported :(
		*vblCount = 0;
		return(-1);
	}
}

/* PsychOSGetSwapCompletionTimestamp()
 *
 * Retrieve a very precise timestamp of doublebuffer swap completion by means
 * of OS specific facilities. This function is optional. If the underlying
 * OS/drier/GPU combo doesn't support a high-precision, high-reliability method
 * to query such timestamps, the function should return -1 as a signal that it
 * is unsupported or (temporarily) unavailable. Higher level timestamping code
 * should use/prefer timestamps returned by this function over other timestamps
 * provided by other mechanisms if possible. Calling code must be prepared to
 * use alternate timestamping methods if this method fails or returns a -1
 * unsupported error. Calling code must expect this function to block until
 * swap completion.
 *
 * Input argument targetSBC: Swapbuffers count for which to wait for. A value
 * of zero means to block until all pending bufferswaps for windowRecord have
 * completed, then return the timestamp of the most recently completed swap.
 *
 * A value of zero is recommended.
 *
 * Returns: Precise and reliable swap completion timestamp in seconds of
 * system time in variable referenced by 'tSwap', and msc value of completed swap,
 * or a negative value on error (-1 == unsupported, -2/-3 == Query failed).
 *
 */
psych_int64 PsychOSGetSwapCompletionTimestamp(PsychWindowRecordType *windowRecord, psych_int64 targetSBC, double* tSwap)
{
	psych_int64 ust, msc, sbc;
	msc = -1;

	#ifdef GLX_OML_sync_control
	
	// Extension unsupported or known to be defective? Return -1 "unsupported" in that case:
	if ((NULL == glXWaitForSbcOML) || (windowRecord->specialflags & kPsychOpenMLDefective)) return(-1);

	if (PsychPrefStateGet_Verbosity() > 11) printf("PTB-DEBUG:PsychOSGetSwapCompletionTimestamp: Supported. Calling with targetSBC = %lld.\n", targetSBC);

	// If this is a vsync'ed swap which potentially waits until a future point in time before completing, then
	// glXWaitForSbcOML() may block until that future point in time. Doing so, it will block the used x-display
	// connection to the X-Server. If we are not the only onscreen window in existence and use of per-window
	// x-display connections is disabled then we share this connection with all other onscreen windows. If
	// currently any asynchronous swaps are pending via async background flip threads, then us blocking
	// the shared x-display connection in glXWaitForSbcOML() would prevent those other threads from
	// communicating with the X-Server, effectively destroying all parallelism for background swap execution.
	// As a consequence all scheduled swaps on all onscreen windows would execute and finalize in lock-step,
	// rendering the requested stimulus onset presentation times for those windows dysfunctional, therefore
	// massively disrupting the wanted presentation timing!
	//
	// To prevent this, we must only call glXWaitForSbcOML() after we can be certain the swap completed. We
	// do this by waiting via polling. We poll the current sbc value and compare against the target value for
	// confirmed swap completion. Only then we continue to glXWaitForSbcOML() to collect the swap info non-blocking.
	//
	// This is the polling loop:
	while ((windowRecord->vSynced) && !PsychIsLastOnscreenWindow(windowRecord) && (PsychGetNrAsyncFlipsActive() > 0) &&
	       (windowRecord->targetSpecific.privDpy == windowRecord->targetSpecific.deviceContext) &&
	       glXGetSyncValuesOML(windowRecord->targetSpecific.privDpy, windowRecord->targetSpecific.windowHandle, &ust, &msc, &sbc) &&
	       (sbc < windowRecord->target_sbc)) {
		// Wanted 'sbc' value of target_sbc not yet reached -> The bufferswap isn't confirmed to be completed yet.
		// Need to wait a bit to release the cpu for other threads and processes, then repoll for swap completion.

		// Is the current video refresh cycle count 'msc' already at or past the expected count of swap completion?
		if (msc < windowRecord->lastSwaptarget_msc) {
			// No: At time 'ust', the 'msc' was at least one refresh cycle duration away from the earliest possible
			// count of swap completion. That means the swap won't complete earlier than at least one refresh
			// duration after 'ust'. Let's go to sleep and wait until almost until that point in time, aka
			// 'ust' + 1 video refresh duration:
			PsychWaitUntilSeconds(PsychOSMonotonicToRefTime(((double) ust) / PsychGetKernelTimebaseFrequencyHz()) + windowRecord->VideoRefreshInterval - 0.001);
		} else {
			// Yes: Swap completion can happen almost any time now. Sleep for a millisecond, then repoll:
			PsychYieldIntervalSeconds(0.001);
		}
		// Repoll for swap completion...
	}

	// Extension supported: Perform query and error check.
	if (!glXWaitForSbcOML(windowRecord->targetSpecific.privDpy, windowRecord->targetSpecific.windowHandle, targetSBC, &ust, &msc, &sbc)) {
		// OpenML supposed to be supported and in good working order according to startup check?
		if (windowRecord->gfxcaps & kPsychGfxCapSupportsOpenML) {
			// Yes. Then this is a new failure condition and we report it as such:
			if (PsychPrefStateGet_Verbosity() > 11) {
				printf("PTB-DEBUG:PsychOSGetSwapCompletionTimestamp: glXWaitForSbcOML() failed! Failing with rc = -2.\n");
			}
			return(-2);
		}
		
		// No. Failing this call is kind'a expected, so we don't make a big fuss on each
		// failure but return "unsupported" rc, so calling code can try fallback-path without
		// making much noise:
		return(-1);
	}
	
	// Check for valid return values: A zero ust or msc means failure, except for results from nouveau,
	// because there it is "expected" to get a constant zero return value for msc, at least when running
	// on top of a pre Linux-3.2 kernel:
	if ((ust == 0) || ((msc == 0) && !strstr((char*) glGetString(GL_VENDOR), "nouveau"))) {
		// Ohoh:
		if (PsychPrefStateGet_Verbosity() > 1) {
			printf("PTB-DEBUG:PsychOSGetSwapCompletionTimestamp: Invalid return values ust = %lld, msc = %lld from call with success return code (sbc = %lld)! Failing with rc = -2.\n", ust, msc, sbc);
			printf("PTB-DEBUG:PsychOSGetSwapCompletionTimestamp: This likely means a driver bug or malfunction, or that timestamping support has been disabled by the user in the driver!\n");
		}
		
		// Return with "failure" rc, so calling code can provide more error handling:
		return(-2);
	}

	// Success. Translate ust into system time in seconds:
	if (tSwap) *tSwap = PsychOSMonotonicToRefTime(((double) ust) / PsychGetKernelTimebaseFrequencyHz());

	// If we are running on a slightly incomplete nouveau-kms driver which always returns a zero msc,
	// we need to get good ust,msc,sbc values for later use as reference and as return value via an
	// extra roundtrip to the kernel. The most important info, the swap completion timestamp, aka ust
	// as returned from glXWaitForSbcOML() has already been converted into GetSecs() timebase and returned
	// in tSwap, so it is ok to overwrite ust here:
	if (msc == 0) {
		if (!glXGetSyncValuesOML(windowRecord->targetSpecific.privDpy, windowRecord->targetSpecific.windowHandle, &ust, &msc, &sbc)) {
			// Ohoh:
			if (PsychPrefStateGet_Verbosity() > 11) {
				printf("PTB-DEBUG:PsychOSGetSwapCompletionTimestamp: Invalid return values ust = %lld, msc = %lld from glXGetSyncValuesOML() call with success return code (sbc = %lld)! Failing with rc = -1.\n", ust, msc, sbc);
			}
		
			// Return with "unsupported" rc, so calling code can try fallback-path:
			return(-1);
		}
	}

	// Update cached reference values for future swaps:
	windowRecord->reference_ust = ust;
	windowRecord->reference_msc = msc;
	windowRecord->reference_sbc = sbc;

	if (PsychPrefStateGet_Verbosity() > 11) printf("PTB-DEBUG:PsychOSGetSwapCompletionTimestamp: Success! refust = %lld, refmsc = %lld, refsbc = %lld.\n", ust, msc, sbc);
	#endif
	
	// Return msc of swap completion:
	return(msc);
}

/* PsychOSInitializeOpenML() - Linux specific function.
 *
 * Performs basic initialization of the OpenML OML_sync_control extension.
 * Performs basic and extended correctness tests and disables extension if it
 * is unreliable, or enables workarounds for partially broken extensions.
 *
 * Called from PsychDetectAndAssignGfxCapabilities() as part of the PsychOpenOffscreenWindow()
 * procedure for a window with OpenML support.
 *
 */
void PsychOSInitializeOpenML(PsychWindowRecordType *windowRecord)
{
	#ifdef GLX_OML_sync_control

	psych_int64 ust, msc, sbc, oldmsc, oldust, finalmsc;
	psych_bool failed = FALSE;
	
	// Enable rendering context of window:
	PsychSetGLContext(windowRecord);

	// Perform a wait for 3 video refresh cycles to get valid (ust,msc,sbc)
	// values for initialization of windowRecord's cached values:
	if (!glXGetSyncValuesOML(windowRecord->targetSpecific.privDpy, windowRecord->targetSpecific.windowHandle, &ust, &msc, &sbc) || (msc == 0) ||
		!glXWaitForMscOML(windowRecord->targetSpecific.privDpy, windowRecord->targetSpecific.windowHandle, msc + 3, 0, 0, &ust, &msc, &sbc) || (ust == 0)) {
		
		// Basic OpenML functions failed?!? Not good! Disable OpenML swap scheduling:
		windowRecord->gfxcaps &= ~kPsychGfxCapSupportsOpenML;

		// OpenML timestamping in PsychOSGetSwapCompletionTimestamp() and PsychOSGetVBLTimeAndCount() disabled:
		windowRecord->specialflags |= kPsychOpenMLDefective;

		// Warn user:
		if (PsychPrefStateGet_Verbosity() > 1) {
			printf("PTB-WARNING: At least one test call for OpenML OML_sync_control extension failed! Will disable OpenML and revert to fallback implementation.\n");
		}

		return;
	}

	// Have a valid (ust, msc) baseline. Store it in windowRecord for future use:
	windowRecord->reference_ust = ust;
	windowRecord->reference_msc = msc;
	windowRecord->reference_sbc = sbc;

	// Perform correctness test for glXGetSyncValuesOML() over a time span
	// of 6 video refresh cycles. This checks for a limitation that is present
	// in all shipping Linux kernels up to at least version 2.6.36, possibly
	// also in 2.6.37 depending on MK's progress with this feature:
	finalmsc = msc + 6;
	oldmsc = msc;
	oldust = ust;
	
	while ((msc < finalmsc) && !failed) {
		// Wait a quarter millisecond:
		PsychWaitIntervalSeconds(0.000250);
		
		// Query current (msc, ust):
		if (!glXGetSyncValuesOML(windowRecord->targetSpecific.privDpy, windowRecord->targetSpecific.windowHandle, &ust, &msc, &sbc)) {
			// Query failed!
			failed = TRUE;
		}
		
		// Has msc changed since last query due to a regular msc increment, i.e., a new video refresh interval?
		if (msc != oldmsc) {
			// Yes. Update reference values for test:
			oldmsc = msc;
			oldust = ust;
		}
		
		// ust must be equal to oldust at this point, either because a msc increment has updated
		// the ust for the new vblank interval in lock-step and our code above has updated oldust
		// accordingly, or because no msc increment has happened, in which case ust should stay
		// unchanged as well, ie., ust == oldust. If ust and oldust are different then that means
		// that ust has changed its value in the middle of a refresh interval without an intervening
		// vblank. This would happen if glXGetSyncValuesOML() is defective and doesn't return ust
		// timestamps locked to vblank / msc increments, but simply system time values.
		if (ust != oldust) {
			// Failure of glXGetSyncValuesOML()! This is a broken implementation which needs
			// our workaround:
			failed = TRUE;			
		}

		// Repeat test loop:
	}
	
	// Failed or succeeded?
	if (failed) {
		// Failed! Enable workaround and optionally inform user:
		windowRecord->specialflags |= kPsychNeedOpenMLWorkaround1;
		
		if (PsychPrefStateGet_Verbosity() > 1) {
			printf("PTB-INFO: OpenML OML_sync_control implementation with problematic glXGetSyncValuesOML() function detected. Enabling workaround for ok performance.\n");
		}
	}
	#else
		// Disable extension:
		windowRecord->gfxcaps &= ~kPsychGfxCapSupportsOpenML;	
	#endif

	return;
}

/*
    PsychOSScheduleFlipWindowBuffers()
    
    Schedules a double buffer swap operation for given window at a given
	specific target time or target refresh count in a specified way.
	
	This uses OS specific API's and algorithms to schedule the asynchronous
	swap. This function is optional, target platforms are free to not implement
	it but simply return a "not supported" status code.
	
	Arguments:
	
	windowRecord - The window to be swapped.
	tWhen        - Requested target system time for swap. Swap shall happen at first
				   VSync >= tWhen.
	targetMSC	 - If non-zero, specifies target msc count for swap. Overrides tWhen.
	divisor, remainder - If set to non-zero, msc at swap must satisfy (msc % divisor) == remainder.
	specialFlags - Additional options, a bit field consisting of single bits that can be or'ed together:
				   1 = Constrain swaps to even msc values, 2 = Constrain swaps to odd msc values. (Used for frame-seq. stereo field selection)
	
	Return value:
	 
	Value greater than or equal to zero on success: The target msc for which swap is scheduled.
	Negative value: Error. Function failed. -1 == Function unsupported on current system configuration.
	-2 ... -x == Error condition.
	
*/
psych_int64 PsychOSScheduleFlipWindowBuffers(PsychWindowRecordType *windowRecord, double tWhen, psych_int64 targetMSC, psych_int64 divisor, psych_int64 remainder, unsigned int specialFlags)
{
	psych_int64 ust, msc, sbc, rc;
	double tNow, tMsc;
	
	// Linux: If this is implemented then it is implemented via the OpenML OML_sync_control extension.
	// Is the extension supported by the system and enabled by Psychtoolbox? If not, we return
	// a "not-supported" status code of -1 and turn into a no-op:
	if (!(windowRecord->gfxcaps & kPsychGfxCapSupportsOpenML)) return(-1);

	// Extension supported and enabled. Use it.
	#ifdef GLX_OML_sync_control

	// Enable rendering context of window:
	PsychSetGLContext(windowRecord);
	
	// According to OpenML spec, a glFlush() isn't implicitely performed by
	// glXSwapBuffersMscOML(). Therefore need to do it ourselves, although
	// some implementations may do it anyway:
	if (!windowRecord->PipelineFlushDone) glFlush();
	windowRecord->PipelineFlushDone = TRUE;

	// Non-Zero targetMSC provided to directy specify the msc on which swap should happen?
	// If so, then we can skip computation and directly call with that targetMSC:
	if (targetMSC == 0) {
		// No: targetMSC shall be computed from given tWhen system target time.
		// Get current (msc,ust) reference values for computation.
		
		// Get current values for (msc, ust, sbc) the textbook way: Return error code -2 on failure:
		if (!glXGetSyncValuesOML(windowRecord->targetSpecific.privDpy, windowRecord->targetSpecific.windowHandle, &ust, &msc, &sbc)) return(-2);
		
		// glXGetSyncValuesOML() known to return totally bogus ust timestamps? Or ust <= 0 returned,
		// which means a temporary (EAGAIN style) failure?
		if ((windowRecord->specialflags & kPsychNeedOpenMLWorkaround1) || (ust <= 0)) {
			// Useless ust returned. We need to recover a useable reference (msc, ust) pair via
			// trickery instead. Check if tWhen is at least 4 video refresh cycles in the future.
			if ((ust <= 0) && (PsychPrefStateGet_Verbosity() > 11)) printf("PTB-DEBUG:PsychOSScheduleFlipWindowBuffers: Invalid ust %lld returned by query. Current msc = %lld.\n", ust, msc);

			PsychGetAdjustedPrecisionTimerSeconds(&tNow);
			if (((tWhen - tNow) / windowRecord->VideoRefreshInterval) > 4.0) {
				// Yes. We have some time until deadline. Use a blocking wait for at
				// least 2 video refresh cycles. glXWaitForMscOML() doesn't have known
				// issues iff it has to wait for a msc that is in the future, ie., it has
				// to perform a blocking wait. In that case it will return a valid (msc, ust)
				// pair on return from blocking wait. Wait until msc+2 is reached and retrieve
				// updated (msc, ust):
				if (PsychPrefStateGet_Verbosity() > 11) printf("PTB-DEBUG:PsychOSScheduleFlipWindowBuffers: glXWaitForMscOML until msc = %lld, now msc = %lld.\n", msc + 2, msc);
				if (!glXWaitForMscOML(windowRecord->targetSpecific.privDpy, windowRecord->targetSpecific.windowHandle, msc + 2, 0, 0, &ust, &msc, &sbc)) return(-3);
			}
			else {
				// No. Swap deadline is too close to current time. We have no option other than
				// simply using the last cached values in our windowRecord and hoping that they
				// will be good enough:
				ust = windowRecord->reference_ust;
				msc = windowRecord->reference_msc;
				sbc = windowRecord->reference_sbc;
			}
		}
		
		// Have a valid (ust, msc) baseline. Store it in windowRecord for future use:
		windowRecord->reference_ust = ust;
		windowRecord->reference_msc = msc;
		windowRecord->reference_sbc = sbc;
		
		// Compute targetMSC for given baseline and target time tWhen:
		tMsc = PsychOSMonotonicToRefTime(((double) ust) / PsychGetKernelTimebaseFrequencyHz());
		targetMSC = msc + ((psych_int64)(floor((tWhen - tMsc) / windowRecord->VideoRefreshInterval) + 1));
	}
	
	// Clamp targetMSC to a positive non-zero value:
	if (targetMSC <= 0) targetMSC = 1;

	// Swap at specific even or odd frame requested? This is useful for frame-sequential stereo
	// presentation that shall start its presentation at a specific eye-view:
	if (specialFlags & (0x1 | 0x2)) {
		// Yes. Setup (divisor,remainder) constraint so that
		// 0x1 maps to even target frames, and 0x2 maps to odd
		// target frames:
		divisor = 2;
		remainder = (specialFlags & 0x1) ? 0 : 1;
		// Make sure initial targetMSC obeys (divisor,remainder) constraint:
		targetMSC += (targetMSC % divisor == remainder) ? 0 : 1; 
	}

	if (PsychPrefStateGet_Verbosity() > 12) printf("PTB-DEBUG:PsychOSScheduleFlipWindowBuffers: Submitting swap request for targetMSC = %lld, divisor = %lld, remainder = %lld.\n", targetMSC, divisor, remainder);

	// Ok, we have a valid final targetMSC. Schedule a bufferswap for that targetMSC, taking a potential
	// (divisor, remainder) constraint into account:
	rc = glXSwapBuffersMscOML(windowRecord->targetSpecific.privDpy, windowRecord->targetSpecific.windowHandle, targetMSC, divisor, remainder);

	// Failed? Return -4 error code if so:
	if (rc == -1) return(-4);

	// Keep track of target_sbc and targetMSC, who knows for what they might be good for?
	windowRecord->target_sbc = rc;
	windowRecord->lastSwaptarget_msc = targetMSC;

	#else
		// No op branch in case OML_sync_control isn't enabled at compile time:
		return(-1);
	#endif

	// Successfully scheduled the swap request: Return targetMSC for which it was scheduled:
	return(targetMSC);
}

/*
    PsychOSFlipWindowBuffers()
    
    Performs OS specific double buffer swap call.
*/
void PsychOSFlipWindowBuffers(PsychWindowRecordType *windowRecord)
{
	// Execute OS neutral bufferswap code first:
	PsychExecuteBufferSwapPrefix(windowRecord);
	
	// Trigger the "Front <-> Back buffer swap (flip) (on next vertical retrace)":
	glXSwapBuffers(windowRecord->targetSpecific.privDpy, windowRecord->targetSpecific.windowHandle);
	windowRecord->target_sbc = 0;
}

/* Enable/disable syncing of buffer-swaps to vertical retrace. */
void PsychOSSetVBLSyncLevel(PsychWindowRecordType *windowRecord, int swapInterval)
{
  int error, myinterval;

  // Enable rendering context of window:
  PsychSetGLContext(windowRecord);

  // Store new setting also in internal helper variable, e.g., to allow workarounds to work:
  windowRecord->vSynced = (swapInterval > 0) ? TRUE : FALSE;

  // Try to set requested swapInterval if swap-control extension is supported on
  // this Linux machine. Otherwise this will be a no-op...
  // Note: On Mesa, glXSwapIntervalSGI() is actually a redirected call to glXSwapIntervalMESA()!
  if (glXSwapIntervalSGI) {
	  error = glXSwapIntervalSGI(swapInterval);
	  if (error) {
		  if (PsychPrefStateGet_Verbosity()>1) printf("\nPTB-WARNING: FAILED to %s synchronization to vertical retrace!\n\n", (swapInterval > 0) ? "enable" : "disable");
	  }
  }

  // If Mesa query is supported, double-check if the system accepted our settings:
  if (glXGetSwapIntervalMESA) {
	  myinterval = glXGetSwapIntervalMESA();
	  if (myinterval != swapInterval) {
		  if (PsychPrefStateGet_Verbosity()>1) printf("\nPTB-WARNING: FAILED to %s synchronization to vertical retrace (System ignored setting [Req %i != Actual %i])!\n\n", (swapInterval > 0) ? "enable" : "disable", swapInterval, myinterval);
	  }
  }
  
  return;
}

/*
    PsychOSSetGLContext()
    
    Set the window to which GL drawing commands are sent.  
*/
void PsychOSSetGLContext(PsychWindowRecordType *windowRecord)
{
  if (glXGetCurrentContext() != windowRecord->targetSpecific.contextObject) {
    if (glXGetCurrentContext() != NULL) {
      // We need to glFlush the context before switching, otherwise race-conditions may occur:
      glFlush();
      
      // Need to unbind any FBO's in old context before switch, otherwise bad things can happen...
      if (glBindFramebufferEXT) glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
    }
    
    // Switch to new context:
    glXMakeCurrent(windowRecord->targetSpecific.deviceContext, windowRecord->targetSpecific.windowHandle, windowRecord->targetSpecific.contextObject);    
  }
}

/*
    PsychOSUnsetGLContext()
    
    Clear the drawing context.  
*/
void PsychOSUnsetGLContext(PsychWindowRecordType* windowRecord)
{
	if (glXGetCurrentContext() != NULL) {
		// We need to glFlush the context before switching, otherwise race-conditions may occur:
		glFlush();
		
		// Need to unbind any FBO's in old context before switch, otherwise bad things can happen...
		if (glBindFramebufferEXT) glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
    }
	
	glXMakeCurrent(windowRecord->targetSpecific.deviceContext, None, NULL);
}

/* Same as PsychOSSetGLContext() but for selecting userspace rendering context,
 * optionally copying state from PTBs context.
 */
void PsychOSSetUserGLContext(PsychWindowRecordType *windowRecord, psych_bool copyfromPTBContext)
{
  // Child protection:
  if (windowRecord->targetSpecific.glusercontextObject == NULL) PsychErrorExitMsg(PsychError_user,"GL Userspace context unavailable! Call InitializeMatlabOpenGL *before* Screen('OpenWindow')!");
  
  if (copyfromPTBContext) {
    // This unbind is probably not needed on X11/GLX, but better safe than sorry...
    glXMakeCurrent(windowRecord->targetSpecific.deviceContext, None, NULL);

    // Copy render context state:
    glXCopyContext(windowRecord->targetSpecific.deviceContext, windowRecord->targetSpecific.contextObject, windowRecord->targetSpecific.glusercontextObject, GL_ALL_ATTRIB_BITS);
  }
  
  // Setup new context if it isn't already setup. -> Avoid redundant context switch.
  if (glXGetCurrentContext() != windowRecord->targetSpecific.glusercontextObject) {
    glXMakeCurrent(windowRecord->targetSpecific.deviceContext, windowRecord->targetSpecific.windowHandle, windowRecord->targetSpecific.glusercontextObject);
  }
}

/* PsychOSSetupFrameLock - Check if framelock / swaplock support is available on
 * the given graphics system implementation and try to enable it for the given
 * pair of onscreen windows.
 *
 * If possible, will try to add slaveWindow to the swap group and/or swap barrier
 * of which masterWindow is already a member, putting slaveWindow into a swap-lock
 * with the masterWindow. If masterWindow isn't yet part of a swap group, create a
 * new swap group and attach masterWindow to it, before joining slaveWindow into the
 * new group. If masterWindow is part of a swap group and slaveWindow is NULL, then
 * remove masterWindow from the swap group.
 *
 * The swap lock mechanism used is operating system and GPU dependent. Many systems
 * will not support framelock/swaplock at all.
 *
 * Returns TRUE on success, FALSE on failure.
 */
psych_bool PsychOSSetupFrameLock(PsychWindowRecordType *masterWindow, PsychWindowRecordType *slaveWindow)
{
	GLuint maxGroups, maxBarriers, targetGroup;
	psych_bool rc = FALSE;
	
	// GNU/Linux: Try NV_swap_group support first, then SGI swap group support.

	// NVidia swap group extension supported?
	if((glxewIsSupported("GLX_NV_swap_group") || glewIsSupported("GLX_NV_swap_group")) && (NULL != glXQueryMaxSwapGroupsNV)) {
		// Yes. Check if given GPU really supports it:
		if (PsychPrefStateGet_Verbosity() > 5) printf("PTB-DEBUG: NV_swap_group supported. Querying available groups...\n");

		if (glXQueryMaxSwapGroupsNV(masterWindow->targetSpecific.deviceContext, PsychGetXScreenIdForScreen(masterWindow->screenNumber), &maxGroups, &maxBarriers) && (maxGroups > 0)) {
			// Yes. What to do?
			if (PsychPrefStateGet_Verbosity() > 5) printf("PTB-DEBUG: NV_swap_group supported. Implementation supports up to %i swap groups. Trying to join or unjoin group.\n", maxGroups);

			if (NULL == slaveWindow) {
				// Asked to remove master from swap group:
				glXJoinSwapGroupNV(masterWindow->targetSpecific.deviceContext, masterWindow->targetSpecific.windowHandle, 0);
				masterWindow->swapGroup = 0;
				return(TRUE);
			}
			else {
				// Non-NULL slaveWindow: Shall attach to swap group.
				// Master already part of a swap group?
				if (0 == masterWindow->swapGroup) {
					// Nope. Try to attach it to first available one:
					targetGroup = (GLuint) PsychFindFreeSwapGroupId(maxGroups);
					
					if ((targetGroup == 0) || !glXJoinSwapGroupNV(masterWindow->targetSpecific.deviceContext, masterWindow->targetSpecific.windowHandle, targetGroup)) {
						// Failed!
						if (PsychPrefStateGet_Verbosity() > 1) {
							printf("PTB-WARNING: Tried to enable framelock support for master-slave window pair, but masterWindow failed to join swapgroup %i! Skipped.\n", targetGroup);
						}
						
						goto try_sgi_swapgroup;
					}
					
					// Sucess for master!
					masterWindow->swapGroup = targetGroup;
				}
				
				// Now try to join the masters swapgroup with the slave:
				if (!glXJoinSwapGroupNV(slaveWindow->targetSpecific.deviceContext, slaveWindow->targetSpecific.windowHandle,  masterWindow->swapGroup)) {
					// Failed!
					if (PsychPrefStateGet_Verbosity() > 1) {
						printf("PTB-WARNING: Tried to enable framelock support for master-slave window pair, but slaveWindow failed to join swapgroup %i of master! Skipped.\n", masterWindow->swapGroup);
					}
					
					goto try_sgi_swapgroup;
				}
				
				// Success! Now both windows are in a common swapgroup and framelock should work!
				slaveWindow->swapGroup = masterWindow->swapGroup;
				
				if (PsychPrefStateGet_Verbosity() > 1) {
					printf("PTB-INFO: Framelock support for master-slave window pair via NV_swap_group extension enabled! Joined swap group %i.\n", masterWindow->swapGroup);
				}
				
				return(TRUE);
			}
		}
	}

// If we reach this point, then NV_swap groups are unsupported, or setup failed.
try_sgi_swapgroup:

	// Try if we have more luck with SGIX_swap_group extension:
	if (PsychPrefStateGet_Verbosity() > 5) printf("PTB-DEBUG: NV_swap_group unsupported or join operation failed. Trying GLX_SGIX_swap_group support...\n");

	// SGIX swap group extension supported?
	if((glxewIsSupported("GLX_SGIX_swap_group") || glewIsSupported("GLX_SGIX_swap_group")) && (NULL != glXJoinSwapGroupSGIX)) {
		// Yes. What to do?
		if (NULL == slaveWindow) {
			// Asked to remove master from swap group:
			glXJoinSwapGroupSGIX(masterWindow->targetSpecific.deviceContext, masterWindow->targetSpecific.windowHandle, None);
			masterWindow->swapGroup = 0;
			return(TRUE);
		}
		else {
			// Non-NULL slaveWindow: Shall attach to swap group.

			// Sucess for master by definition. Master is member of its own swapgroup, obviously...
			masterWindow->swapGroup = 1;
			
			// Now try to join the masters swapgroup with the slave. This can't fail in a non-fatal way.
			// Either it succeeds, or the whole runtime will abort with some GLX command stream error :-I
			glXJoinSwapGroupSGIX(slaveWindow->targetSpecific.deviceContext, slaveWindow->targetSpecific.windowHandle,  masterWindow->targetSpecific.windowHandle);
			
			// Success! Now both windows are in a common swapgroup and framelock should work!
			slaveWindow->swapGroup = masterWindow->swapGroup;
			
			if (PsychPrefStateGet_Verbosity() > 1) {
				printf("PTB-INFO: Framelock support for master-slave window pair via GLX_SGIX_swap_group extension enabled!\n");
			}
			
			return(TRUE);
		}
	}
	
	if (PsychPrefStateGet_Verbosity() > 5) printf("PTB-DEBUG: NV_swap_group and GLX_SGIX_swap_group unsupported or join operations failed.\n");
	
	return(rc);
}

// Perform OS specific processing of Window events:
void PsychOSProcessEvents(PsychWindowRecordType *windowRecord, int flags)
{
	Window rootRet;
	unsigned int depth_return, border_width_return, w, h;
	int x, y;

	// Trigger event queue dispatch processing for GUI windows:
	if (windowRecord == NULL) {
		// No op, so far...
		return;
	}
	
	// GUI windows need to behave GUIyee:
	if ((windowRecord->specialflags & kPsychGUIWindow) && PsychIsOnscreenWindow(windowRecord)) {
		// Update windows rect and globalrect, based on current size and location:
		XGetGeometry(windowRecord->targetSpecific.deviceContext, windowRecord->targetSpecific.xwindowHandle, &rootRet, &x, &y,
			     &w, &h, &border_width_return, &depth_return);
		XTranslateCoordinates(windowRecord->targetSpecific.deviceContext, windowRecord->targetSpecific.xwindowHandle, rootRet,
				      0,0, &x, &y, &rootRet);
		PsychMakeRect(windowRecord->globalrect, x, y, x + (int) w - 1, y + (int) h - 1);
		PsychNormalizeRect(windowRecord->globalrect, windowRecord->rect);
		PsychSetupClientRect(windowRecord);
		PsychSetupView(windowRecord, FALSE);
	}
}

psych_bool PsychOSSwapCompletionLogging(PsychWindowRecordType *windowRecord, int cmd, int aux1)
{
	const char *FieldNames[]={ "OnsetTime", "OnsetVBLCount", "SwapbuffersCount", "SwapType" };
	const int  fieldCount = 4;
	PsychGenericScriptType	*s;
	unsigned long glxmask = 0;
	XEvent evt;
	int scrnum;

	if (cmd == 0 || cmd == 1) {
		// Check if GLX_INTEL_swap_event extension is supported. Enable/Disable swap completion event
		// delivery for our window, if so:
		scrnum = PsychGetXScreenIdForScreen(windowRecord->screenNumber);
		if (useGLX13 && strstr(glXQueryExtensionsString(windowRecord->targetSpecific.deviceContext, scrnum), "GLX_INTEL_swap_event")) {
			glXSelectEvent(windowRecord->targetSpecific.deviceContext, windowRecord->targetSpecific.windowHandle, (unsigned long) ((cmd == 1) ? GLX_BUFFER_SWAP_COMPLETE_INTEL_MASK : 0));
			return(TRUE);
		} else {
			return(FALSE);
		}
	}

	if (cmd == 2) {
		// Experimental support for INTEL_swap_event extension enabled? Process swap events if so:
		if (useGLX13) {
			glXGetSelectedEvent(windowRecord->targetSpecific.deviceContext, windowRecord->targetSpecific.windowHandle, &glxmask);
			if (glxmask & GLX_BUFFER_SWAP_COMPLETE_INTEL_MASK) {
				// INTEL_swap_event delivery enabled and requested. Try to fetch all pending ones for this window:			
				if (XCheckTypedWindowEvent(windowRecord->targetSpecific.deviceContext, windowRecord->targetSpecific.xwindowHandle, glx_event_base + GLX_BufferSwapComplete, &evt)) {
					// Cast to proper event type:
					GLXBufferSwapComplete *sce = (GLXBufferSwapComplete*) &evt;
					if (PsychPrefStateGet_Verbosity() > 5) {
						printf("SWAPEVENT: OurWin=%i ust = %lld, msc = %lld, sbc = %lld, type %s.\n", (int) (sce->drawable == windowRecord->targetSpecific.xwindowHandle),
						       sce->ust, sce->msc, sce->sbc, (sce->event_type == GLX_FLIP_COMPLETE_INTEL) ? "PAGEFLIP" : "BLIT/EXCHANGE");
					}

					PsychAllocOutStructArray(aux1, FALSE, 1, fieldCount, FieldNames, &s);
					PsychSetStructArrayDoubleElement("OnsetTime", 0, PsychOSMonotonicToRefTime(((double) sce->ust) / PsychGetKernelTimebaseFrequencyHz()), s);
					PsychSetStructArrayDoubleElement("OnsetVBLCount", 0, (double) sce->msc, s);
					PsychSetStructArrayDoubleElement("SwapbuffersCount", 0, (double) sce->sbc, s);
					switch (sce->event_type) {
						case GLX_FLIP_COMPLETE_INTEL:
							PsychSetStructArrayStringElement("SwapType", 0, "Pageflip", s);
						break;

						case GLX_EXCHANGE_COMPLETE_INTEL:
							PsychSetStructArrayStringElement("SwapType", 0, "Exchange", s);
						break;

						case GLX_COPY_COMPLETE_INTEL:
							PsychSetStructArrayStringElement("SwapType", 0, "Copy", s);
						break;

						default:
							PsychSetStructArrayStringElement("SwapType", 0, "Unknown", s);
					}
				}
			}
		}
	}
}