*** empty log message ***
[dana/urxvt.git] / src / rxvttoolkit.C
1 /*--------------------------------*-C-*---------------------------------*
2  * File:        rxvttoolkit.C
3  *----------------------------------------------------------------------*
4  *
5  * All portions of code are copyright by their respective author/s.
6  * Copyright (c) 2003-2004 Marc Lehmann <pcg@goof.com>
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21  *----------------------------------------------------------------------*/
22
23 #include "../config.h"
24 #include <rxvt.h>
25 #include <rxvttoolkit.h>
26
27 #include <unistd.h>
28 #include <fcntl.h>
29
30 #include <sys/utsname.h>
31
32 #ifndef NO_SLOW_LINK_SUPPORT
33 # include <sys/socket.h>
34 # include <sys/un.h>
35 #endif
36
37 #if XFT
38 # include <X11/extensions/Xrender.h>
39 #endif
40
41 const char *const xa_names[] =
42 {
43   "TEXT",
44   "COMPOUND_TEXT",
45   "UTF8_STRING",
46   "MULTIPLE",
47   "TARGETS",
48   "TIMESTAMP",
49   "VT_SELECTION",
50   "INCR",
51   "WM_PROTOCOLS",
52   "WM_DELETE_WINDOW",
53   "CLIPBOARD",
54   "AVERAGE_WIDTH",
55   "WEIGHT_NAME",
56   "SLANT",
57   "CHARSET_REGISTRY",
58   "CHARSET_ENCODING",
59 #if ENABLE_FRILLS
60   "_MOTIF_WM_HINTS",
61 #endif
62 #if ENABLE_EWMH
63   "_NET_WM_PID",
64   "_NET_WM_NAME",
65   "_NET_WM_ICON_NAME",
66   "_NET_WM_PING",
67 #endif
68 #if USE_XIM
69   "WM_LOCALE_NAME",
70   "XIM_SERVERS",
71 #endif
72 #ifdef TRANSPARENT
73   "_XROOTPMAP_ID",
74   "ESETROOT_PMAP_ID",
75 #endif
76 #if ENABLE_XEMBED
77   "_XEMBED",
78   "_XEMBED_INFO",
79 #endif
80 #if !ENABLE_MINIMAL
81   "SCREEN_RESOURCES",
82   "XDCCC_LINEAR_RGB_CORRECTION",
83   "XDCCC_LINEAR_RGB_MATRICES",
84   "WM_COLORMAP_WINDOWS",
85   "WM_STATE",
86   "cursor",
87 # if USE_XIM
88   "TRANSPORT",
89   "LOCALES",
90   "_XIM_PROTOCOL",
91   "_XIM_XCONNECT",
92   "_XIM_MOREDATA",
93 # endif
94 #endif
95 };
96
97 /////////////////////////////////////////////////////////////////////////////
98
99 refcounted::refcounted (const char *id)
100 {
101   this->id = strdup (id);
102 }
103
104 refcounted::~refcounted ()
105 {
106   free (id);
107 }
108
109 template<class T>
110 T *refcache<T>::get (const char *id)
111 {
112   for (T **i = this->begin (); i < this->end (); ++i)
113     {
114       if (!strcmp (id, (*i)->id))
115         {
116           ++(*i)->referenced;
117           (*i)->ref_next ();
118           return *i;
119         }
120     }
121
122   T *obj = new T (id);
123
124   if (obj && obj->ref_init ())
125     {
126       obj->referenced = 1;
127       this->push_back (obj);
128       return obj;
129     }
130   else
131     {
132       delete obj;
133       return 0;
134     }
135 }
136
137 template<class T>
138 void refcache<T>::put (T *obj)
139 {
140   if (!obj)
141     return;
142
143   if (!--obj->referenced)
144     {
145       this->erase (find (this->begin (), this->end (), obj));
146       delete obj;
147     }
148 }
149
150 template<class T>
151 void refcache<T>::clear ()
152 {
153   while (this->size ())
154     put (*this->begin ());
155 }
156
157 /////////////////////////////////////////////////////////////////////////////
158
159 #ifdef USE_XIM
160
161 static void
162 #if XIMCB_PROTO_BROKEN
163 im_destroy_cb (XIC unused1, XPointer client_data, XPointer unused3)
164 #else
165 im_destroy_cb (XIM unused1, XPointer client_data, XPointer unused3)
166 #endif
167 {
168   rxvt_xim *xim = (rxvt_xim *)client_data;
169   rxvt_display *display = xim->display;
170
171   xim->xim = 0;
172
173   display->xims.erase (find (display->xims.begin (), display->xims.end (), xim));
174   display->im_change_cb ();
175 }
176
177 bool
178 rxvt_xim::ref_init ()
179 {
180   display = GET_R->display; //HACK: TODO
181
182   xim = XOpenIM (display->display, NULL, NULL, NULL);
183
184   if (!xim)
185     return false;
186
187   XIMCallback ximcallback;
188   ximcallback.client_data = (XPointer)this;
189   ximcallback.callback = im_destroy_cb;
190
191   XSetIMValues (xim, XNDestroyCallback, &ximcallback, NULL);
192
193   return true;
194 }
195
196 rxvt_xim::~rxvt_xim ()
197 {
198   if (xim)
199     XCloseIM (xim);
200 }
201
202 #endif
203
204 /////////////////////////////////////////////////////////////////////////////
205
206 void
207 rxvt_screen::set (rxvt_display *disp)
208 {
209   display = disp;
210   xdisp   = disp->display;
211
212   Screen *screen = ScreenOfDisplay (xdisp, disp->screen);
213
214   depth   = DefaultDepthOfScreen    (screen);
215   visual  = DefaultVisualOfScreen   (screen);
216   cmap    = DefaultColormapOfScreen (screen);
217 }
218
219 void
220 rxvt_screen::set (rxvt_display *disp, int bitdepth)
221 {
222   set (disp);
223
224 #if XFT
225   XVisualInfo vinfo;
226
227   if (XMatchVisualInfo (xdisp, display->screen, bitdepth, TrueColor, &vinfo))
228     {
229       depth  = bitdepth;
230       visual = vinfo.visual;
231       cmap   = XCreateColormap (xdisp, disp->root, visual, AllocNone);
232     }
233 #endif
234 }
235
236 void
237 rxvt_screen::clear ()
238 {
239   if (cmap != DefaultColormapOfScreen (ScreenOfDisplay (xdisp, display->screen)))
240     XFreeColormap (xdisp, cmap);
241 }
242
243 /////////////////////////////////////////////////////////////////////////////
244
245 rxvt_display::rxvt_display (const char *id)
246 : refcounted (id)
247 , x_ev (this, &rxvt_display::x_cb)
248 , selection_owner (0)
249 {
250 }
251
252 XrmDatabase
253 rxvt_display::get_resources ()
254 {
255   char *homedir = (char *)getenv ("HOME");
256   char fname[1024];
257
258   /*
259    * get resources using the X library function
260    */
261   char *displayResource, *xe;
262   XrmDatabase database, rdb1;
263
264   database = NULL;
265
266   // for ordering, see for example http://www.faqs.org/faqs/Xt-FAQ/ Subject: 20
267
268   // 6. System wide per application default file.
269
270   /* Add in $XAPPLRESDIR/Rxvt only; not bothering with XUSERFILESEARCHPATH */
271   if ((xe = (char *)getenv ("XAPPLRESDIR")))
272     {
273       snprintf (fname, sizeof (fname), "%s/%s", xe, RESCLASS);
274
275       if ((rdb1 = XrmGetFileDatabase (fname)))
276         XrmMergeDatabases (rdb1, &database);
277     }
278
279   // 5. User's per application default file.
280   // none
281
282   // 4. User's defaults file.
283   /* Get any Xserver defaults */
284   displayResource = XResourceManagerString (display);
285
286   if (displayResource != NULL)
287     {
288       if ((rdb1 = XrmGetStringDatabase (displayResource)))
289         XrmMergeDatabases (rdb1, &database);
290     }
291   else if (homedir)
292     {
293       snprintf (fname, sizeof (fname), "%s/.Xdefaults", homedir);
294
295       if ((rdb1 = XrmGetFileDatabase (fname)))
296         XrmMergeDatabases (rdb1, &database);
297     }
298
299   /* Get screen specific resources */
300   displayResource = XScreenResourceString (ScreenOfDisplay (display, screen));
301
302   if (displayResource != NULL)
303     {
304       if ((rdb1 = XrmGetStringDatabase (displayResource)))
305         /* Merge with screen-independent resources */
306         XrmMergeDatabases (rdb1, &database);
307
308       XFree (displayResource);
309     }
310
311   // 3. User's per host defaults file
312   /* Add in XENVIRONMENT file */
313   if ((xe = (char *)getenv ("XENVIRONMENT"))
314       && (rdb1 = XrmGetFileDatabase (xe)))
315     XrmMergeDatabases (rdb1, &database);
316   else if (homedir)
317     {
318       struct utsname un;
319
320       if (!uname (&un))
321         {
322           snprintf (fname, sizeof (fname), "%s/.Xdefaults-%s", homedir, un.nodename);
323
324           if ((rdb1 = XrmGetFileDatabase (fname)))
325             XrmMergeDatabases (rdb1, &database);
326         }
327     }
328
329   return database;
330 }
331
332 bool rxvt_display::ref_init ()
333 {
334 #ifdef LOCAL_X_IS_UNIX
335   if (id[0] == ':')
336     {
337       val = rxvt_malloc (5 + strlen (id) + 1);
338       strcpy (val, "unix/");
339       strcat (val, id);
340       display = XOpenDisplay (val);
341       free (val);
342     }
343   else
344 #endif
345     display = 0;
346
347   if (!display)
348     display = XOpenDisplay (id);
349
350   if (!display)
351     return false;
352
353   screen = DefaultScreen (display);
354   root   = DefaultRootWindow (display);
355
356   assert (sizeof (xa_names) / sizeof (char *) == NUM_XA);
357   XInternAtoms (display, (char **)xa_names, NUM_XA, False, xa);
358
359   XrmSetDatabase (display, get_resources ());
360
361 #ifdef POINTER_BLANK
362   XColor blackcolour;
363   blackcolour.red   = 0;
364   blackcolour.green = 0;
365   blackcolour.blue  = 0;
366   Font f = XLoadFont (display, "fixed");
367   blank_cursor = XCreateGlyphCursor (display, f, f, ' ', ' ',
368                                      &blackcolour, &blackcolour);
369   XUnloadFont (display, f);
370 #endif
371
372   int fd = XConnectionNumber (display);
373
374 #ifndef NO_SLOW_LINK_SUPPORT
375   // try to detect wether we have a local connection.
376   // assume unix domains socket == local, everything else not
377   // TODO: might want to check for inet/127.0.0.1
378   is_local = 0;
379   sockaddr_un sa;
380   socklen_t sl = sizeof (sa);
381
382   if (!getsockname (fd, (sockaddr *)&sa, &sl))
383     is_local = sa.sun_family == AF_LOCAL;
384 #endif
385
386   x_ev.start (fd, EVENT_READ);
387   fcntl (fd, F_SETFD, FD_CLOEXEC);
388
389   XSelectInput (display, root, PropertyChangeMask);
390
391   flush ();
392
393   return true;
394 }
395
396 void
397 rxvt_display::ref_next ()
398 {
399   // TODO: somehow check wether the database files/resources changed
400   // before affording re-loading/parsing
401   XrmDestroyDatabase (XrmGetDatabase (display));
402   XrmSetDatabase (display, get_resources ());
403   printf ("next\n");//D
404 }
405
406 rxvt_display::~rxvt_display ()
407 {
408   if (!display)
409     return;
410
411 #ifdef POINTER_BLANK
412   XFreeCursor (display, blank_cursor);
413 #endif
414   x_ev.stop ();
415 #ifdef USE_XIM
416   xims.clear ();
417 #endif
418   XCloseDisplay (display);
419 }
420
421 #ifdef USE_XIM
422 void rxvt_display::im_change_cb ()
423 {
424   for (im_watcher **i = imw.begin (); i != imw.end (); ++i)
425     (*i)->call ();
426 }
427
428 void rxvt_display::im_change_check ()
429 {
430   // try to only call im_change_cb when a new input method
431   // registers, as xlib crashes due to a race otherwise.
432   Atom actual_type, *atoms;
433   int actual_format;
434   unsigned long nitems, bytes_after;
435
436   if (XGetWindowProperty (display, root, xa[XA_XIM_SERVERS], 0L, 1000000L,
437                           False, XA_ATOM, &actual_type, &actual_format,
438                           &nitems, &bytes_after, (unsigned char **)&atoms)
439       != Success )
440     return;
441
442   if (actual_type == XA_ATOM  && actual_format == 32)
443     for (int i = 0; i < nitems; i++)
444       if (XGetSelectionOwner (display, atoms[i]))
445         {
446           im_change_cb ();
447           break;
448         }
449
450   XFree (atoms);
451 }
452 #endif
453
454 void rxvt_display::x_cb (io_watcher &w, short revents)
455 {
456   do
457     {
458       XEvent xev;
459       XNextEvent (display, &xev);
460
461 #ifdef USE_XIM
462       if (!XFilterEvent (&xev, None))
463         {
464           if (xev.type == PropertyNotify
465               && xev.xany.window == root
466               && xev.xproperty.atom == xa[XA_XIM_SERVERS])
467             im_change_check ();
468 #endif
469           for (int i = xw.size (); i--; )
470             {
471               if (!xw[i])
472                 xw.erase_unordered (i);
473               else if (xw[i]->window == xev.xany.window)
474                 xw[i]->call (xev);
475             }
476 #ifdef USE_XIM
477         }
478 #endif
479     }
480   while (XEventsQueued (display, QueuedAlready));
481
482   XFlush (display);
483 }
484
485 void rxvt_display::flush ()
486 {
487   if (XEventsQueued (display, QueuedAlready))
488     x_cb (x_ev, EVENT_READ);
489
490   XFlush (display);
491 }
492
493 void rxvt_display::reg (xevent_watcher *w)
494 {
495   xw.push_back (w);
496   w->active = xw.size ();
497 }
498
499 void rxvt_display::unreg (xevent_watcher *w)
500 {
501   if (w->active)
502     xw[w->active - 1] = 0;
503 }
504
505 void rxvt_display::set_selection_owner (rxvt_term *owner)
506 {
507   if (selection_owner && selection_owner != owner)
508     selection_owner->selection_clear ();
509
510   selection_owner = owner;
511 }
512
513 #ifdef USE_XIM
514
515 void rxvt_display::reg (im_watcher *w)
516 {
517   imw.push_back (w);
518 }
519
520 void rxvt_display::unreg (im_watcher *w)
521 {
522   imw.erase (find (imw.begin (), imw.end (), w));
523 }
524
525 rxvt_xim *rxvt_display::get_xim (const char *locale, const char *modifiers)
526 {
527   char *id;
528   int l, m;
529
530   l = strlen (locale);
531   m = strlen (modifiers);
532
533   if (!(id = (char *)malloc (l + m + 2)))
534     return 0;
535
536   memcpy (id, locale, l); id[l] = '\n';
537   memcpy (id + l + 1, modifiers, m); id[l + m + 1] = 0;
538
539   rxvt_xim *xim = xims.get (id);
540
541   free (id);
542
543   return xim;
544 }
545
546 void rxvt_display::put_xim (rxvt_xim *xim)
547 {
548 # if XLIB_IS_RACEFREE
549   xims.put (xim);
550 # endif
551 }
552
553 #endif
554
555 Atom rxvt_display::atom (const char *name)
556 {
557   return XInternAtom (display, name, False);
558 }
559
560 /////////////////////////////////////////////////////////////////////////////
561
562 template class refcache<rxvt_display>;
563 refcache<rxvt_display> displays;
564
565 /////////////////////////////////////////////////////////////////////////////
566  
567 bool
568 rxvt_color::alloc (rxvt_screen *screen, const rgba &color)
569 {
570 #if XFT
571   XRenderPictFormat *format;
572
573   // FUCKING Xft gets it wrong, of course, so work around it
574   // transparency users should eat shit and die, and then
575   // XRenderQueryPictIndexValues themselves plenty.
576   if ((screen->visual->c_class == TrueColor || screen->visual->c_class == DirectColor)
577       && (format = XRenderFindVisualFormat (screen->xdisp, screen->visual)))
578     {
579       // the fun lies in doing everything manually...
580       c.color.red   = color.r;
581       c.color.green = color.g;
582       c.color.blue  = color.b;
583       c.color.alpha = color.a;
584
585       c.pixel = ((color.r * format->direct.redMask   / rgba::MAX_CC) << format->direct.red  )
586               | ((color.g * format->direct.greenMask / rgba::MAX_CC) << format->direct.green)
587               | ((color.b * format->direct.blueMask  / rgba::MAX_CC) << format->direct.blue )
588               | ((color.a * format->direct.alphaMask / rgba::MAX_CC) << format->direct.alpha);
589
590       return true;
591     }
592   else
593     {
594       XRenderColor d;
595
596       d.red   = color.r;
597       d.green = color.g;
598       d.blue  = color.b;
599       d.alpha = color.a;
600
601       return XftColorAllocValue (screen->xdisp, screen->visual, screen->cmap, &d, &c);
602     }
603 #else
604   c.red   = color.r;
605   c.green = color.g;
606   c.blue  = color.b;
607
608   if (screen->visual->c_class == TrueColor || screen->visual->c_class == DirectColor)
609     {
610       c.pixel = (color.r * (screen->visual->red_mask   >> ctz (screen->visual->red_mask  ))
611                          / rgba::MAX_CC) << ctz (screen->visual->red_mask  )
612               | (color.g * (screen->visual->green_mask >> ctz (screen->visual->green_mask))
613                          / rgba::MAX_CC) << ctz (screen->visual->green_mask)
614               | (color.b * (screen->visual->blue_mask  >> ctz (screen->visual->blue_mask ))
615                          / rgba::MAX_CC) << ctz (screen->visual->blue_mask );
616
617       return true;
618     }
619   else if (XAllocColor (screen->xdisp, screen->cmap, &c))
620     return true;
621   else
622     c.pixel = (color.r + color.g + color.b) > 128*3
623             ? WhitePixelOfScreen (DefaultScreenOfDisplay (screen->xdisp))
624             : BlackPixelOfScreen (DefaultScreenOfDisplay (screen->xdisp));
625 #endif
626
627   return false;
628 }
629
630 bool
631 rxvt_color::set (rxvt_screen *screen, const char *name)
632 {
633   rgba c;
634   char eos;
635   int skip;
636
637   // parse the nonstandard "[alphapercent]" prefix
638   if (1 <= sscanf (name, "[%hd]%n", &c.a, &skip))
639     {
640       c.a = lerp<int, int, int> (0, rgba::MAX_CC, c.a);
641       name += skip;
642     }
643   else
644     c.a = rgba::MAX_CC;
645
646   // parse the non-standard "rgba:rrrr/gggg/bbbb/aaaa" format
647   if (strlen (name) != 4+5*4 || 4 != sscanf (name, "rgba:%4hx/%4hx/%4hx/%4hx%c", &c.r, &c.g, &c.b, &c.a, &eos))
648     {
649       XColor xc, xc_exact;
650
651       if (XParseColor (screen->xdisp, screen->cmap, name, &xc))
652         {
653           c.r = xc.red;
654           c.g = xc.green;
655           c.b = xc.blue;
656         }
657       else
658         {
659           c.r = 0xffff;
660           c.g = 0x6969;
661           c.b = 0xb4b4;
662
663           rxvt_warn ("unable to parse color '%s', using pink instead.\n", name);
664         }
665     }
666
667   return set (screen, c);
668 }
669
670 bool
671 rxvt_color::set (rxvt_screen *screen, const rgba &color)
672 {
673   bool got = alloc (screen, color);
674
675 #if !ENABLE_MINIMAL
676   int cmap_size = screen->visual->map_entries;
677
678   if (!got
679       && screen->visual->c_class == PseudoColor
680       && cmap_size < 4096)
681     {
682       XColor *colors = new XColor [screen->visual->map_entries];
683
684       for (int i = 0; i < cmap_size; i++)
685         colors [i].pixel = i;
686  
687       // many kilobytes transfer per colour, but pseudocolor isn't worth
688       // many extra optimisations.
689       XQueryColors (screen->xdisp, screen->cmap, colors, cmap_size);
690
691       int diff = 0x7fffffffUL;
692       XColor *best = colors;
693
694       for (int i = 0; i < cmap_size; i++)
695         {
696           int d = (squared_diff<int> (color.r >> 2, colors [i].red   >> 2))
697                 + (squared_diff<int> (color.g >> 2, colors [i].green >> 2))
698                 + (squared_diff<int> (color.b >> 2, colors [i].blue  >> 2));
699
700           if (d < diff)
701             {
702               diff = d;
703               best = colors + i;
704             }
705         }
706
707       //rxvt_warn ("could not allocate %04x %04x %04x, getting %04x %04x %04x instead (%d)\n",
708       //    color.r, color.g, color.b, best->red, best->green, best->blue, diff);
709           
710       got = alloc (screen, rgba (best->red, best->green, best->blue));
711
712       delete colors;
713     }
714 #endif
715
716   return got;
717 }
718
719 void
720 rxvt_color::get (rgba &color)
721 {
722 #if XFT
723   color.r = c.color.red;
724   color.g = c.color.green;
725   color.b = c.color.blue;
726   color.a = c.color.alpha;
727 #else
728   color.r = c.red;
729   color.g = c.green;
730   color.b = c.blue;
731   color.a = rgba::MAX_CC;
732 #endif
733 }
734
735 void
736 rxvt_color::get (XColor &color)
737 {
738   rgba c;
739   get (c);
740
741   color.red   = c.r;
742   color.green = c.g;
743   color.blue  = c.b;
744   color.pixel = (Pixel)*this;
745 }
746
747 void 
748 rxvt_color::free (rxvt_screen *screen)
749 {
750 #if XFT
751   XftColorFree (screen->xdisp, screen->visual, screen->cmap, &c);
752 #else
753   XFreeColors (screen->xdisp, screen->cmap, &c.pixel, 1, AllPlanes);
754 #endif
755 }
756
757 void
758 rxvt_color::fade (rxvt_screen *screen, int percent, rxvt_color &result, const rgba &to)
759 {
760   rgba c;
761   get (c);
762
763   result.set (
764     screen,
765     rgba (
766       lerp (c.r, to.r, percent),
767       lerp (c.g, to.g, percent),
768       lerp (c.b, to.b, percent),
769       lerp (c.a, to.a, percent)
770     )
771   );
772 }
773