Blob


1 /*
2 * Some of the stuff in this file is not X-dependent and should be elsewhere.
3 */
4 #include <u.h>
5 #include "x11-inc.h"
6 #include <libc.h>
7 #include <draw.h>
8 #include <memdraw.h>
9 #include <keyboard.h>
10 #include <mouse.h>
11 #include <cursor.h>
12 #include "x11-memdraw.h"
13 #include "devdraw.h"
15 static void plan9cmap(void);
16 static int setupcmap(XWindow);
17 static XGC xgc(XDrawable, int, int);
19 Xprivate _x;
21 static int
22 xerror(XDisplay *d, XErrorEvent *e)
23 {
24 char buf[200];
26 if(e->request_code == 42) /* XSetInputFocus */
27 return 0;
28 if(e->request_code == 18) /* XChangeProperty */
29 return 0;
30 /*
31 * BadDrawable happens in apps that get resized a LOT,
32 * e.g. when KDE is configured to resize continuously
33 * during a window drag.
34 */
35 if(e->error_code == 9) /* BadDrawable */
36 return 0;
38 fprint(2, "X error: error_code=%d, request_code=%d, minor=%d disp=%p\n",
39 e->error_code, e->request_code, e->minor_code, d);
40 XGetErrorText(d, e->error_code, buf, sizeof buf);
41 fprint(2, "%s\n", buf);
42 return 0;
43 }
45 static int
46 xioerror(XDisplay *d)
47 {
48 /*print("X I/O error\n"); */
49 exit(0);
50 /*sysfatal("X I/O error\n");*/
51 abort();
52 return -1;
53 }
56 Memimage*
57 _xattach(char *label, char *winsize)
58 {
59 char *argv[2], *disp;
60 int i, havemin, height, mask, n, width, x, xrootid, y;
61 Rectangle r;
62 XClassHint classhint;
63 XDrawable pmid;
64 XPixmapFormatValues *pfmt;
65 XScreen *xscreen;
66 XSetWindowAttributes attr;
67 XSizeHints normalhint;
68 XTextProperty name;
69 XVisualInfo xvi;
70 XWindow xrootwin;
71 XWindowAttributes wattr;
72 XWMHints hint;
73 Atom atoms[2];
75 /*
76 if(XInitThreads() == 0){
77 fprint(2, "XInitThreads failed\n");
78 abort();
79 }
80 */
82 /*
83 * Connect to X server.
84 */
85 _x.display = XOpenDisplay(NULL);
86 if(_x.display == nil){
87 disp = getenv("DISPLAY");
88 werrstr("XOpenDisplay %s: %r", disp ? disp : ":0");
89 free(disp);
90 return nil;
91 }
92 _x.fd = ConnectionNumber(_x.display);
93 XSetErrorHandler(xerror);
94 XSetIOErrorHandler(xioerror);
95 xrootid = DefaultScreen(_x.display);
96 xrootwin = DefaultRootWindow(_x.display);
98 /*
99 * Figure out underlying screen format.
100 */
101 if(XMatchVisualInfo(_x.display, xrootid, 24, TrueColor, &xvi)
102 || XMatchVisualInfo(_x.display, xrootid, 24, DirectColor, &xvi)){
103 _x.vis = xvi.visual;
104 _x.depth = 24;
106 else
107 if(XMatchVisualInfo(_x.display, xrootid, 16, TrueColor, &xvi)
108 || XMatchVisualInfo(_x.display, xrootid, 16, DirectColor, &xvi)){
109 _x.vis = xvi.visual;
110 _x.depth = 16;
112 else
113 if(XMatchVisualInfo(_x.display, xrootid, 15, TrueColor, &xvi)
114 || XMatchVisualInfo(_x.display, xrootid, 15, DirectColor, &xvi)){
115 _x.vis = xvi.visual;
116 _x.depth = 15;
118 else
119 if(XMatchVisualInfo(_x.display, xrootid, 8, PseudoColor, &xvi)
120 || XMatchVisualInfo(_x.display, xrootid, 8, StaticColor, &xvi)){
121 if(_x.depth > 8){
122 werrstr("can't deal with colormapped depth %d screens",
123 _x.depth);
124 goto err0;
126 _x.vis = xvi.visual;
127 _x.depth = 8;
129 else{
130 _x.depth = DefaultDepth(_x.display, xrootid);
131 if(_x.depth != 8){
132 werrstr("can't understand depth %d screen", _x.depth);
133 goto err0;
135 _x.vis = DefaultVisual(_x.display, xrootid);
138 if(DefaultDepth(_x.display, xrootid) == _x.depth)
139 _x.usetable = 1;
141 /*
142 * _x.depth is only the number of significant pixel bits,
143 * not the total number of pixel bits. We need to walk the
144 * display list to find how many actual bits are used
145 * per pixel.
146 */
147 _x.chan = 0;
148 pfmt = XListPixmapFormats(_x.display, &n);
149 for(i=0; i<n; i++){
150 if(pfmt[i].depth == _x.depth){
151 switch(pfmt[i].bits_per_pixel){
152 case 1: /* untested */
153 _x.chan = GREY1;
154 break;
155 case 2: /* untested */
156 _x.chan = GREY2;
157 break;
158 case 4: /* untested */
159 _x.chan = GREY4;
160 break;
161 case 8:
162 _x.chan = CMAP8;
163 break;
164 case 15:
165 _x.chan = RGB15;
166 break;
167 case 16: /* how to tell RGB15? */
168 _x.chan = RGB16;
169 break;
170 case 24: /* untested (impossible?) */
171 _x.chan = RGB24;
172 break;
173 case 32:
174 _x.chan = XRGB32;
175 break;
179 if(_x.chan == 0){
180 werrstr("could not determine screen pixel format");
181 goto err0;
184 /*
185 * Set up color map if necessary.
186 */
187 xscreen = DefaultScreenOfDisplay(_x.display);
188 _x.cmap = DefaultColormapOfScreen(xscreen);
189 if(_x.vis->class != StaticColor){
190 plan9cmap();
191 setupcmap(xrootwin);
194 /*
195 * We get to choose the initial rectangle size.
196 * This is arbitrary. In theory we should read the
197 * command line and allow the traditional X options.
198 */
199 mask = 0;
200 x = 0;
201 y = 0;
202 if(winsize && winsize[0]){
203 if(parsewinsize(winsize, &r, &havemin) < 0)
204 sysfatal("%r");
205 }else{
206 /*
207 * Parse the various X resources. Thanks to Peter Canning.
208 */
209 char *screen_resources, *display_resources, *geom,
210 *geomrestype, *home, *file;
211 XrmDatabase database;
212 XrmValue geomres;
214 database = XrmGetDatabase(_x.display);
215 screen_resources = XScreenResourceString(xscreen);
216 if(screen_resources != nil){
217 XrmCombineDatabase(XrmGetStringDatabase(screen_resources), &database, False);
218 XFree(screen_resources);
221 display_resources = XResourceManagerString(_x.display);
222 if(display_resources == nil){
223 home = getenv("HOME");
224 if(home!=nil && (file=smprint("%s/.Xdefaults", home)) != nil){
225 XrmCombineFileDatabase(file, &database, False);
226 free(file);
228 free(home);
229 }else
230 XrmCombineDatabase(XrmGetStringDatabase(display_resources), &database, False);
232 geom = smprint("%s.geometry", label);
233 if(geom && XrmGetResource(database, geom, nil, &geomrestype, &geomres))
234 mask = XParseGeometry(geomres.addr, &x, &y, (uint*)&width, (uint*)&height);
235 free(geom);
237 if((mask & WidthValue) && (mask & HeightValue)){
238 r = Rect(0, 0, width, height);
239 }else{
240 r = Rect(0, 0, WidthOfScreen(xscreen)*3/4,
241 HeightOfScreen(xscreen)*3/4);
242 if(Dx(r) > Dy(r)*3/2)
243 r.max.x = r.min.x + Dy(r)*3/2;
244 if(Dy(r) > Dx(r)*3/2)
245 r.max.y = r.min.y + Dx(r)*3/2;
247 if(mask & XNegative){
248 x += WidthOfScreen(xscreen);
250 if(mask & YNegative){
251 y += HeightOfScreen(xscreen);
253 havemin = 0;
255 screenrect = Rect(0, 0, WidthOfScreen(xscreen), HeightOfScreen(xscreen));
256 windowrect = r;
258 memset(&attr, 0, sizeof attr);
259 attr.colormap = _x.cmap;
260 attr.background_pixel = ~0;
261 attr.border_pixel = 0;
262 _x.drawable = XCreateWindow(
263 _x.display, /* display */
264 xrootwin, /* parent */
265 x, /* x */
266 y, /* y */
267 Dx(r), /* width */
268 Dy(r), /* height */
269 0, /* border width */
270 _x.depth, /* depth */
271 InputOutput, /* class */
272 _x.vis, /* visual */
273 /* valuemask */
274 CWBackPixel|CWBorderPixel|CWColormap,
275 &attr /* attributes (the above aren't?!) */
276 );
278 /*
279 * Label and other properties required by ICCCCM.
280 */
281 memset(&name, 0, sizeof name);
282 if(label == nil)
283 label = "pjw-face-here";
284 name.value = (uchar*)label;
285 name.encoding = XA_STRING;
286 name.format = 8;
287 name.nitems = strlen((char*)name.value);
289 memset(&normalhint, 0, sizeof normalhint);
290 normalhint.flags = PSize|PMaxSize;
291 if(winsize && winsize[0]){
292 normalhint.flags &= ~PSize;
293 normalhint.flags |= USSize;
294 normalhint.width = Dx(r);
295 normalhint.height = Dy(r);
296 }else{
297 if((mask & WidthValue) && (mask & HeightValue)){
298 normalhint.flags &= ~PSize;
299 normalhint.flags |= USSize;
300 normalhint.width = width;
301 normalhint.height = height;
303 if((mask & WidthValue) && (mask & HeightValue)){
304 normalhint.flags |= USPosition;
305 normalhint.x = x;
306 normalhint.y = y;
310 normalhint.max_width = WidthOfScreen(xscreen);
311 normalhint.max_height = HeightOfScreen(xscreen);
313 memset(&hint, 0, sizeof hint);
314 hint.flags = InputHint|StateHint;
315 hint.input = 1;
316 hint.initial_state = NormalState;
318 memset(&classhint, 0, sizeof classhint);
319 classhint.res_name = label;
320 classhint.res_class = label;
322 argv[0] = label;
323 argv[1] = nil;
325 XSetWMProperties(
326 _x.display, /* display */
327 _x.drawable, /* window */
328 &name, /* XA_WM_NAME property */
329 &name, /* XA_WM_ICON_NAME property */
330 argv, /* XA_WM_COMMAND */
331 1, /* argc */
332 &normalhint, /* XA_WM_NORMAL_HINTS */
333 &hint, /* XA_WM_HINTS */
334 &classhint /* XA_WM_CLASSHINTS */
335 );
336 XFlush(_x.display);
338 if(havemin){
339 XWindowChanges ch;
341 memset(&ch, 0, sizeof ch);
342 ch.x = r.min.x;
343 ch.y = r.min.y;
344 XConfigureWindow(_x.display, _x.drawable, CWX|CWY, &ch);
345 /*
346 * Must pretend origin is 0,0 for X.
347 */
348 r = Rect(0,0,Dx(r),Dy(r));
350 /*
351 * Look up clipboard atom.
352 */
353 _x.clipboard = XInternAtom(_x.display, "CLIPBOARD", False);
354 _x.utf8string = XInternAtom(_x.display, "UTF8_STRING", False);
355 _x.targets = XInternAtom(_x.display, "TARGETS", False);
356 _x.text = XInternAtom(_x.display, "TEXT", False);
357 _x.compoundtext = XInternAtom(_x.display, "COMPOUND_TEXT", False);
358 _x.takefocus = XInternAtom(_x.display, "WM_TAKE_FOCUS", False);
359 _x.losefocus = XInternAtom(_x.display, "_9WM_LOSE_FOCUS", False);
360 _x.wmprotos = XInternAtom(_x.display, "WM_PROTOCOLS", False);
362 atoms[0] = _x.takefocus;
363 atoms[1] = _x.losefocus;
364 XChangeProperty(_x.display, _x.drawable, _x.wmprotos, XA_ATOM, 32,
365 PropModeReplace, (uchar*)atoms, 2);
367 /*
368 * Put the window on the screen, check to see what size we actually got.
369 */
370 XMapWindow(_x.display, _x.drawable);
371 XSync(_x.display, False);
373 if(!XGetWindowAttributes(_x.display, _x.drawable, &wattr))
374 fprint(2, "XGetWindowAttributes failed\n");
375 else if(wattr.width && wattr.height){
376 if(wattr.width != Dx(r) || wattr.height != Dy(r)){
377 r.max.x = wattr.width;
378 r.max.y = wattr.height;
380 }else
381 fprint(2, "XGetWindowAttributes: bad attrs\n");
383 /*
384 * Allocate our local backing store.
385 */
386 _x.screenr = r;
387 _x.screenpm = XCreatePixmap(_x.display, _x.drawable, Dx(r), Dy(r), _x.depth);
388 _x.nextscreenpm = _x.screenpm;
389 _x.screenimage = _xallocmemimage(r, _x.chan, _x.screenpm);
391 /*
392 * Allocate some useful graphics contexts for the future.
393 */
394 _x.gcfill = xgc(_x.screenpm, FillSolid, -1);
395 _x.gccopy = xgc(_x.screenpm, -1, -1);
396 _x.gcsimplesrc = xgc(_x.screenpm, FillStippled, -1);
397 _x.gczero = xgc(_x.screenpm, -1, -1);
398 _x.gcreplsrc = xgc(_x.screenpm, FillTiled, -1);
400 pmid = XCreatePixmap(_x.display, _x.drawable, 1, 1, 1);
401 _x.gcfill0 = xgc(pmid, FillSolid, 0);
402 _x.gccopy0 = xgc(pmid, -1, -1);
403 _x.gcsimplesrc0 = xgc(pmid, FillStippled, -1);
404 _x.gczero0 = xgc(pmid, -1, -1);
405 _x.gcreplsrc0 = xgc(pmid, FillTiled, -1);
406 XFreePixmap(_x.display, pmid);
408 return _x.screenimage;
410 err0:
411 /*
412 * Should do a better job of cleaning up here.
413 */
414 XCloseDisplay(_x.display);
415 return nil;
418 int
419 _xsetlabel(char *label)
421 XTextProperty name;
423 /*
424 * Label and other properties required by ICCCCM.
425 */
426 memset(&name, 0, sizeof name);
427 if(label == nil)
428 label = "pjw-face-here";
429 name.value = (uchar*)label;
430 name.encoding = XA_STRING;
431 name.format = 8;
432 name.nitems = strlen((char*)name.value);
434 XSetWMProperties(
435 _x.display, /* display */
436 _x.drawable, /* window */
437 &name, /* XA_WM_NAME property */
438 &name, /* XA_WM_ICON_NAME property */
439 nil, /* XA_WM_COMMAND */
440 0, /* argc */
441 nil, /* XA_WM_NORMAL_HINTS */
442 nil, /* XA_WM_HINTS */
443 nil /* XA_WM_CLASSHINTS */
444 );
445 XFlush(_x.display);
446 return 0;
449 /*
450 * Create a GC with a particular fill style and XXX.
451 * Disable generation of GraphicsExpose/NoExpose events in the GC.
452 */
453 static XGC
454 xgc(XDrawable d, int fillstyle, int foreground)
456 XGC gc;
457 XGCValues v;
459 memset(&v, 0, sizeof v);
460 v.function = GXcopy;
461 v.graphics_exposures = False;
462 gc = XCreateGC(_x.display, d, GCFunction|GCGraphicsExposures, &v);
463 if(fillstyle != -1)
464 XSetFillStyle(_x.display, gc, fillstyle);
465 if(foreground != -1)
466 XSetForeground(_x.display, gc, 0);
467 return gc;
471 /*
472 * Initialize map with the Plan 9 rgbv color map.
473 */
474 static void
475 plan9cmap(void)
477 int r, g, b, cr, cg, cb, v, num, den, idx, v7, idx7;
478 static int once;
480 if(once)
481 return;
482 once = 1;
484 for(r=0; r!=4; r++)
485 for(g = 0; g != 4; g++)
486 for(b = 0; b!=4; b++)
487 for(v = 0; v!=4; v++){
488 den=r;
489 if(g > den)
490 den=g;
491 if(b > den)
492 den=b;
493 /* divide check -- pick grey shades */
494 if(den==0)
495 cr=cg=cb=v*17;
496 else {
497 num=17*(4*den+v);
498 cr=r*num/den;
499 cg=g*num/den;
500 cb=b*num/den;
502 idx = r*64 + v*16 + ((g*4 + b + v - r) & 15);
503 _x.map[idx].red = cr*0x0101;
504 _x.map[idx].green = cg*0x0101;
505 _x.map[idx].blue = cb*0x0101;
506 _x.map[idx].pixel = idx;
507 _x.map[idx].flags = DoRed|DoGreen|DoBlue;
509 v7 = v >> 1;
510 idx7 = r*32 + v7*16 + g*4 + b;
511 if((v & 1) == v7){
512 _x.map7to8[idx7][0] = idx;
513 if(den == 0) { /* divide check -- pick grey shades */
514 cr = ((255.0/7.0)*v7)+0.5;
515 cg = cr;
516 cb = cr;
518 else {
519 num=17*15*(4*den+v7*2)/14;
520 cr=r*num/den;
521 cg=g*num/den;
522 cb=b*num/den;
524 _x.map7[idx7].red = cr*0x0101;
525 _x.map7[idx7].green = cg*0x0101;
526 _x.map7[idx7].blue = cb*0x0101;
527 _x.map7[idx7].pixel = idx7;
528 _x.map7[idx7].flags = DoRed|DoGreen|DoBlue;
530 else
531 _x.map7to8[idx7][1] = idx;
535 /*
536 * Initialize and install the rgbv color map as a private color map
537 * for this application. It gets the best colors when it has the
538 * cursor focus.
540 * We always choose the best depth possible, but that might not
541 * be the default depth. On such "suboptimal" systems, we have to allocate an
542 * empty color map anyway, according to Axel Belinfante.
543 */
544 static int
545 setupcmap(XWindow w)
547 char buf[30];
548 int i;
549 u32int p, pp;
550 XColor c;
552 if(_x.depth <= 1)
553 return 0;
555 if(_x.depth >= 24) {
556 if(_x.usetable == 0)
557 _x.cmap = XCreateColormap(_x.display, w, _x.vis, AllocNone);
559 /*
560 * The pixel value returned from XGetPixel needs to
561 * be converted to RGB so we can call rgb2cmap()
562 * to translate between 24 bit X and our color. Unfortunately,
563 * the return value appears to be display server endian
564 * dependant. Therefore, we run some heuristics to later
565 * determine how to mask the int value correctly.
566 * Yeah, I know we can look at _x.vis->byte_order but
567 * some displays say MSB even though they run on LSB.
568 * Besides, this is more anal.
569 */
570 c = _x.map[19]; /* known to have different R, G, B values */
571 if(!XAllocColor(_x.display, _x.cmap, &c)){
572 werrstr("XAllocColor: %r");
573 return -1;
575 p = c.pixel;
576 pp = rgb2cmap((p>>16)&0xff,(p>>8)&0xff,p&0xff);
577 if(pp != _x.map[19].pixel) {
578 /* check if endian is other way */
579 pp = rgb2cmap(p&0xff,(p>>8)&0xff,(p>>16)&0xff);
580 if(pp != _x.map[19].pixel){
581 werrstr("cannot detect X server byte order");
582 return -1;
585 switch(_x.chan){
586 case RGB24:
587 _x.chan = BGR24;
588 break;
589 case XRGB32:
590 _x.chan = XBGR32;
591 break;
592 default:
593 werrstr("cannot byteswap channel %s",
594 chantostr(buf, _x.chan));
595 break;
598 }else if(_x.vis->class == TrueColor || _x.vis->class == DirectColor){
599 /*
600 * Do nothing. We have no way to express a
601 * mixed-endian 16-bit screen, so pretend they don't exist.
602 */
603 if(_x.usetable == 0)
604 _x.cmap = XCreateColormap(_x.display, w, _x.vis, AllocNone);
605 }else if(_x.vis->class == PseudoColor){
606 if(_x.usetable == 0){
607 _x.cmap = XCreateColormap(_x.display, w, _x.vis, AllocAll);
608 XStoreColors(_x.display, _x.cmap, _x.map, 256);
609 for(i = 0; i < 256; i++){
610 _x.tox11[i] = i;
611 _x.toplan9[i] = i;
613 }else{
614 for(i = 0; i < 128; i++){
615 c = _x.map7[i];
616 if(!XAllocColor(_x.display, _x.cmap, &c)){
617 werrstr("can't allocate colors in 7-bit map");
618 return -1;
620 _x.tox11[_x.map7to8[i][0]] = c.pixel;
621 _x.tox11[_x.map7to8[i][1]] = c.pixel;
622 _x.toplan9[c.pixel] = _x.map7to8[i][0];
625 }else{
626 werrstr("unsupported visual class %d", _x.vis->class);
627 return -1;
629 return 0;
632 void
633 _flushmemscreen(Rectangle r)
635 if(_x.nextscreenpm != _x.screenpm){
636 qlock(&_x.screenlock);
637 XSync(_x.display, False);
638 XFreePixmap(_x.display, _x.screenpm);
639 _x.screenpm = _x.nextscreenpm;
640 qunlock(&_x.screenlock);
643 if(r.min.x >= r.max.x || r.min.y >= r.max.y)
644 return;
645 XCopyArea(_x.display, _x.screenpm, _x.drawable, _x.gccopy, r.min.x, r.min.y,
646 Dx(r), Dy(r), r.min.x, r.min.y);
647 XFlush(_x.display);
650 void
651 _xexpose(XEvent *e)
653 XExposeEvent *xe;
654 Rectangle r;
656 qlock(&_x.screenlock);
657 if(_x.screenpm != _x.nextscreenpm){
658 qunlock(&_x.screenlock);
659 return;
661 xe = (XExposeEvent*)e;
662 r.min.x = xe->x;
663 r.min.y = xe->y;
664 r.max.x = xe->x+xe->width;
665 r.max.y = xe->y+xe->height;
666 XCopyArea(_x.display, _x.screenpm, _x.drawable, _x.gccopy, r.min.x, r.min.y,
667 Dx(r), Dy(r), r.min.x, r.min.y);
668 XSync(_x.display, False);
669 qunlock(&_x.screenlock);
672 int
673 _xdestroy(XEvent *e)
675 XDestroyWindowEvent *xe;
677 xe = (XDestroyWindowEvent*)e;
678 if(xe->window == _x.drawable){
679 _x.destroyed = 1;
680 return 1;
682 return 0;
685 int
686 _xconfigure(XEvent *e)
688 Rectangle r;
689 XConfigureEvent *xe = (XConfigureEvent*)e;
691 if(!fullscreen){
692 int rx, ry;
693 XWindow w;
694 if(XTranslateCoordinates(_x.display, _x.drawable, DefaultRootWindow(_x.display), 0, 0, &rx, &ry, &w))
695 windowrect = Rect(rx, ry, rx+xe->width, ry+xe->height);
698 if(xe->width == Dx(_x.screenr) && xe->height == Dy(_x.screenr))
699 return 0;
700 r = Rect(0, 0, xe->width, xe->height);
702 qlock(&_x.screenlock);
703 if(_x.screenpm != _x.nextscreenpm){
704 XCopyArea(_x.display, _x.screenpm, _x.drawable, _x.gccopy, r.min.x, r.min.y,
705 Dx(r), Dy(r), r.min.x, r.min.y);
706 XSync(_x.display, False);
708 qunlock(&_x.screenlock);
709 _x.newscreenr = r;
710 return 1;
713 int
714 _xreplacescreenimage(void)
716 Memimage *m;
717 XDrawable pixmap;
718 Rectangle r;
720 r = _x.newscreenr;
722 pixmap = XCreatePixmap(_x.display, _x.drawable, Dx(r), Dy(r), _x.depth);
723 m = _xallocmemimage(r, _x.chan, pixmap);
724 if(_x.nextscreenpm != _x.screenpm)
725 XFreePixmap(_x.display, _x.nextscreenpm);
726 _x.nextscreenpm = pixmap;
727 _x.screenr = r;
728 _drawreplacescreenimage(m);
729 return 1;