*** 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 const char *const xa_names[] =
38   {
39     "TEXT",
40     "COMPOUND_TEXT",
41     "UTF8_STRING",
42     "MULTIPLE",
43     "TARGETS",
44     "TIMESTAMP",
45     "VT_SELECTION",
46     "INCR",
47     "WM_PROTOCOLS",
48     "WM_DELETE_WINDOW",
49     "CLIPBOARD",
50 #if ENABLE_FRILLS
51     "_MOTIF_WM_HINTS",
52 #endif
53 #if ENABLE_EWMH
54     "_NET_WM_PID",
55     "_NET_WM_NAME",
56     "_NET_WM_ICON_NAME",
57     "_NET_WM_PING",
58 #endif
59 #if USE_XIM
60     "WM_LOCALE_NAME",
61     "XIM_SERVERS",
62 #endif
63 #ifdef TRANSPARENT
64     "_XROOTPMAP_ID",
65     "ESETROOT_PMAP_ID",
66 #endif
67 #if ENABLE_XEMBED
68     "_XEMBED",
69     "_XEMBED_INFO",
70 #endif
71   };
72
73 /////////////////////////////////////////////////////////////////////////////
74
75 refcounted::refcounted (const char *id)
76 {
77   this->id = strdup (id);
78 }
79
80 refcounted::~refcounted ()
81 {
82   free (id);
83 }
84
85 template<class T>
86 T *refcache<T>::get (const char *id)
87 {
88   for (T **i = this->begin (); i < this->end (); ++i)
89     {
90       if (!strcmp (id, (*i)->id))
91         {
92           ++(*i)->referenced;
93           (*i)->ref_next ();
94           return *i;
95         }
96     }
97
98   T *obj = new T (id);
99
100   if (obj && obj->ref_init ())
101     {
102       obj->referenced = 1;
103       this->push_back (obj);
104       return obj;
105     }
106   else
107     {
108       delete obj;
109       return 0;
110     }
111 }
112
113 template<class T>
114 void refcache<T>::put (T *obj)
115 {
116   if (!obj)
117     return;
118
119   if (!--obj->referenced)
120     {
121       this->erase (find (this->begin (), this->end (), obj));
122       delete obj;
123     }
124 }
125
126 template<class T>
127 void refcache<T>::clear ()
128 {
129   while (this->size ())
130     put (*this->begin ());
131 }
132
133 /////////////////////////////////////////////////////////////////////////////
134
135 #ifdef USE_XIM
136
137 static void
138 #if XIMCB_PROTO_BROKEN
139 im_destroy_cb (XIC unused1, XPointer client_data, XPointer unused3)
140 #else
141 im_destroy_cb (XIM unused1, XPointer client_data, XPointer unused3)
142 #endif
143 {
144   rxvt_xim *xim = (rxvt_xim *)client_data;
145   rxvt_display *display = xim->display;
146
147   xim->xim = 0;
148
149   display->xims.erase (find (display->xims.begin (), display->xims.end (), xim));
150   display->im_change_cb ();
151 }
152
153 bool
154 rxvt_xim::ref_init ()
155 {
156   display = GET_R->display; //HACK: TODO
157
158   xim = XOpenIM (display->display, NULL, NULL, NULL);
159
160   if (!xim)
161     return false;
162
163   XIMCallback ximcallback;
164   ximcallback.client_data = (XPointer)this;
165   ximcallback.callback = im_destroy_cb;
166
167   XSetIMValues (xim, XNDestroyCallback, &ximcallback, NULL);
168
169   return true;
170 }
171
172 rxvt_xim::~rxvt_xim ()
173 {
174   if (xim)
175     XCloseIM (xim);
176 }
177
178 #endif
179
180 /////////////////////////////////////////////////////////////////////////////
181
182 void
183 rxvt_screen::set (rxvt_display *disp)
184 {
185   display = disp;
186   xdisp   = disp->display;
187
188   Screen *screen = ScreenOfDisplay (xdisp, disp->screen);
189
190   depth   = DefaultDepthOfScreen    (screen);
191   visual  = DefaultVisualOfScreen   (screen);
192   cmap    = DefaultColormapOfScreen (screen);
193 }
194
195 void
196 rxvt_screen::set (rxvt_display *disp, int bitdepth)
197 {
198   set (disp);
199
200   XVisualInfo vinfo;
201
202   if (XMatchVisualInfo (xdisp, display->screen, bitdepth, TrueColor, &vinfo))
203     {
204       depth  = bitdepth;
205       visual = vinfo.visual;
206       cmap   = XCreateColormap (xdisp, disp->root, visual, AllocNone);
207     }
208 }
209
210 void
211 rxvt_screen::clear ()
212 {
213   if (cmap != DefaultColormapOfScreen (ScreenOfDisplay (xdisp, display->screen)))
214     XFreeColormap (xdisp, cmap);
215 }
216
217 /////////////////////////////////////////////////////////////////////////////
218
219 rxvt_display::rxvt_display (const char *id)
220 : refcounted (id)
221 , x_ev (this, &rxvt_display::x_cb)
222 , selection_owner (0)
223 {
224 }
225
226 XrmDatabase
227 rxvt_display::get_resources ()
228 {
229   char *homedir = (char *)getenv ("HOME");
230   char fname[1024];
231
232   /*
233    * get resources using the X library function
234    */
235   char *displayResource, *xe;
236   XrmDatabase database, rdb1;
237
238   database = NULL;
239
240   // for ordering, see for example http://www.faqs.org/faqs/Xt-FAQ/ Subject: 20
241
242   // 6. System wide per application default file.
243
244   /* Add in $XAPPLRESDIR/Rxvt only; not bothering with XUSERFILESEARCHPATH */
245   if ((xe = (char *)getenv ("XAPPLRESDIR")))
246     {
247       snprintf (fname, sizeof (fname), "%s/%s", xe, RESCLASS);
248
249       if ((rdb1 = XrmGetFileDatabase (fname)))
250         XrmMergeDatabases (rdb1, &database);
251     }
252
253   // 5. User's per application default file.
254   // none
255
256   // 4. User's defaults file.
257   /* Get any Xserver defaults */
258   displayResource = XResourceManagerString (display);
259
260   if (displayResource != NULL)
261     {
262       if ((rdb1 = XrmGetStringDatabase (displayResource)))
263         XrmMergeDatabases (rdb1, &database);
264     }
265   else if (homedir)
266     {
267       snprintf (fname, sizeof (fname), "%s/.Xdefaults", homedir);
268
269       if ((rdb1 = XrmGetFileDatabase (fname)))
270         XrmMergeDatabases (rdb1, &database);
271     }
272
273   /* Get screen specific resources */
274   displayResource = XScreenResourceString (ScreenOfDisplay (display, screen));
275
276   if (displayResource != NULL)
277     {
278       if ((rdb1 = XrmGetStringDatabase (displayResource)))
279         /* Merge with screen-independent resources */
280         XrmMergeDatabases (rdb1, &database);
281
282       XFree (displayResource);
283     }
284
285   // 3. User's per host defaults file
286   /* Add in XENVIRONMENT file */
287   if ((xe = (char *)getenv ("XENVIRONMENT"))
288       && (rdb1 = XrmGetFileDatabase (xe)))
289     XrmMergeDatabases (rdb1, &database);
290   else if (homedir)
291     {
292       struct utsname un;
293
294       if (!uname (&un))
295         {
296           snprintf (fname, sizeof (fname), "%s/.Xdefaults-%s", homedir, un.nodename);
297
298           if ((rdb1 = XrmGetFileDatabase (fname)))
299             XrmMergeDatabases (rdb1, &database);
300         }
301     }
302
303   return database;
304 }
305
306 bool rxvt_display::ref_init ()
307 {
308 #ifdef LOCAL_X_IS_UNIX
309   if (id[0] == ':')
310     {
311       val = rxvt_malloc (5 + strlen (id) + 1);
312       strcpy (val, "unix/");
313       strcat (val, id);
314       display = XOpenDisplay (val);
315       free (val);
316     }
317   else
318 #endif
319     display = 0;
320
321   if (!display)
322     display = XOpenDisplay (id);
323
324   if (!display)
325     return false;
326
327   screen = DefaultScreen (display);
328   root   = DefaultRootWindow (display);
329
330   assert (sizeof (xa_names) / sizeof (char *) == NUM_XA);
331   XInternAtoms (display, (char **)xa_names, NUM_XA, False, xa);
332
333   XrmSetDatabase (display, get_resources ());
334
335 #ifdef POINTER_BLANK
336   XColor blackcolour;
337   blackcolour.red   = 0;
338   blackcolour.green = 0;
339   blackcolour.blue  = 0;
340   Font f = XLoadFont (display, "fixed");
341   blank_cursor = XCreateGlyphCursor (display, f, f, ' ', ' ',
342                                      &blackcolour, &blackcolour);
343   XUnloadFont (display, f);
344 #endif
345
346   int fd = XConnectionNumber (display);
347
348 #ifndef NO_SLOW_LINK_SUPPORT
349   // try to detect wether we have a local connection.
350   // assume unix domains socket == local, everything else not
351   // TODO: might want to check for inet/127.0.0.1
352   is_local = 0;
353   sockaddr_un sa;
354   socklen_t sl = sizeof (sa);
355
356   if (!getsockname (fd, (sockaddr *)&sa, &sl))
357     is_local = sa.sun_family == AF_LOCAL;
358 #endif
359
360   x_ev.start (fd, EVENT_READ);
361   fcntl (fd, F_SETFD, FD_CLOEXEC);
362
363   XSelectInput (display, root, PropertyChangeMask);
364
365   flush ();
366
367   return true;
368 }
369
370 void
371 rxvt_display::ref_next ()
372 {
373   // TODO: somehow check wether the database files/resources changed
374   // before re-loading/parsing
375   XrmDestroyDatabase (XrmGetDatabase (display));
376   XrmSetDatabase (display, get_resources ());
377 }
378
379 rxvt_display::~rxvt_display ()
380 {
381   if (!display)
382     return;
383
384 #ifdef POINTER_BLANK
385   XFreeCursor (display, blank_cursor);
386 #endif
387   x_ev.stop ();
388 #ifdef USE_XIM
389   xims.clear ();
390 #endif
391   XCloseDisplay (display);
392 }
393
394 #ifdef USE_XIM
395 void rxvt_display::im_change_cb ()
396 {
397   for (im_watcher **i = imw.begin (); i != imw.end (); ++i)
398     (*i)->call ();
399 }
400
401 void rxvt_display::im_change_check ()
402 {
403   // try to only call im_change_cb when a new input method
404   // registers, as xlib crashes due to a race otherwise.
405   Atom actual_type, *atoms;
406   int actual_format;
407   unsigned long nitems, bytes_after;
408
409   if (XGetWindowProperty (display, root, xa[XA_XIM_SERVERS], 0L, 1000000L,
410                           False, XA_ATOM, &actual_type, &actual_format,
411                           &nitems, &bytes_after, (unsigned char **)&atoms)
412       != Success )
413     return;
414
415   if (actual_type == XA_ATOM  && actual_format == 32)
416     for (int i = 0; i < nitems; i++)
417       if (XGetSelectionOwner (display, atoms[i]))
418         {
419           im_change_cb ();
420           break;
421         }
422
423   XFree (atoms);
424 }
425 #endif
426
427 void rxvt_display::x_cb (io_watcher &w, short revents)
428 {
429   do
430     {
431       XEvent xev;
432       XNextEvent (display, &xev);
433
434 #ifdef USE_XIM
435       if (!XFilterEvent (&xev, None))
436         {
437           if (xev.type == PropertyNotify
438               && xev.xany.window == root
439               && xev.xproperty.atom == xa[XA_XIM_SERVERS])
440             im_change_check ();
441 #endif
442           for (int i = xw.size (); i--; )
443             {
444               if (!xw[i])
445                 xw.erase_unordered (i);
446               else if (xw[i]->window == xev.xany.window)
447                 xw[i]->call (xev);
448             }
449 #ifdef USE_XIM
450         }
451 #endif
452     }
453   while (XEventsQueued (display, QueuedAlready));
454
455   XFlush (display);
456 }
457
458 void rxvt_display::flush ()
459 {
460   if (XEventsQueued (display, QueuedAlready))
461     x_cb (x_ev, EVENT_READ);
462
463   XFlush (display);
464 }
465
466 void rxvt_display::reg (xevent_watcher *w)
467 {
468   xw.push_back (w);
469   w->active = xw.size ();
470 }
471
472 void rxvt_display::unreg (xevent_watcher *w)
473 {
474   if (w->active)
475     xw[w->active - 1] = 0;
476 }
477
478 void rxvt_display::set_selection_owner (rxvt_term *owner)
479 {
480   if (selection_owner && selection_owner != owner)
481     selection_owner->selection_clear ();
482
483   selection_owner = owner;
484 }
485
486 #ifdef USE_XIM
487 void rxvt_display::reg (im_watcher *w)
488 {
489   imw.push_back (w);
490 }
491
492 void rxvt_display::unreg (im_watcher *w)
493 {
494   imw.erase (find (imw.begin (), imw.end (), w));
495 }
496
497 rxvt_xim *rxvt_display::get_xim (const char *locale, const char *modifiers)
498 {
499   char *id;
500   int l, m;
501
502   l = strlen (locale);
503   m = strlen (modifiers);
504
505   if (!(id = (char *)malloc (l + m + 2)))
506     return 0;
507
508   memcpy (id, locale, l); id[l] = '\n';
509   memcpy (id + l + 1, modifiers, m); id[l + m + 1] = 0;
510
511   rxvt_xim *xim = xims.get (id);
512
513   free (id);
514
515   return xim;
516 }
517
518 void rxvt_display::put_xim (rxvt_xim *xim)
519 {
520 #if XLIB_IS_RACEFREE
521   xims.put (xim);
522 #endif
523 }
524 #endif
525
526 Atom rxvt_display::atom (const char *name)
527 {
528   return XInternAtom (display, name, False);
529 }
530
531 /////////////////////////////////////////////////////////////////////////////
532
533 template class refcache<rxvt_display>;
534 refcache<rxvt_display> displays;
535
536 /////////////////////////////////////////////////////////////////////////////
537   
538 bool
539 rxvt_color::set (rxvt_screen *screen, const char *name)
540 {
541 #if XFT
542   int l = strlen (name);
543   rxvt_rgba r;
544   char eos;
545   int mult;
546
547   if (     l == 1+4*1 && 4 == sscanf (name, "#%1hx%1hx%1hx%1hx%c", &r.a, &r.r, &r.g, &r.b, &eos))
548     mult = rxvt_rgba::MAX_CC / 0x000f;
549   else if (l == 1+4*2 && 4 == sscanf (name, "#%2hx%2hx%2hx%2hx%c", &r.a, &r.r, &r.g, &r.b, &eos))
550     mult = rxvt_rgba::MAX_CC / 0x00ff;
551   else if (l == 1+4*4 && 4 == sscanf (name, "#%4hx%4hx%4hx%4hx%c", &r.a, &r.r, &r.g, &r.b, &eos))
552     mult = rxvt_rgba::MAX_CC / 0xffff;
553   else if (l == 4+5*4 && 4 == sscanf (name, "rgba:%hx/%hx/%hx/%hx%c", &r.r, &r.g, &r.b, &r.a, &eos))
554     mult = rxvt_rgba::MAX_CC / 0xffff;
555   else
556     return XftColorAllocName (screen->xdisp, screen->visual, screen->cmap, name, &c);
557
558   r.r *= mult; r.g *= mult; r.b *= mult; r.a *= mult;
559   return set (screen, r);
560 #else
561   XColor xc;
562
563   if (XParseColor (screen->xdisp, screen->cmap, name, &xc))
564     return set (screen, rxvt_rgba (xc.red, xc.green, xc.blue));
565
566   return false;
567 #endif
568 }
569
570 bool
571 rxvt_color::set (rxvt_screen *screen, rxvt_rgba rgba)
572 {
573 #if XFT
574   XRenderColor d;
575
576   d.red   = rgba.r;
577   d.green = rgba.g;
578   d.blue  = rgba.b;
579   d.alpha = rgba.a;
580
581   if (XftColorAllocValue (screen->xdisp, screen->visual, screen->cmap, &d, &c))
582     {
583       // FUCKING Xft gets it wrong, of course, fix it for the common case
584       // transparency users should eat shit and die, and then
585       // XRenderQueryPictIndexValues themselves plenty.
586       if (screen->depth == 32
587           && screen->visual->c_class == TrueColor
588           && screen->visual->red_mask   == 0x00ff0000
589           && screen->visual->green_mask == 0x0000ff00
590           && screen->visual->blue_mask  == 0x000000ff)
591         c.pixel = c.pixel & 0x00ffffffUL | ((rgba.a >> 8) << 24);
592
593       return true;
594     }
595
596   return false;
597 #else
598   XColor xc;
599
600   xc.red   = rgba.r;
601   xc.green = rgba.g;
602   xc.blue  = rgba.b;
603   xc.flags = DoRed | DoGreen | DoBlue;
604
605   if (XAllocColor (screen->xdisp, screen->cmap, &xc))
606     {
607       p = xc.pixel;
608       return true;
609     }
610
611   return false;
612 #endif
613 }
614
615 void 
616 rxvt_color::get (rxvt_screen *screen, rxvt_rgba &rgba)
617 {
618 #if XFT
619   rgba.r = c.color.red;
620   rgba.g = c.color.green;
621   rgba.b = c.color.blue;
622   rgba.a = c.color.alpha;
623 #else
624   XColor c;
625
626   c.pixel = p;
627   XQueryColor (screen->xdisp, screen->cmap, &c);
628
629   rgba.r = c.red;
630   rgba.g = c.green;
631   rgba.b = c.blue;
632   rgba.a = rxvt_rgba::MAX_CC;
633 #endif
634 }
635
636 void 
637 rxvt_color::free (rxvt_screen *screen)
638 {
639 #if XFT
640   XftColorFree (screen->xdisp, screen->visual, screen->cmap, &c);
641 #else
642   XFreeColors (screen->xdisp, screen->cmap, &p, 1, AllPlanes);
643 #endif
644 }
645
646 rxvt_color
647 rxvt_color::fade (rxvt_screen *screen, int percent)
648 {
649   rxvt_color faded;
650
651   rxvt_rgba c;
652   get (screen, c);
653
654   c.r = lerp (0, c.r, percent);
655   c.g = lerp (0, c.g, percent);
656   c.b = lerp (0, c.b, percent);
657
658   faded.set (screen, c);
659
660   return faded;
661 }
662
663 rxvt_color
664 rxvt_color::fade (rxvt_screen *screen, int percent, rxvt_color &fadeto)
665 {
666   rxvt_rgba c, fc;
667   rxvt_color faded;
668   
669   get (screen, c);
670   fadeto.get (screen, fc);
671
672   faded.set (
673     screen,
674     rxvt_rgba (
675       lerp (fc.r, c.r, percent),
676       lerp (fc.g, c.g, percent),
677       lerp (fc.b, c.b, percent),
678       lerp (fc.a, c.a, percent)
679     )
680   );
681
682   return faded;
683 }
684