2 * Some of the stuff in this file is not X-dependent and should be elsewhere.
12 #include "x11-memdraw.h"
15 static int parsewinsize(char*, Rectangle*, int*);
17 static Memimage *xattach(char*);
18 static void plan9cmap(void);
19 static int setupcmap(XWindow);
20 static int xreplacescreenimage(void);
21 static XGC xgc(XDrawable, int, int);
22 static Image *getimage0(Display*, Image*);
27 _initdisplay(void (*error)(Display*, char*), char *label)
33 * This rfork(RFNOTEG) isn't exactly right,
34 * but we need some way to signal window
35 * closes. Right now we post a hangup
36 * note to the note group, which kills a whole
37 * lot more than just the current program
38 * if we don't do this.
41 * Actually, I don't know what I changed but
42 * this appears not to be necessary anymore.
43 * I'll regret this probably.
48 d = mallocz(sizeof(Display), 1);
52 d->buf = malloc(16000+5);
53 d->obuf = malloc(16000);
54 if(d->buf == nil || d->obuf == nil){
72 _initdisplaymemimage(d, m);
73 d->screenimage = getimage0(d, 0);
78 getimage0(Display *d, Image *image)
83 extern int _freeimage1(Image*);
86 * If there's an old screen, it has id 0. The 'J' request below
87 * will try to install the new screen as id 0, so the old one
88 * must be freed first.
92 memset(image, 0, sizeof(Image));
98 if(flushimage(d, 0) < 0){
99 fprint(2, "cannot read screen info: %r\n");
103 n = _drawmsgread(d, info, sizeof info);
105 fprint(2, "short screen info\n");
110 image = mallocz(sizeof(Image), 1);
112 fprint(2, "cannot allocate image: %r\n");
119 image->chan = strtochan(info+2*12);
120 image->depth = chantodepth(image->chan);
121 image->repl = atoi(info+3*12);
122 image->r.min.x = atoi(info+4*12);
123 image->r.min.y = atoi(info+5*12);
124 image->r.max.x = atoi(info+6*12);
125 image->r.max.y = atoi(info+7*12);
126 image->clipr.min.x = atoi(info+8*12);
127 image->clipr.min.y = atoi(info+9*12);
128 image->clipr.max.x = atoi(info+10*12);
129 image->clipr.max.y = atoi(info+11*12);
134 getwindow(Display *d, int ref)
140 postnote(PNGROUP, getpgrp(), "hangup");
141 if(xreplacescreenimage() == 0)
145 * Libdraw promises not to change the value of "screen",
146 * so we have to reuse the image structure
147 * memory we already have.
150 i = getimage0(d, oi);
151 screen = d->screenimage = d->image = i;
152 // fprint(2, "getwindow %p -> %p\n", oi, i);
157 xerror(XDisplay *d, XErrorEvent *e)
161 if(e->request_code == 42) /* XSetInputFocus */
163 if(e->request_code == 18) /* XChangeProperty */
166 print("X error: error_code=%d, request_code=%d, minor=%d disp=%p\n",
167 e->error_code, e->request_code, e->minor_code, d);
168 XGetErrorText(d, e->error_code, buf, sizeof buf);
174 xioerror(XDisplay *d)
176 //print("X I/O error\n");
177 sysfatal("X I/O error\n");
186 char *argv[2], *disp;
187 int i, havemin, height, mask, n, width, x, xrootid, y;
189 XClassHint classhint;
191 XPixmapFormatValues *pfmt;
193 XSetWindowAttributes attr;
194 XSizeHints normalhint;
198 XWindowAttributes wattr;
203 if(XInitThreads() == 0){
204 fprint(2, "XInitThreads failed\n");
210 * Connect to X server.
212 _x.display = XOpenDisplay(NULL);
213 if(_x.display == nil){
214 disp = getenv("DISPLAY");
215 werrstr("XOpenDisplay %s: %r", disp ? disp : ":0");
219 XSetErrorHandler(xerror);
220 XSetIOErrorHandler(xioerror);
221 xrootid = DefaultScreen(_x.display);
222 xrootwin = DefaultRootWindow(_x.display);
225 * Figure out underlying screen format.
227 if(XMatchVisualInfo(_x.display, xrootid, 16, TrueColor, &xvi)
228 || XMatchVisualInfo(_x.display, xrootid, 16, DirectColor, &xvi)){
233 if(XMatchVisualInfo(_x.display, xrootid, 15, TrueColor, &xvi)
234 || XMatchVisualInfo(_x.display, xrootid, 15, DirectColor, &xvi)){
239 if(XMatchVisualInfo(_x.display, xrootid, 24, TrueColor, &xvi)
240 || XMatchVisualInfo(_x.display, xrootid, 24, DirectColor, &xvi)){
245 if(XMatchVisualInfo(_x.display, xrootid, 8, PseudoColor, &xvi)
246 || XMatchVisualInfo(_x.display, xrootid, 8, StaticColor, &xvi)){
248 werrstr("can't deal with colormapped depth %d screens",
256 _x.depth = DefaultDepth(_x.display, xrootid);
258 werrstr("can't understand depth %d screen", _x.depth);
261 _x.vis = DefaultVisual(_x.display, xrootid);
264 if(DefaultDepth(_x.display, xrootid) == _x.depth)
268 * _x.depth is only the number of significant pixel bits,
269 * not the total number of pixel bits. We need to walk the
270 * display list to find how many actual bits are used
274 pfmt = XListPixmapFormats(_x.display, &n);
276 if(pfmt[i].depth == _x.depth){
277 switch(pfmt[i].bits_per_pixel){
278 case 1: /* untested */
281 case 2: /* untested */
284 case 4: /* untested */
293 case 16: /* how to tell RGB15? */
296 case 24: /* untested (impossible?) */
306 werrstr("could not determine screen pixel format");
311 * Set up color map if necessary.
313 xscreen = DefaultScreenOfDisplay(_x.display);
314 _x.cmap = DefaultColormapOfScreen(xscreen);
315 if(_x.vis->class != StaticColor){
321 * We get to choose the initial rectangle size.
322 * This is arbitrary. In theory we should read the
323 * command line and allow the traditional X options.
329 if(parsewinsize(winsize, &r, &havemin) < 0)
333 * Parse the various X resources. Thanks to Peter Canning.
335 char *screen_resources, *display_resources, *geom,
336 *geomrestype, *home, *file;
337 XrmDatabase database;
340 database = XrmGetDatabase(_x.display);
341 screen_resources = XScreenResourceString(xscreen);
342 if(screen_resources != nil){
343 XrmCombineDatabase(XrmGetStringDatabase(screen_resources), &database, False);
344 XFree(screen_resources);
347 display_resources = XResourceManagerString(_x.display);
348 if(display_resources == nil){
349 home = getenv("home");
351 home = getenv("HOME");
352 if(home!=nil && (file=smprint("%s/.Xdefaults", home)) != nil){
353 XrmCombineFileDatabase(file, &database, False);
358 XrmCombineDatabase(XrmGetStringDatabase(display_resources), &database, False);
360 geom = smprint("%s.geometry", label);
361 if(geom && XrmGetResource(database, geom, nil, &geomrestype, &geomres))
362 mask = XParseGeometry(geomres.addr, &x, &y, (uint*)&width, (uint*)&height);
365 if((mask & WidthValue) && (mask & HeightValue)){
366 r = Rect(0, 0, width, height);
368 r = Rect(0, 0, WidthOfScreen(xscreen)*3/4,
369 HeightOfScreen(xscreen)*3/4);
370 if(Dx(r) > Dy(r)*3/2)
371 r.max.x = r.min.x + Dy(r)*3/2;
372 if(Dy(r) > Dx(r)*3/2)
373 r.max.y = r.min.y + Dx(r)*3/2;
375 if(mask & XNegative){
376 x += WidthOfScreen(xscreen);
378 if(mask & YNegative){
379 y += HeightOfScreen(xscreen);
384 memset(&attr, 0, sizeof attr);
385 attr.colormap = _x.cmap;
386 attr.background_pixel = ~0;
387 attr.border_pixel = 0;
388 _x.drawable = XCreateWindow(
389 _x.display, /* display */
390 xrootwin, /* parent */
395 0, /* border width */
396 _x.depth, /* depth */
397 InputOutput, /* class */
400 CWBackPixel|CWBorderPixel|CWColormap,
401 &attr /* attributes (the above aren't?!) */
405 * Label and other properties required by ICCCCM.
407 memset(&name, 0, sizeof name);
409 label = "pjw-face-here";
410 name.value = (uchar*)label;
411 name.encoding = XA_STRING;
413 name.nitems = strlen((char*)name.value);
415 memset(&normalhint, 0, sizeof normalhint);
416 normalhint.flags = PSize|PMaxSize;
418 normalhint.flags &= ~PSize;
419 normalhint.flags |= USSize;
420 normalhint.width = Dx(r);
421 normalhint.height = Dy(r);
423 if((mask & WidthValue) && (mask & HeightValue)){
424 normalhint.flags &= ~PSize;
425 normalhint.flags |= USSize;
426 normalhint.width = width;
427 normalhint.height = height;
429 if((mask & WidthValue) && (mask & HeightValue)){
430 normalhint.flags |= USPosition;
436 normalhint.max_width = WidthOfScreen(xscreen);
437 normalhint.max_height = HeightOfScreen(xscreen);
439 memset(&hint, 0, sizeof hint);
440 hint.flags = InputHint|StateHint;
442 hint.initial_state = NormalState;
444 memset(&classhint, 0, sizeof classhint);
445 classhint.res_name = label;
446 classhint.res_class = label;
452 _x.display, /* display */
453 _x.drawable, /* window */
454 &name, /* XA_WM_NAME property */
455 &name, /* XA_WM_ICON_NAME property */
456 argv, /* XA_WM_COMMAND */
458 &normalhint, /* XA_WM_NORMAL_HINTS */
459 &hint, /* XA_WM_HINTS */
460 &classhint /* XA_WM_CLASSHINTS */
467 memset(&ch, 0, sizeof ch);
470 XConfigureWindow(_x.display, _x.drawable, CWX|CWY, &ch);
473 * Look up clipboard atom.
475 _x.clipboard = XInternAtom(_x.display, "CLIPBOARD", False);
476 _x.utf8string = XInternAtom(_x.display, "UTF8_STRING", False);
477 _x.targets = XInternAtom(_x.display, "TARGETS", False);
478 _x.text = XInternAtom(_x.display, "TEXT", False);
479 _x.compoundtext = XInternAtom(_x.display, "COMPOUND_TEXT", False);
480 _x.takefocus = XInternAtom(_x.display, "WM_TAKE_FOCUS", False);
481 _x.losefocus = XInternAtom(_x.display, "_9WM_LOSE_FOCUS", False);
482 _x.wmprotos = XInternAtom(_x.display, "WM_PROTOCOLS", False);
484 atoms[0] = _x.takefocus;
485 atoms[1] = _x.losefocus;
486 XChangeProperty(_x.display, _x.drawable, _x.wmprotos, XA_ATOM, 32,
487 PropModeReplace, (uchar*)atoms, 2);
490 * Put the window on the screen, check to see what size we actually got.
492 XMapWindow(_x.display, _x.drawable);
493 XSync(_x.display, False);
495 if(!XGetWindowAttributes(_x.display, _x.drawable, &wattr))
496 fprint(2, "XGetWindowAttributes failed\n");
497 else if(wattr.width && wattr.height){
498 if(wattr.width != Dx(r) || wattr.height != Dy(r)){
499 r.max.x = wattr.width;
500 r.max.y = wattr.height;
503 fprint(2, "XGetWindowAttributes: bad attrs\n");
506 * Allocate our local backing store.
509 _x.screenpm = XCreatePixmap(_x.display, _x.drawable, Dx(r), Dy(r), _x.depth);
510 _x.nextscreenpm = _x.screenpm;
511 _x.screenimage = _xallocmemimage(r, _x.chan, _x.screenpm);
514 * Allocate some useful graphics contexts for the future.
516 _x.gcfill = xgc(_x.screenpm, FillSolid, -1);
517 _x.gccopy = xgc(_x.screenpm, -1, -1);
518 _x.gcsimplesrc = xgc(_x.screenpm, FillStippled, -1);
519 _x.gczero = xgc(_x.screenpm, -1, -1);
520 _x.gcreplsrc = xgc(_x.screenpm, FillTiled, -1);
522 pmid = XCreatePixmap(_x.display, _x.drawable, 1, 1, 1);
523 _x.gcfill0 = xgc(pmid, FillSolid, 0);
524 _x.gccopy0 = xgc(pmid, -1, -1);
525 _x.gcsimplesrc0 = xgc(pmid, FillStippled, -1);
526 _x.gczero0 = xgc(pmid, -1, -1);
527 _x.gcreplsrc0 = xgc(pmid, FillTiled, -1);
528 XFreePixmap(_x.display, pmid);
531 * Lots of display connections for various procs.
533 _x.kbdcon = XOpenDisplay(NULL);
534 _x.mousecon = XOpenDisplay(NULL);
535 _x.snarfcon = XOpenDisplay(NULL);
537 if(0) fprint(2, "x: display=%p kbd=%p mouse=%p snarf=%p\n",
538 _x.display, _x.kbdcon, _x.mousecon, _x.snarfcon);
540 _x.black = xscreen->black_pixel;
541 _x.white = xscreen->white_pixel;
543 return _x.screenimage;
548 * Should do a better job of cleaning up here.
550 XCloseDisplay(_x.display);
555 drawsetlabel(char *label)
558 XClassHint classhint;
562 * Label and other properties required by ICCCCM.
564 memset(&name, 0, sizeof name);
566 label = "pjw-face-here";
567 name.value = (uchar*)label;
568 name.encoding = XA_STRING;
570 name.nitems = strlen((char*)name.value);
572 memset(&classhint, 0, sizeof classhint);
573 classhint.res_name = label;
574 classhint.res_class = label;
580 _x.display, /* display */
581 _x.drawable, /* window */
582 &name, /* XA_WM_NAME property */
583 &name, /* XA_WM_ICON_NAME property */
584 argv, /* XA_WM_COMMAND */
586 nil, /* XA_WM_NORMAL_HINTS */
587 nil, /* XA_WM_HINTS */
588 &classhint /* XA_WM_CLASSHINTS */
595 * Create a GC with a particular fill style and XXX.
596 * Disable generation of GraphicsExpose/NoExpose events in the GC.
599 xgc(XDrawable d, int fillstyle, int foreground)
604 memset(&v, 0, sizeof v);
606 v.graphics_exposures = False;
607 gc = XCreateGC(_x.display, d, GCFunction|GCGraphicsExposures, &v);
609 XSetFillStyle(_x.display, gc, fillstyle);
611 XSetForeground(_x.display, gc, 0);
617 * Initialize map with the Plan 9 rgbv color map.
622 int r, g, b, cr, cg, cb, v, num, den, idx, v7, idx7;
630 for(g = 0; g != 4; g++)
631 for(b = 0; b!=4; b++)
632 for(v = 0; v!=4; v++){
638 /* divide check -- pick grey shades */
647 idx = r*64 + v*16 + ((g*4 + b + v - r) & 15);
648 _x.map[idx].red = cr*0x0101;
649 _x.map[idx].green = cg*0x0101;
650 _x.map[idx].blue = cb*0x0101;
651 _x.map[idx].pixel = idx;
652 _x.map[idx].flags = DoRed|DoGreen|DoBlue;
655 idx7 = r*32 + v7*16 + g*4 + b;
657 _x.map7to8[idx7][0] = idx;
658 if(den == 0) { /* divide check -- pick grey shades */
659 cr = ((255.0/7.0)*v7)+0.5;
664 num=17*15*(4*den+v7*2)/14;
669 _x.map7[idx7].red = cr*0x0101;
670 _x.map7[idx7].green = cg*0x0101;
671 _x.map7[idx7].blue = cb*0x0101;
672 _x.map7[idx7].pixel = idx7;
673 _x.map7[idx7].flags = DoRed|DoGreen|DoBlue;
676 _x.map7to8[idx7][1] = idx;
681 * Initialize and install the rgbv color map as a private color map
682 * for this application. It gets the best colors when it has the
685 * We always choose the best depth possible, but that might not
686 * be the default depth. On such "suboptimal" systems, we have to allocate an
687 * empty color map anyway, according to Axel Belinfante.
702 _x.cmap = XCreateColormap(_x.display, w, _x.vis, AllocNone);
705 * The pixel value returned from XGetPixel needs to
706 * be converted to RGB so we can call rgb2cmap()
707 * to translate between 24 bit X and our color. Unfortunately,
708 * the return value appears to be display server endian
709 * dependant. Therefore, we run some heuristics to later
710 * determine how to mask the int value correctly.
711 * Yeah, I know we can look at _x.vis->byte_order but
712 * some displays say MSB even though they run on LSB.
713 * Besides, this is more anal.
715 c = _x.map[19]; /* known to have different R, G, B values */
716 if(!XAllocColor(_x.display, _x.cmap, &c)){
717 werrstr("XAllocColor: %r");
721 pp = rgb2cmap((p>>16)&0xff,(p>>8)&0xff,p&0xff);
722 if(pp != _x.map[19].pixel) {
723 /* check if endian is other way */
724 pp = rgb2cmap(p&0xff,(p>>8)&0xff,(p>>16)&0xff);
725 if(pp != _x.map[19].pixel){
726 werrstr("cannot detect X server byte order");
738 werrstr("cannot byteswap channel %s",
739 chantostr(buf, _x.chan));
743 }else if(_x.vis->class == TrueColor || _x.vis->class == DirectColor){
745 * Do nothing. We have no way to express a
746 * mixed-endian 16-bit screen, so pretend they don't exist.
749 _x.cmap = XCreateColormap(_x.display, w, _x.vis, AllocNone);
750 }else if(_x.vis->class == PseudoColor){
751 if(_x.usetable == 0){
752 _x.cmap = XCreateColormap(_x.display, w, _x.vis, AllocAll);
753 XStoreColors(_x.display, _x.cmap, _x.map, 256);
754 for(i = 0; i < 256; i++){
759 for(i = 0; i < 128; i++){
761 if(!XAllocColor(_x.display, _x.cmap, &c)){
762 werrstr("can't allocate colors in 7-bit map");
765 _x.tox11[_x.map7to8[i][0]] = c.pixel;
766 _x.tox11[_x.map7to8[i][1]] = c.pixel;
767 _x.toplan9[c.pixel] = _x.map7to8[i][0];
771 werrstr("unsupported visual class %d", _x.vis->class);
778 _flushmemscreen(Rectangle r)
780 if(_x.nextscreenpm != _x.screenpm){
781 qlock(&_x.screenlock);
782 XSync(_x.display, False);
783 XFreePixmap(_x.display, _x.screenpm);
784 _x.screenpm = _x.nextscreenpm;
785 qunlock(&_x.screenlock);
788 if(r.min.x >= r.max.x || r.min.y >= r.max.y)
790 XCopyArea(_x.display, _x.screenpm, _x.drawable, _x.gccopy, r.min.x, r.min.y,
791 Dx(r), Dy(r), r.min.x, r.min.y);
796 _xexpose(XEvent *e, XDisplay *xd)
801 qlock(&_x.screenlock);
802 if(_x.screenpm != _x.nextscreenpm){
803 qunlock(&_x.screenlock);
806 xe = (XExposeEvent*)e;
809 r.max.x = xe->x+xe->width;
810 r.max.y = xe->y+xe->height;
811 XCopyArea(xd, _x.screenpm, _x.drawable, _x.gccopy, r.min.x, r.min.y,
812 Dx(r), Dy(r), r.min.x, r.min.y);
814 qunlock(&_x.screenlock);
818 _xdestroy(XEvent *e, XDisplay *xd)
820 XDestroyWindowEvent *xe;
822 xe = (XDestroyWindowEvent*)e;
823 if(xe->window == _x.drawable){
831 _xconfigure(XEvent *e, XDisplay *xd)
834 XConfigureEvent *xe = (XConfigureEvent*)e;
836 if(xe->width == Dx(_x.screenr) && xe->height == Dy(_x.screenr))
838 if(xe->width==0 || xe->height==0)
839 fprint(2, "ignoring resize to %dx%d\n", xe->width, xe->height);
840 r = Rect(0, 0, xe->width, xe->height);
841 qlock(&_x.screenlock);
842 if(_x.screenpm != _x.nextscreenpm){
843 XCopyArea(xd, _x.screenpm, _x.drawable, _x.gccopy, r.min.x, r.min.y,
844 Dx(r), Dy(r), r.min.x, r.min.y);
847 qunlock(&_x.screenlock);
853 xreplacescreenimage(void)
860 if(eqrect(_x.screenr, r))
863 pixmap = XCreatePixmap(_x.display, _x.drawable, Dx(r), Dy(r), _x.depth);
864 m = _xallocmemimage(r, _x.chan, pixmap);
865 if(_x.nextscreenpm != _x.screenpm)
866 XFreePixmap(_x.display, _x.nextscreenpm);
867 _x.nextscreenpm = pixmap;
869 _drawreplacescreenimage(m);
874 parsewinsize(char *s, Rectangle *r, int *havemin)
884 i = strtol(s, &s, 0);
889 j = strtol(s, &s, 0);
900 i = strtol(s, &s, 0);
901 if(*s != ',' && *s != ' ')
906 j = strtol(s, &s, 0);
909 *r = rectaddpt(*r, Pt(i,j));
915 if(c != ' ' && c != ',')
920 j = strtol(s, &s, 0);
926 k = strtol(s, &s, 0);
932 l = strtol(s, &s, 0);
940 werrstr("bad syntax in window size '%s'", os);