Source

Fireplace / FPWindowManager.m

Full commit
  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
#import <X11/Xlib.h>
#import <X11/extensions/Xcomposite.h>
#import <X11/extensions/Xfixes.h>
#import <X11/extensions/shape.h>
#import <GL/gl.h>
#import <unistd.h>
#import <fcntl.h>
#import "FPWindowManager.h"
#import "FPX11Display.h"
#import "FPManagedWindow.h"
#import "GLConfiguration.h"

static int attrListSgl[] = {
    GLX_RGBA, GLX_RED_SIZE, 4,
    GLX_GREEN_SIZE, 4,
    GLX_BLUE_SIZE, 4,
    GLX_DEPTH_SIZE, 16,
    None};

static int attrListDbl[] = { 
    GLX_RGBA, GLX_DOUBLEBUFFER,
    GLX_RED_SIZE, 4,
    GLX_GREEN_SIZE, 4,
    GLX_BLUE_SIZE, 4,
    GLX_DEPTH_SIZE, 16,
    None };

static const int fbconfig[] = {
    GLX_BIND_TO_TEXTURE_RGBA_EXT, True,
#if !VBOXCOMPAT
    GLX_DRAWABLE_TYPE, GLX_PIXMAP_BIT,
#endif
#if USE_TEXTURE_RECTANGLE
    GLX_BIND_TO_TEXTURE_TARGETS_EXT, GLX_TEXTURE_RECTANGLE_BIT_EXT,
#else
    GLX_BIND_TO_TEXTURE_TARGETS_EXT, GLX_TEXTURE_2D_BIT_EXT,
#endif
    GLX_Y_INVERTED_EXT, GLX_DONT_CARE,
    None
};

static void x11ErrorHandler(Display * dpy, XErrorEvent * errEvt)
{
	NSLog(@"An X error has occurred");
}

@implementation FPWindowManager
-(id)init
{
	FPX11Display * mainDisplay;
	Display * display;

	self = [super init];
	if(!self)
		return nil;

	_managedWindows = [NSMutableArray new];	
	
	mainDisplay = [FPX11Display mainDisplay];	
	display = [mainDisplay display];

	/////////////////////

	int compositeBaseEvent = 0, compositeBaseError = 0;
	if(!XCompositeQueryExtension(display, &compositeBaseEvent, &compositeBaseError))
	{
		NSLog(@"Composite extension not supported!");
		[self release];
		return nil;
	}

	int compositeVersionMajor = 0, compositeVersionMinor = 0;
	XCompositeQueryVersion(display, &compositeVersionMajor, &compositeVersionMinor);
	NSLog(@"Composite extension version: %d.%d", compositeVersionMajor, compositeVersionMinor);

	///////////////////

	XSetErrorHandler(x11ErrorHandler);

	///////////////////

	[self _openStageWindow];

	XMapRaised(display, _stage);

//	XCompositeRedirectSubwindows (display, _root, CompositeRedirectAutomatic);
	XCompositeRedirectSubwindows(display, _root, CompositeRedirectManual);
	XSelectInput (display, _root, SubstructureNotifyMask);

	_overlay = XCompositeGetOverlayWindow (display, _root);

	XReparentWindow (display, _stage, _overlay, 0, 0);
//	XSelectInput (display, _stage, ExposureMask);

	[self _allowInputPassthrough:_stage];
	[self _allowInputPassthrough:_overlay];
	
	[[FPEventLoop mainLoop] addEventHandler:self];
	return self;
}

-(void)dealloc
{
	FPX11Display * mainDisplay = [FPX11Display mainDisplay];	
	Display * display = [mainDisplay display];

	XFree(_glxFBConfigs);
	[mainDisplay makeCurrentContext:NULL
	                       onWindow:None
	                    contextName:@"NULL"];
	glXDestroyContext(display, _glxContext);
	XDestroyWindow(display, _stage);
	XCompositeReleaseOverlayWindow(display, _overlay);
	[_managedWindows release];

	[[FPEventLoop mainLoop] removeEventHandler:self];
	[super dealloc];
}
-(void)_execCommand:(NSString*)command
{
	FPX11Display * mainDisplay = [FPX11Display mainDisplay];	
	Display * display = [mainDisplay display];
	if ((fcntl(ConnectionNumber(display), F_SETFD, 1)) == -1)
		NSLog(@"launching process: child cannot disinherit TCP fd");
	if(fork()==0)
	{
		if(execl([command UTF8String], [[command lastPathComponent] UTF8String], nil) == -1)	
		{
			NSLog(@"error launching process");
		}
		exit(0);
	}	
}
-(void)_allowInputPassthrough:(Window)window
{
	FPX11Display * mainDisplay = [FPX11Display mainDisplay];	
	Display * display = [mainDisplay display];

	XserverRegion region = XFixesCreateRegion (display, NULL, 0);
 
	XFixesSetWindowShapeRegion (display, window, ShapeBounding, 0, 0, 0);
	XFixesSetWindowShapeRegion (display, window, ShapeInput, 0, 0, region);

	XFixesDestroyRegion (display, region);
}
-(void)_openStageWindow
{
	// opens a GLX window ;)

	FPX11Display * mainDisplay = [FPX11Display mainDisplay];
	Display * display = [mainDisplay display];
	int screen = [mainDisplay screen];
	int width = [mainDisplay width];
	int height = [mainDisplay height];
	int depth = [mainDisplay depth];
	Visual * visual = [mainDisplay visual];
	Window rootWindow = [mainDisplay rootWindow];
	int borderWidth = 0;
	XSetWindowAttributes attr = {0};

#pragma unused(width)
#pragma unused(height)
#pragma unused(rootWindow)
#pragma unused(depth)
#pragma unused(visual)

	XVisualInfo *glxVisualInfo;
	Colormap glxColorMap;
	Window glxRootWindow;
	int glxWidth, glxHeight, glxDepth;
	Visual * glxVisual;
	
	////////	
	glxVisualInfo = _visualInfo = glXChooseVisual(display, screen, attrListDbl);
	if (glxVisualInfo == NULL)
	{
		glxVisualInfo = glXChooseVisual(display, screen, attrListSgl);
		_isVisualDoubleBuffered = NO;
		if(!glxVisualInfo)
		{
			[NSException raise:@"FPWindowManagerNoGLXVisual" format:@"Failed to get a GLX visual"];
		}
		NSLog(@"Note: only Singlebuffered Visual available!");
	}
	else
	{
		_isVisualDoubleBuffered = YES;
	}

	glxRootWindow = _root = [mainDisplay rootWindowForScreen:glxVisualInfo->screen];
	glxVisual = glxVisualInfo->visual;
	glxColorMap = XCreateColormap(
		display, 
		glxRootWindow, 
		glxVisual, 
		AllocNone);
	glxWidth = [mainDisplay widthForScreen:glxVisualInfo->screen];
	glxHeight = [mainDisplay heightForScreen:glxVisualInfo->screen];
	glxDepth = glxVisualInfo->depth;

	attr.colormap = glxColorMap;
	attr.border_pixel = 0;
	attr.event_mask = 
		StructureNotifyMask | FocusChangeMask | PointerMotionMask
                  | KeyPressMask | KeyReleaseMask | ButtonPressMask
                  | ButtonReleaseMask | PropertyChangeMask | ExposureMask;
	attr.override_redirect = true;

	_glxContext = glXCreateContext(display, glxVisualInfo, 0, GL_TRUE);

	///
	
	_stage = XCreateWindow(
		display, 
		_root,
		0, 0,
		glxWidth, glxHeight,
		borderWidth,
		glxDepth,
		InputOutput, // class
		glxVisual,
		CWBorderPixel | CWColormap | CWEventMask, // valuemask
		&attr
		);

	XSetStandardProperties(
		display, 
		_stage, 
		"Fireplace",
		"Fireplace",
		None, 
		NULL, 
		0, 
		NULL);

	[mainDisplay makeCurrentContext:_glxContext
	                       onWindow:_stage
	                    contextName:@"Stage"];
	
	///////////
		
	int c = 0;
	_glxFBConfigs = glXChooseFBConfig(display, screen, fbconfig, &c);
	if(!_glxFBConfigs)
	{
		// TODO: throw exception or return nil instead of exiting
		NSLog(@"No FBConfigs");
		exit(1);
	}
	
	///////////
	
	XGetGeometry(
		display, 
		_stage, 
		&_root, // dummy
		&_x, 
		&_y,
		&_width,
		&_height,
		&_borderWidth,
		&_depth);
	if(!glXIsDirect(display, _glxContext))
	{
		NSLog(@"No direct rendering");
	}
	_wasExposed = NO;
}

-(void)_addPreexistingWindows
{
	FPX11Display * mainDisplay = [FPX11Display mainDisplay];
	Display * display = [mainDisplay display];
	int screen = [mainDisplay screen];
	int width = [mainDisplay width];
	int height = [mainDisplay height];
	int depth = [mainDisplay depth];
	Visual * visual = [mainDisplay visual];
	Window rootWindow = [mainDisplay rootWindow];

	Window * children = NULL;
	unsigned int nChildren = 0;
	Window returningRootWindow = 0, returningParentWindow = 0;

	XQueryTree(display, rootWindow, &returningRootWindow, &returningParentWindow, &children, &nChildren);
	for(int i = 0; i < nChildren; i++)
	{
		Window * window = children[i];
		if(window != _stage && window != _root && window != _overlay)
		{
			FPManagedWindow * managedWindow = [[FPManagedWindow alloc] initWithWindow:window manager:self];
			[_managedWindows addObject:managedWindow];
			[managedWindow release];
		}
		
	}
}

-(void)handleXEvent:(XEvent)event
{
	NSLog(@"Event %d", event.type);
	switch(event.type)	
	{
		case Expose:
		if (event.xexpose.count != 0)
			break;
		NSLog(@"Expose");
		[self render];
		if(!_wasExposed)
		{
			[self _addPreexistingWindows];
			[self _execCommand:@"/usr/bin/xterm"];
		}
		_wasExposed = YES;

		
		break;

		case ConfigureNotify:
		NSLog(@"ConfigureNotify");
		break;
		
		case ClientMessage:
		NSLog(@"ClientMessage");
		break;
		
		case MapNotify:
		NSLog(@"Map notify");
		break;

		case ReparentNotify:
		NSLog(@"Reparent notify");
		break;

		case CreateNotify:
		NSLog(@"Create notify");
		if(event.xcreatewindow.window != _stage && event.xcreatewindow.window != _root && event.xcreatewindow.window != _overlay)
		{
			FPManagedWindow * managedWindow = [[FPManagedWindow alloc] initWithWindow:event.xcreatewindow.window manager:self];
			[_managedWindows addObject:managedWindow];
			[managedWindow release];
		}
		break;
	}
}

-(void)render
{
	FPX11Display * mainDisplay = [FPX11Display mainDisplay];
	Display * display = [mainDisplay display];
#if SWITCH_CONTEXTS
	[mainDisplay makeCurrentContext:_glxContext
	                       onWindow:_stage
	                    contextName:@"Stage"];
#endif

	XSync([[FPX11Display mainDisplay] display], False);
	NSLog(@"=============== NEXT FRAME ===========");
	NSLog(@"Starting with context %@", [mainDisplay glxContextName]);
	glDrawBuffer(GL_BACK);
	glViewport(0, 0, _width, _height);
	glClearColor(0.2,0.2,0.4,1);
	glClear(GL_COLOR_BUFFER_BIT);

	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	glOrtho(0, _width, _height, 0, 0, 1);
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();

	for(FPManagedWindow *managedWindow in _managedWindows)
	{
		NSLog(@"Window draw with context %@", [mainDisplay glxContextName]);
		[managedWindow drawWindow];		
		NSLog(@"Window drawn with context %@", [mainDisplay glxContextName]);
	}

#if 1
	glLoadIdentity();
	glDisable(GL_TEXTURE_2D);
	glPointSize(10);
	glColor3f(1,0,0);
	glBegin(GL_POINTS);
	glVertex3f(rand()%640, rand()%480, 0);	
	glEnd();
#endif	

#if SWITCH_CONTEXTS
	[mainDisplay makeCurrentContext:_glxContext
	                       onWindow:_stage
	                    contextName:@"Stage"];
#endif
	XSync([[FPX11Display mainDisplay] display], False);
	glFlush();
	
	if(_isVisualDoubleBuffered)
	{
		NSLog(@"SWAPPING BUFFERS");
		glXSwapBuffers([[FPX11Display mainDisplay] display], _stage);
	}
	glFinish();
	glXWaitGL();
	NSLog(@"Ending with context %@", [mainDisplay glxContextName]);
	
	/* vsync from KWin's scene_opengl in kdebase-3.90.1 */
#if VSYNC
	unsigned int sync;
        glFlush();
        glXGetVideoSync( &sync );
        glXWaitVideoSync( 2, ( sync + 1 ) % 2, &sync );
#else
	usleep(1000000/60 * 2); // 30fps
	//usleep(1000000/60 * 8); // 7.5fps
#endif
	/* end vsync */
}

/*
-(BOOL)_setupTexture
{
	int textureData[] = {
		255, 0, 0,     255, 255, 255,
		255, 255, 255, 0, 0, 0
	};

	GLuint _width = 2, _height = 2;
	GLuint _internalFormat = GL_RGBA;
        glGenTextures(1, &testTexture);

        GLuint errorID=glGetError();
        if(errorID != GL_NO_ERROR)
        {
                printf("GL ERROR: %d\n", (errorID));
                return NO;
        }
        glBindTexture(GL_TEXTURE_2D, testTexture);
        glTexImage2D(GL_TEXTURE_2D, 0, _internalFormat, (GLsizei)_width, (GLsizei)_height, 0, _internalFormat, GL_UNSIGNED_BYTE, textureData);
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

	return YES;	
}
*/

-(void)updateWithDeltaTime:(float)sec;
{

	if(_wasExposed)
		[self render];

}

-(void)stopManagingWindow:(FPManagedWindow*)managedWindow
{
	[_managedWindows removeObject:managedWindow];
}

-(XVisualInfo*)visualInfo
{
	return _visualInfo;
}
-(GLXFBConfig*)glxFBConfigs
{
	return _glxFBConfigs;
}
-(GLXContext)glxContext
{
	return _glxContext;
}
-(Window)stage
{
	return _stage;
}
@end


// TODO: study http://sidvind.com/wiki/Xlib_and_GLX:_Part_1