*** empty log message ***
[dana/urxvt.git] / src / main.C
1 /*--------------------------------*-C-*---------------------------------*
2  * File:        main.C
3  *----------------------------------------------------------------------*
4  *
5  * All portions of code are copyright by their respective author/s.
6  * Copyright (c) 1992      John Bovey, University of Kent at Canterbury <jdb@ukc.ac.uk>
7  *                              - original version
8  * Copyright (c) 1994      Robert Nation <nation@rocket.sanders.lockheed.com>
9  *                              - extensive modifications
10  * Copyright (c) 1995      Garrett D'Amore <garrett@netcom.com>
11  * Copyright (c) 1997      mj olesen <olesen@me.QueensU.CA>
12  *                              - extensive modifications
13  * Copyright (c) 1997,1998 Oezguer Kesim <kesim@math.fu-berlin.de>
14  * Copyright (c) 1998-2001 Geoff Wing <gcw@pobox.com>
15  *                              - extensive modifications
16  * Copyright (c) 2003-2006 Marc Lehmann <pcg@goof.com>
17  *
18  * This program is free software; you can redistribute it and/or modify
19  * it under the terms of the GNU General Public License as published by
20  * the Free Software Foundation; either version 2 of the License, or
21  * (at your option) any later version.
22  *
23  * This program is distributed in the hope that it will be useful,
24  * but WITHOUT ANY WARRANTY; without even the implied warranty of
25  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
26  * GNU General Public License for more details.
27  *
28  * You should have received a copy of the GNU General Public License
29  * along with this program; if not, write to the Free Software
30  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
31  *---------------------------------------------------------------------*/
32
33 #include "../config.h"          /* NECESSARY */
34 #include "rxvt.h"               /* NECESSARY */
35 #include "keyboard.h"
36 #include "rxvtperl.h"
37
38 #include <limits>
39
40 #include <csignal>
41 #include <cstring>
42
43 #ifdef TTY_GID_SUPPORT
44 # include <grp.h>
45 #endif
46
47 #ifdef HAVE_TERMIOS_H
48 # include <termios.h>
49 #endif
50
51 #if (defined(HAVE_SETEUID) || defined(HAVE_SETREUID)) && !defined(__CYGWIN32__)
52 static uid_t saved_euid;
53 static gid_t saved_egid;
54 #endif
55
56 bool
57 rxvt_tainted ()
58 {
59 #if (defined(HAVE_SETEUID) || defined(HAVE_SETREUID)) && !defined(__CYGWIN32__)
60   return getuid () != saved_euid || getgid () != saved_egid;
61 #else
62   return false;
63 #endif
64 }
65
66 vector<rxvt_term *> rxvt_term::termlist;
67
68 static char curlocale[128], savelocale[128];
69
70 bool
71 rxvt_set_locale (const char *locale)
72 {
73   if (!locale || !strncmp (locale, curlocale, 128))
74     return false;
75
76   strncpy (curlocale, locale, 128);
77   setlocale (LC_CTYPE, curlocale);
78   return true;
79 }
80
81 void
82 rxvt_push_locale (const char *locale)
83 {
84   strcpy (savelocale, curlocale);
85   rxvt_set_locale (locale);
86 }
87
88 void
89 rxvt_pop_locale ()
90 {
91   rxvt_set_locale (savelocale);
92 }
93
94 #if ENABLE_COMBINING
95 class rxvt_composite_vec rxvt_composite;
96
97 text_t rxvt_composite_vec::compose (unicode_t c1, unicode_t c2)
98 {
99   compose_char *cc;
100   
101   // break compose chains, as stupid readline really likes to duplicate
102   // composing characters for some reason near the end of a line.
103   cc = (*this)[c1];
104   while (cc)
105     {
106       if (cc->c2 == c2) return c1;
107       cc = (*this)[cc->c1];
108     }
109
110   // check to see wether this combination already exists otherwise
111   for (cc = v.end (); cc-- > v.begin (); )
112     {
113       if (cc->c1 == c1 && cc->c2 == c2)
114         return COMPOSE_LO + (cc - v.begin ());
115     }
116
117   // allocate a new combination
118   if (v.size () == COMPOSE_HI - COMPOSE_LO + 1)
119     {
120       static int seen;
121
122       if (!seen++)
123         fprintf (stderr, "too many unrepresentable composite characters, try --enable-unicode3\n");
124
125       return REPLACEMENT_CHAR;
126     }
127
128   v.push_back (compose_char (c1, c2));
129
130   return v.size () - 1 + COMPOSE_LO;
131 }
132
133 int rxvt_composite_vec::expand (unicode_t c, wchar_t *r)
134 {
135   compose_char *cc = (*this)[c];
136
137   if (!cc)
138     {
139       if (r) *r = c;
140       return 1;
141     }
142
143   int len = expand (cc->c1, r);
144
145   if (r) r += len;
146
147   if (cc->c2 != NOCHAR)
148     {
149       len++;
150       if (r) *r++ = cc->c2;
151     }
152
153   return len;
154
155 }
156 #endif
157
158 rxvt_term::rxvt_term ()
159     :
160 #if TRANSPARENT
161     rootwin_ev (this, &rxvt_term::rootwin_cb),
162 #endif
163 #ifdef HAVE_SCROLLBARS
164     scrollbar_ev (this, &rxvt_term::x_cb),
165 #endif
166 #ifdef MENUBAR
167     menubar_ev (this, &rxvt_term::x_cb),
168 #endif
169 #ifdef CURSOR_BLINK
170     cursor_blink_ev (this, &rxvt_term::cursor_blink_cb),
171 #endif
172 #ifdef TEXT_BLINK
173     text_blink_ev (this, &rxvt_term::text_blink_cb),
174 #endif
175 #ifndef NO_SCROLLBAR_BUTTON_CONTINUAL_SCROLLING
176     cont_scroll_ev (this, &rxvt_term::cont_scroll_cb),
177 #endif
178 #ifdef SELECTION_SCROLLING
179     sel_scroll_ev (this, &rxvt_term::sel_scroll_cb),
180 #endif
181 #if defined(MOUSE_WHEEL) && defined(MOUSE_SLIP_WHEELING)
182     slip_wheel_ev (this, &rxvt_term::slip_wheel_cb),
183 #endif
184 #ifdef POINTER_BLANK
185     pointer_ev (this, &rxvt_term::pointer_cb),
186 #endif
187 #ifdef USE_XIM
188     im_ev (this, &rxvt_term::im_cb),
189 #endif
190     termwin_ev (this, &rxvt_term::x_cb),
191     vt_ev (this, &rxvt_term::x_cb),
192     check_ev (this, &rxvt_term::check_cb),
193     flush_ev (this, &rxvt_term::flush_cb),
194     destroy_ev (this, &rxvt_term::destroy_cb),
195     pty_ev (this, &rxvt_term::pty_cb),
196     incr_ev (this, &rxvt_term::incr_cb)
197 {
198   cmdbuf_ptr = cmdbuf_endp = cmdbuf_base;
199
200   termlist.push_back (this);
201
202 #ifdef KEYSYM_RESOURCE
203   keyboard = new keyboard_manager;
204
205   if (!keyboard)
206     rxvt_fatal ("out of memory, aborting.\n");
207 #endif
208 }
209
210 // clean up the most important stuff, do *not* call x or free mem etc.
211 // for use before an emergency exit
212 void rxvt_term::emergency_cleanup ()
213 {
214   if (cmd_pid)
215     kill (-cmd_pid, SIGHUP);
216
217 #ifdef UTMP_SUPPORT
218   privileged_utmp (RESTORE);
219 #endif
220
221   pty.put ();
222 }
223
224 rxvt_term::~rxvt_term ()
225 {
226   HOOK_INVOKE ((this, HOOK_DESTROY, DT_END));
227
228   termlist.erase (find (termlist.begin (), termlist.end(), this));
229
230   emergency_cleanup ();
231
232 #if ENABLE_STYLES
233   for (int i = RS_styleCount; --i; )
234     if (fontset[i] != fontset[0])
235       delete fontset[i];
236 #endif
237   delete fontset[0];
238
239   if (display)
240     {
241       dDisp;
242
243       selection_clear ();
244
245 #ifdef USE_XIM
246       im_destroy ();
247 #endif
248 #ifdef MENUBAR
249       if (menubarGC)    XFreeGC (disp, menubarGC);
250 #endif
251 #ifdef XTERM_SCROLLBAR
252       if (xscrollbarGC) XFreeGC (disp, xscrollbarGC);
253       if (ShadowGC)     XFreeGC (disp, ShadowGC);
254 #endif
255 #ifdef PLAIN_SCROLLBAR
256       if (pscrollbarGC) XFreeGC (disp, pscrollbarGC);
257 #endif
258 #ifdef NEXT_SCROLLBAR
259       if (blackGC)      XFreeGC (disp, blackGC);
260       if (whiteGC)      XFreeGC (disp, whiteGC);
261       if (grayGC)       XFreeGC (disp, grayGC);
262       if (darkGC)       XFreeGC (disp, darkGC);
263       if (stippleGC)    XFreeGC (disp, stippleGC);
264       if (dimple)       XFreePixmap (disp, dimple);
265       if (upArrow)      XFreePixmap (disp, upArrow);
266       if (downArrow)    XFreePixmap (disp, downArrow);
267       if (upArrowHi)    XFreePixmap (disp, upArrowHi);
268       if (downArrowHi)  XFreePixmap (disp, downArrowHi);
269 #endif
270 #if defined(MENUBAR) || defined(RXVT_SCROLLBAR)
271       if (topShadowGC)  XFreeGC (disp, topShadowGC);
272       if (botShadowGC)  XFreeGC (disp, botShadowGC);
273       if (scrollbarGC)  XFreeGC (disp, scrollbarGC);
274 #endif
275       if (gc)   XFreeGC (disp, gc);
276
277 #if defined(MENUBAR) && (MENUBAR_MAX > 1)
278       delete menuBar.drawable;
279       //if (menuBar.win)
280       //  XDestroyWindow (disp, menuBar.win);
281 #endif
282       delete drawable;
283       // destroy all windows
284       if (parent[0])
285         XDestroyWindow (disp, parent[0]);
286     }
287
288   // TODO: free pixcolours, colours should become part of rxvt_display
289   delete pix_colors_focused;
290 #if OFF_FOCUS_FADING
291   delete pix_colors_unfocused;
292 #endif
293
294   displays.put (display);
295
296   scr_release ();
297
298   /* clear all resources */
299   for (int i = 0; i < allocated.size (); i++)
300     free (allocated [i]);
301
302   free (selection.text);
303   // TODO: manage env vars in child only(!)
304   free (env_windowid);
305   free (env_display);
306   free (env_term);
307   free (env_colorfgbg);
308   free (locale);
309   free (v_buffer);
310   free (incr_buf);
311
312   delete envv;
313   delete argv;
314
315 #ifdef KEYSYM_RESOURCE
316   delete keyboard;
317 #endif
318 }
319
320 void
321 rxvt_term::child_exit ()
322 {
323   cmd_pid = 0;
324
325   if (!OPTION (Opt_hold))
326     destroy ();
327 }
328
329 void
330 rxvt_term::destroy ()
331 {
332   if (destroy_ev.active)
333     return;
334
335 #if ENABLE_OVERLAY
336   scr_overlay_off ();
337 #endif
338
339   if (display)
340     {
341 #if USE_XIM
342       im_ev.stop (display);
343 #endif
344 #if HAVE_SCROLLBARS
345       scrollbar_ev.stop (display);
346 #endif
347 #if MENUBAR
348       menubar_ev.stop (display);
349 #endif
350 #if TRANSPARENT
351       rootwin_ev.stop (display);
352 #endif
353       incr_ev.stop ();
354       termwin_ev.stop (display);
355       vt_ev.stop (display);
356     }
357
358   check_ev.stop ();
359   pty_ev.stop ();
360 #ifdef CURSOR_BLINK
361   cursor_blink_ev.stop ();
362 #endif
363 #ifdef TEXT_BLINK
364   text_blink_ev.stop ();
365 #endif
366 #ifndef NO_SCROLLBAR_BUTTON_CONTINUAL_SCROLLING
367   cont_scroll_ev.stop ();
368 #endif
369 #ifdef SELECTION_SCROLLING
370   sel_scroll_ev.stop ();
371 #endif
372 #ifdef POINTER_BLANK
373   pointer_ev.stop ();
374 #endif
375
376   destroy_ev.start (0);
377 }
378
379 void
380 rxvt_term::destroy_cb (time_watcher &w)
381 {
382   SET_R (this);
383
384   delete this;
385 }
386
387 /*----------------------------------------------------------------------*/
388 /*
389  * Exit gracefully, clearing the utmp entry and restoring tty attributes
390  * TODO: if debugging, this should free up any known resources if we can
391  */
392 static XErrorHandler old_xerror_handler;
393
394 static void
395 rxvt_emergency_cleanup ()
396 {
397   for (rxvt_term **t = rxvt_term::termlist.begin (); t < rxvt_term::termlist.end (); t++)
398     (*t)->emergency_cleanup ();
399 }
400
401 #if ENABLE_FRILLS
402 static void
403 print_x_error (Display *dpy, XErrorEvent *event)
404 {
405     char buffer[BUFSIZ];
406     char mesg[BUFSIZ];
407     char number[32];
408     char *mtype = "XlibMessage";
409     XGetErrorText(dpy, event->error_code, buffer, BUFSIZ);
410     XGetErrorDatabaseText(dpy, mtype, "XError", "X Error", mesg, BUFSIZ);
411     rxvt_warn ("An X Error occured, trying to continue after report.\n");
412     rxvt_warn ("%s:  %s\n", mesg, buffer);
413     XGetErrorDatabaseText(dpy, mtype, "MajorCode", "Request Major code %d", mesg, BUFSIZ);
414     rxvt_warn (strncat (mesg, "\n", BUFSIZ), event->request_code);
415     sprintf(number, "%d", event->request_code);
416     XGetErrorDatabaseText(dpy, "XRequest", number, "", buffer, BUFSIZ);
417     rxvt_warn ("(which is %s)\n", buffer);
418     if (event->request_code >= 128) {
419         XGetErrorDatabaseText(dpy, mtype, "MinorCode", "Request Minor code %d",
420                               mesg, BUFSIZ);
421         rxvt_warn (strncat (mesg, "\n", BUFSIZ), event->minor_code);
422     }
423     if ((event->error_code == BadWindow) ||
424                (event->error_code == BadPixmap) ||
425                (event->error_code == BadCursor) ||
426                (event->error_code == BadFont) ||
427                (event->error_code == BadDrawable) ||
428                (event->error_code == BadColor) ||
429                (event->error_code == BadGC) ||
430                (event->error_code == BadIDChoice) ||
431                (event->error_code == BadValue) ||
432                (event->error_code == BadAtom)) {
433         if (event->error_code == BadValue)
434             XGetErrorDatabaseText(dpy, mtype, "Value", "Value 0x%x",
435                                   mesg, BUFSIZ);
436         else if (event->error_code == BadAtom)
437             XGetErrorDatabaseText(dpy, mtype, "AtomID", "AtomID 0x%x",
438                                   mesg, BUFSIZ);
439         else
440             XGetErrorDatabaseText(dpy, mtype, "ResourceID", "ResourceID 0x%x",
441                                   mesg, BUFSIZ);
442         rxvt_warn (strncat (mesg, "\n", BUFSIZ), event->resourceid);
443     }
444     XGetErrorDatabaseText(dpy, mtype, "ErrorSerial", "Error Serial #%d", 
445                           mesg, BUFSIZ);
446     rxvt_warn (strncat (mesg, "\n", BUFSIZ), event->serial);
447 }
448 #endif
449
450 int
451 rxvt_xerror_handler (Display *display, XErrorEvent *event)
452 {
453   if (GET_R->allowedxerror == -1)
454     GET_R->allowedxerror = event->error_code;
455   else
456     {
457       // GET_R is most likely not the terminal which caused the error,
458       // so just output the error and continue
459 #if ENABLE_FRILLS
460       print_x_error (display, event);
461 #else
462       old_xerror_handler (display, event);
463 #endif
464     }
465
466   return 0;
467 }
468
469 int
470 rxvt_xioerror_handler (Display *display)
471 {
472   rxvt_warn ("X connection to '%s' broken, unable to recover, exiting.\n",
473              DisplayString (display));
474   rxvt_emergency_cleanup ();
475   _exit (EXIT_FAILURE);
476 }
477
478 /*----------------------------------------------------------------------*/
479 bool
480 rxvt_term::init (int argc, const char *const *argv)
481 {
482   SET_R (this);
483   TEMP_ENV; // few things in X do not call setlocale :(
484
485   set_locale ("");
486
487   if (!init_vars ())
488     return false;
489
490   init_secondary ();
491
492   const char **cmd_argv = init_resources (argc, argv);
493
494 #ifdef KEYSYM_RESOURCE
495   keyboard->register_done ();
496 #endif
497
498 #if MENUBAR_MAX
499   menubar_read (rs[Rs_menu]);
500 #endif
501 #ifdef HAVE_SCROLLBARS
502   if (OPTION (Opt_scrollBar))
503     scrollBar.setIdle ();    /* set existence for size calculations */
504 #endif
505
506 #if ENABLE_PERL
507   if (!rs[Rs_perl_ext_1])
508     rs[Rs_perl_ext_1] = "default";
509
510   if ((rs[Rs_perl_ext_1] && *rs[Rs_perl_ext_1])
511       || (rs[Rs_perl_ext_2] && *rs[Rs_perl_ext_2])
512       || (rs[Rs_perl_eval] && *rs[Rs_perl_eval]))
513     {
514 #if (defined(HAVE_SETEUID) || defined(HAVE_SETREUID)) && !defined(__CYGWIN32__)
515       // ignore some perl-related arguments if some bozo installed us set[ug]id
516       if (rxvt_tainted ())
517         {
518           if ((rs[Rs_perl_lib] && *rs[Rs_perl_lib])
519               || (rs[Rs_perl_eval] && *rs[Rs_perl_eval]))
520             {
521               rxvt_warn ("running with elevated privileges: ignoring perl-lib and perl-eval.\n");
522               rs[Rs_perl_lib]  = 0;
523               rs[Rs_perl_eval] = 0;
524             }
525         }
526 #endif
527       rxvt_perl.init ();
528       setlocale (LC_CTYPE, curlocale); // perl init destroys this info
529       HOOK_INVOKE ((this, HOOK_INIT, DT_END));
530     }
531 #endif
532
533   create_windows (argc, argv);
534
535   dDisp;
536
537   init_xlocale ();
538
539   scr_reset (); // initialize screen
540
541 #if 0
542   XSynchronize (disp, True);
543 #endif
544
545 #ifdef HAVE_SCROLLBARS
546   if (OPTION (Opt_scrollBar))
547     resize_scrollbar ();      /* create and map scrollbar */
548 #endif
549 #if (MENUBAR_MAX)
550   if (menubar_visible ())
551     XMapWindow (disp, menuBar.win);
552 #endif
553 #ifdef TRANSPARENT
554   if (OPTION (Opt_transparent))
555     {
556       XSelectInput (disp, display->root, PropertyChangeMask);
557       check_our_parents ();
558       rootwin_ev.start (display, display->root);
559     }
560 #endif
561
562   XMapWindow (disp, vt);
563   XMapWindow (disp, parent[0]);
564
565   set_colorfgbg ();
566
567   init_command (cmd_argv);
568
569   free (cmd_argv);
570
571   if (pty.pty >= 0)
572     pty_ev.start (pty.pty, EVENT_READ);
573
574   check_ev.start ();
575
576   HOOK_INVOKE ((this, HOOK_START, DT_END));
577
578   return true;
579 }
580
581 static struct sig_handlers
582 {
583   sig_watcher sw_chld, sw_term, sw_int;
584   
585   void sig_chld (sig_watcher &w)
586   {
587     // we are being called for every SIGCHLD, find the corresponding term
588     int pid;
589
590     while ((pid = waitpid (-1, NULL, WNOHANG)) > 0)
591       for (rxvt_term **t = rxvt_term::termlist.begin (); t < rxvt_term::termlist.end (); t++)
592         if (pid == (*t)->cmd_pid)
593           {
594             (*t)->child_exit ();
595             break;
596           }
597   }
598
599   /*
600    * Catch a fatal signal and tidy up before quitting
601    */
602   void
603   sig_term (sig_watcher &w)
604   {
605 #ifdef DEBUG_CMD
606     rxvt_warn ("caught signal %d, exiting.\n", w.signum);
607 #endif
608     rxvt_emergency_cleanup ();
609     signal (w.signum, SIG_DFL);
610     kill (getpid (), w.signum);
611   }
612
613   sig_handlers ()
614   : sw_chld (this, &sig_handlers::sig_chld),
615     sw_term (this, &sig_handlers::sig_term),
616     sw_int  (this, &sig_handlers::sig_term)
617   {
618   }
619 } sig_handlers;
620
621 char **rxvt_environ; // startup environment
622
623 void
624 rxvt_init ()
625 {
626   rxvt_environ = environ;
627
628   /*
629    * Save and then give up any super-user privileges
630    * If we need privileges in any area then we must specifically request it.
631    * We should only need to be root in these cases:
632    *  1.  write utmp entries on some systems
633    *  2.  chown tty on some systems
634    */
635   rxvt_privileges (SAVE);
636   rxvt_privileges (IGNORE);
637
638   signal (SIGHUP,  SIG_IGN);
639   signal (SIGPIPE, SIG_IGN);
640
641   sig_handlers.sw_chld.start (SIGCHLD);
642   sig_handlers.sw_term.start (SIGTERM);
643   sig_handlers.sw_int.start  (SIGINT);
644
645   /* need to trap SIGURG for SVR4 (Unixware) rlogin */
646   /* signal (SIGURG, SIG_DFL); */
647
648   old_xerror_handler = XSetErrorHandler ((XErrorHandler) rxvt_xerror_handler);
649   // TODO: handle this with exceptions and tolerate the memory loss
650   XSetIOErrorHandler (rxvt_xioerror_handler);
651
652   XrmInitialize ();
653 }
654
655 /* ------------------------------------------------------------------------- *
656  *                         MEMORY ALLOCATION WRAPPERS                        *
657  * ------------------------------------------------------------------------- */
658 void *
659 rxvt_malloc (size_t size)
660 {
661   void *p = malloc (size);
662
663   if (!p)
664     rxvt_fatal ("memory allocation failure. aborting.\n");
665
666   return p;
667 }
668
669 void *
670 rxvt_calloc (size_t number, size_t size)
671 {
672   void *p = calloc (number, size);
673
674   if (!p)
675     rxvt_fatal ("memory allocation failure. aborting.\n");
676
677   return p;
678 }
679
680 void           *
681 rxvt_realloc (void *ptr, size_t size)
682 {
683   void *p = realloc (ptr, size);
684
685   if (!p)
686     rxvt_fatal ("memory allocation failure. aborting.\n");
687
688   return p;
689 }
690
691 /* ------------------------------------------------------------------------- *
692  *                            PRIVILEGED OPERATIONS                          *
693  * ------------------------------------------------------------------------- */
694 /* take care of suid/sgid super-user (root) privileges */
695 void
696 rxvt_privileges (rxvt_privaction action)
697 {
698 #if ! defined(__CYGWIN32__)
699 # if !defined(HAVE_SETEUID) && defined(HAVE_SETREUID)
700   /* setreuid () is the poor man's setuid (), seteuid () */
701 #  define seteuid(a)    setreuid(-1, (a))
702 #  define setegid(a)    setregid(-1, (a))
703 #  define HAVE_SETEUID
704 # endif
705 # ifdef HAVE_SETEUID
706   switch (action)
707     {
708       case IGNORE:
709         /*
710          * change effective uid/gid - not real uid/gid - so we can switch
711          * back to root later, as required
712          */
713         setegid (getgid ());
714         seteuid (getuid ());
715         break;
716       case SAVE:
717         saved_egid = getegid ();
718         saved_euid = geteuid ();
719         break;
720       case RESTORE:
721         setegid (saved_egid);
722         seteuid (saved_euid);
723         break;
724     }
725 # else
726   switch (action)
727     {
728       case IGNORE:
729         setgid (getgid ());
730         setuid (getuid ());
731         /* FALLTHROUGH */
732       case SAVE:
733         /* FALLTHROUGH */
734       case RESTORE:
735         break;
736     }
737 # endif
738 #endif
739 }
740
741 #ifdef UTMP_SUPPORT
742 void
743 rxvt_term::privileged_utmp (rxvt_privaction action)
744 {
745   if (OPTION (Opt_utmpInhibit)
746       || !pty.name || !*pty.name)
747     return;
748
749   rxvt_privileges (RESTORE);
750
751   if (action == SAVE)
752     makeutent (pty.name, rs[Rs_display_name]);
753   else
754     cleanutent ();
755
756   rxvt_privileges (IGNORE);
757 }
758 #endif
759
760 /*----------------------------------------------------------------------*/
761 /*
762  * window size/position calculcations for XSizeHint and other storage.
763  * if width/height are non-zero then override calculated width/height
764  */
765 void
766 rxvt_term::window_calc (unsigned int newwidth, unsigned int newheight)
767 {
768   short recalc_x, recalc_y;
769   int x, y, sb_w, mb_h, flags;
770   unsigned int w, h;
771   unsigned int max_width, max_height;
772   dDisp;
773
774   D_SIZE ((stderr, "< Cols/Rows: %3d x %3d ; Width/Height: %4d x %4d",
775           ncol, nrow, szHint.width, szHint.height));
776
777   szHint.flags = PMinSize | PResizeInc | PBaseSize | PWinGravity;
778   szHint.win_gravity = NorthWestGravity;
779   /* szHint.min_aspect.x = szHint.min_aspect.y = 1; */
780
781   recalc_x = recalc_y = 0;
782   flags = 0;
783
784   if (!parsed_geometry)
785     {
786       parsed_geometry = 1;
787
788       if (rs[Rs_geometry])
789         flags = XParseGeometry (rs[Rs_geometry], &x, &y, &w, &h);
790
791       if (flags & WidthValue)
792         {
793           ncol = clamp (w, 0, std::numeric_limits<int16_t>::max ());
794           szHint.flags |= USSize;
795         }
796
797       if (flags & HeightValue)
798         {
799           nrow = clamp (h, 0, std::numeric_limits<int16_t>::max ());
800           szHint.flags |= USSize;
801         }
802
803       if (flags & XValue)
804         {
805           szHint.x = x;
806           szHint.flags |= USPosition;
807
808           if (flags & XNegative)
809             {
810               recalc_x = 1;
811               szHint.win_gravity = NorthEastGravity;
812             }
813         }
814
815       if (flags & YValue)
816         {
817           szHint.y = y;
818           szHint.flags |= USPosition;
819
820           if (flags & YNegative)
821             {
822               recalc_y = 1;
823
824               if (szHint.win_gravity == NorthEastGravity)
825                 szHint.win_gravity = SouthEastGravity;
826               else
827                 szHint.win_gravity = SouthWestGravity;
828             }
829         }
830     }
831
832   /* TODO: BOUNDS */
833   width = ncol * fwidth;
834   height = nrow * fheight;
835   max_width = MAX_COLS * fwidth;
836   max_height = MAX_ROWS * fheight;
837
838   szHint.base_width = szHint.base_height = 2 * int_bwidth;
839
840   sb_w = mb_h = 0;
841   window_vt_x = window_vt_y = int_bwidth;
842
843   if (scrollbar_visible ())
844     {
845       sb_w = scrollbar_TotalWidth ();
846       szHint.base_width += sb_w;
847       if (!OPTION (Opt_scrollBar_right))
848         window_vt_x += sb_w;
849     }
850
851   if (menubar_visible ())
852     {
853       mb_h = menuBar_TotalHeight ();
854       szHint.base_height += mb_h;
855       window_vt_y += mb_h;
856     }
857
858   szHint.width_inc = fwidth;
859   szHint.height_inc = fheight;
860   szHint.min_width = szHint.base_width + szHint.width_inc;
861   szHint.min_height = szHint.base_height + szHint.height_inc;
862
863   if (newwidth && newwidth - szHint.base_width < max_width)
864     {
865       szHint.width = newwidth;
866       width = newwidth - szHint.base_width;
867     }
868   else
869     {
870       min_it (width, max_width);
871       szHint.width = szHint.base_width + width;
872     }
873
874   if (newheight && newheight - szHint.base_height < max_height)
875     {
876       szHint.height = newheight;
877       height = newheight - szHint.base_height;
878     }
879   else
880     {
881       min_it (height, max_height);
882       szHint.height = szHint.base_height + height;
883     }
884
885   if (scrollbar_visible () && OPTION (Opt_scrollBar_right))
886     window_sb_x = szHint.width - sb_w;
887
888   if (recalc_x)
889     szHint.x += DisplayWidth  (disp, display->screen) - szHint.width  - 2 * ext_bwidth;
890   if (recalc_y)
891     szHint.y += DisplayHeight (disp, display->screen) - szHint.height - 2 * ext_bwidth;
892
893   ncol = width / fwidth;
894   nrow = height / fheight;
895   D_SIZE ((stderr, "> Cols/Rows: %3d x %3d ; Width/Height: %4d x %4d",
896           ncol, nrow, szHint.width,
897           szHint.height));
898   return;
899 }
900
901 /*----------------------------------------------------------------------*/
902 /*
903  * Tell the teletype handler what size the window is.
904  * Called after a window size change.
905  */
906 void
907 rxvt_term::tt_winch ()
908 {
909   if (pty.pty < 0)
910     return;
911
912   struct winsize ws;
913
914   ws.ws_col = ncol;
915   ws.ws_row = nrow;
916   ws.ws_xpixel = width;
917   ws.ws_ypixel = height;
918   (void)ioctl (pty.pty, TIOCSWINSZ, &ws);
919
920 #if 0
921   // TIOCSWINSZ⎈ is supposed to do this automatically and correctly
922   if (cmd_pid)               /* force through to the command */
923     kill (-cmd_pid, SIGWINCH);
924 #endif
925 }
926
927 /*----------------------------------------------------------------------*/
928 /* set_fonts () - load and set the various fonts
929  *
930  * init = 1   - initialize
931  *
932  * fontname == FONT_UP  - switch to bigger font
933  * fontname == FONT_DN  - switch to smaller font
934  */
935 bool
936 rxvt_term::set_fonts ()
937 {
938   rxvt_fontset *fs = new rxvt_fontset (this);
939   rxvt_fontprop prop;
940
941   if (!fs
942       || !fs->populate (rs[Rs_font] ? rs[Rs_font] : "fixed")
943       || !fs->realize_font (1))
944     {
945       delete fs;
946       return false;
947     }
948
949 #if ENABLE_STYLES
950   for (int i = RS_styleCount; --i; )
951     if (fontset[i] != fontset[0])
952       delete fontset[i];
953 #endif
954
955   delete fontset[0];
956   fontset[0] = fs;
957
958   prop = (*fs)[1]->properties ();
959   prop.height += lineSpace;
960   fs->set_prop (prop);
961
962   fwidth  = prop.width;
963   fheight = prop.height;
964   fbase   = prop.ascent;
965
966   for (int style = 1; style < 4; style++)
967     {
968 #if ENABLE_STYLES
969       const char *res = rs[Rs_font + style];
970
971       if (res && !*res)
972         fontset[style] = fontset[0];
973       else
974         {
975           fontset[style] = fs = new rxvt_fontset (this);
976           rxvt_fontprop prop2 = prop;
977
978           if (res)
979             prop2.weight = prop2.slant = rxvt_fontprop::unset;
980           else
981             {
982               res = fontset[0]->fontdesc;
983
984               if (SET_STYLE (0, style) & RS_Bold)   prop2.weight = rxvt_fontprop::bold;
985               if (SET_STYLE (0, style) & RS_Italic) prop2.slant  = rxvt_fontprop::italic;
986             }
987
988           fs->populate (res);
989           fs->set_prop (prop2);
990         }
991 #else
992       fontset[style] = fontset[0];
993 #endif
994     }
995
996   if (parent[0])
997     {
998       resize_all_windows (0, 0, 0);
999       scr_remap_chars ();
1000       scr_touch (true);
1001     }   
1002
1003   return true;
1004 }
1005
1006 void rxvt_term::set_string_property (Atom prop, const char *str, int len)
1007 {
1008   XChangeProperty (display->display, parent[0],
1009                    prop, XA_STRING, 8, PropModeReplace,
1010                    (const unsigned char *)str, len >= 0 ? len : strlen (str));
1011 }
1012
1013 void rxvt_term::set_utf8_property (Atom prop, const char *str, int len)
1014 {
1015   wchar_t *ws = rxvt_mbstowcs (str, len);
1016   char *s = rxvt_wcstoutf8 (ws);
1017
1018   XChangeProperty (display->display, parent[0],
1019                    prop, xa[XA_UTF8_STRING], 8, PropModeReplace,
1020                    (const unsigned char *)s, strlen (s));
1021
1022   free (s);
1023   free (ws);
1024 }
1025
1026 /*----------------------------------------------------------------------*/
1027 /*----------------------------------------------------------------------*/
1028 /* xterm sequences - title, iconName, color (exptl) */
1029 void
1030 rxvt_term::set_title (const char *str)
1031 {
1032   set_string_property (XA_WM_NAME, str);
1033 #if ENABLE_EWMH
1034   set_utf8_property (xa[XA_NET_WM_NAME], str);
1035 #endif
1036 }
1037
1038 void
1039 rxvt_term::set_icon_name (const char *str)
1040 {
1041   set_string_property (XA_WM_ICON_NAME, str);
1042 #if ENABLE_EWMH
1043   set_utf8_property (xa[XA_NET_WM_ICON_NAME], str);
1044 #endif
1045 }
1046
1047 #ifdef XTERM_COLOR_CHANGE
1048 void
1049 rxvt_term::set_window_color (int idx, const char *color)
1050 {
1051   rxvt_color xcol;
1052   int i;
1053
1054   if (color == NULL || *color == '\0')
1055     return;
1056
1057   /* handle color aliases */
1058   if (isdigit (*color))
1059     {
1060       i = atoi (color);
1061
1062       if (i >= 8 && i <= 15)
1063         {        /* bright colors */
1064           i -= 8;
1065           pix_colors_focused[idx] = pix_colors_focused[minBrightCOLOR + i];
1066           SET_PIXCOLOR (idx);
1067           goto done;
1068         }
1069
1070       if (i >= 0 && i <= 7)
1071         { /* normal colors */
1072           pix_colors_focused[idx] = pix_colors_focused[minCOLOR + i];
1073           SET_PIXCOLOR (idx);
1074           goto done;
1075         }
1076     }
1077
1078   if (!rXParseAllocColor (&xcol, color))
1079     return;
1080
1081   /* XStoreColor (display->display, display->cmap, XColor*); */
1082
1083   /*
1084    * FIXME: should free colors here, but no idea how to do it so instead,
1085    * so just keep gobbling up the colormap
1086    */
1087 # if 0
1088   for (i = Color_Black; i <= Color_White; i++)
1089     if (pix_colors[idx] == pix_colors[i])
1090       break;
1091   if (i > Color_White)
1092     {
1093       /* fprintf (stderr, "XFreeColors: pix_colors [%d] = %lu\n", idx, pix_colors [idx]); */
1094       XFreeColors (display->display, display->cmap, (pix_colors + idx), 1,
1095                   DisplayPlanes (display->display, display->screen));
1096     }
1097 # endif
1098
1099   pix_colors_focused[idx] = xcol;
1100   SET_PIXCOLOR (idx);
1101
1102   /* XSetWindowAttributes attr; */
1103   /* Cursor cursor; */
1104 done:
1105
1106 #if OFF_FOCUS_FADING
1107   if (rs[Rs_fade])
1108     pix_colors_unfocused[idx] = pix_colors_focused[idx].fade (display, atoi (rs[Rs_fade]), pix_colors[Color_fade]);
1109 #endif
1110
1111   /*TODO: handle Color_BD, scrollbar background, etc. */
1112
1113   recolour_cursor ();
1114   scr_recolour ();
1115 }
1116
1117 #else
1118 # define set_window_color (idx,color)   ((void)0)
1119 #endif                          /* XTERM_COLOR_CHANGE */
1120
1121 void
1122 rxvt_term::recolour_cursor ()
1123 {
1124   XColor xcol[2];
1125
1126   xcol[0].pixel = ISSET_PIXCOLOR (Color_pointer_fg)
1127                      ? pix_colors_focused[Color_pointer_fg]
1128                      : pix_colors_focused[Color_fg];
1129   xcol[1].pixel = ISSET_PIXCOLOR (Color_pointer_bg)
1130                      ? pix_colors_focused[Color_pointer_bg]
1131                      : pix_colors_focused[Color_bg];
1132
1133   XQueryColors (display->display, display->cmap, xcol, 2);
1134   XRecolorCursor (display->display, TermWin_cursor, xcol + 0, xcol + 1);
1135 }
1136
1137 /*----------------------------------------------------------------------*/
1138 /*
1139  * find if fg/bg matches any of the normal (low-intensity) colors
1140  */
1141 void
1142 rxvt_term::set_colorfgbg ()
1143 {
1144   unsigned int i;
1145   const char *xpmb = "\0";
1146   char fstr[sizeof ("default") + 1], bstr[sizeof ("default") + 1];
1147
1148   env_colorfgbg = (char *)rxvt_malloc (sizeof ("COLORFGBG=default;default;bg") + 1);
1149   strcpy (fstr, "default");
1150   strcpy (bstr, "default");
1151   for (i = Color_Black; i <= Color_White; i++)
1152     if (pix_colors[Color_fg] == pix_colors[i])
1153       {
1154         sprintf (fstr, "%d", (i - Color_Black));
1155         break;
1156       }
1157
1158   for (i = Color_Black; i <= Color_White; i++)
1159     if (pix_colors[Color_bg] == pix_colors[i])
1160       {
1161         sprintf (bstr, "%d", (i - Color_Black));
1162 #ifdef XPM_BACKGROUND
1163         xpmb = "default;";
1164 #endif
1165         break;
1166       }
1167
1168   sprintf (env_colorfgbg, "COLORFGBG=%s;%s%s", fstr, xpmb, bstr);
1169 }
1170
1171 /*----------------------------------------------------------------------*/
1172
1173 int
1174 rxvt_term::rXParseAllocColor (rxvt_color *screen_in_out, const char *colour)
1175 {
1176   if (!screen_in_out->set (display, colour))
1177     {
1178       rxvt_warn ("can't get colour '%s', continuing without.\n", colour);
1179       return false;
1180     }
1181
1182   return true;
1183 }
1184
1185 /* -------------------------------------------------------------------- *
1186  * -                         WINDOW RESIZING                          - *
1187  * -------------------------------------------------------------------- */
1188 void
1189 rxvt_term::resize_all_windows (unsigned int newwidth, unsigned int newheight, int ignoreparent)
1190 {
1191   int fix_screen;
1192   int old_width = szHint.width, old_height = szHint.height;
1193   dDisp;
1194
1195   window_calc (newwidth, newheight);
1196   XSetWMNormalHints (disp, parent[0], &szHint);
1197
1198   if (!ignoreparent)
1199     {
1200 #ifdef SMART_RESIZE
1201       /*
1202        * resize by Marius Gedminas <marius.gedminas@uosis.mif.vu.lt>
1203        * reposition window on resize depending on placement on screen
1204        */
1205       int x, y, x1, y1;
1206       int dx, dy;
1207       unsigned int unused_w1, unused_h1, unused_b1, unused_d1;
1208       Window unused_cr;
1209
1210       XTranslateCoordinates (disp, parent[0], display->root,
1211                              0, 0, &x, &y, &unused_cr);
1212       XGetGeometry (disp, parent[0], &unused_cr, &x1, &y1,
1213                     &unused_w1, &unused_h1, &unused_b1, &unused_d1);
1214       /*
1215        * if display->root isn't the parent window, a WM will probably have offset
1216        * our position for handles and decorations.  Counter it
1217        */
1218       if (x1 != x || y1 != y)
1219         {
1220           x -= x1;
1221           y -= y1;
1222         }
1223
1224       x1 = (DisplayWidth (disp, display->screen) - old_width) / 2;
1225       y1 = (DisplayHeight (disp, display->screen) - old_height) / 2;
1226       dx = old_width - szHint.width;
1227       dy = old_height - szHint.height;
1228
1229       /* Check position of the center of the window */
1230       if (x < x1)             /* left half */
1231         dx = 0;
1232       else if (x == x1)       /* exact center */
1233         dx /= 2;
1234       if (y < y1)             /* top half */
1235         dy = 0;
1236       else if (y == y1)       /* exact center */
1237         dy /= 2;
1238
1239       XMoveResizeWindow (disp, parent[0], x + dx, y + dy,
1240                          szHint.width, szHint.height);
1241 #else
1242       XResizeWindow (disp, parent[0], szHint.width, szHint.height);
1243 #endif
1244     }
1245
1246   fix_screen = ncol != prev_ncol || nrow != prev_nrow;
1247
1248   if (fix_screen || newwidth != old_width || newheight != old_height)
1249     {
1250       if (scrollbar_visible ())
1251         {
1252           XMoveResizeWindow (disp, scrollBar.win,
1253                              window_sb_x, 0,
1254                              scrollbar_TotalWidth (), szHint.height);
1255           resize_scrollbar ();
1256         }
1257
1258       if (menubar_visible ())
1259         XMoveResizeWindow (disp, menuBar.win,
1260                            window_vt_x, 0,
1261                            width, menuBar_TotalHeight ());
1262
1263       XMoveResizeWindow (disp, vt,
1264                          window_vt_x, window_vt_y,
1265                          width, height);
1266
1267       scr_clear ();
1268 #ifdef XPM_BACKGROUND
1269       resize_pixmap ();
1270 #endif
1271     }
1272
1273   if (fix_screen || old_height == 0)
1274     {
1275       int curr_screen = -1;
1276       int old_ncol = prev_ncol;
1277
1278       /* scr_reset only works on the primary screen */
1279       if (old_height)      /* this is not the first time through */
1280         {
1281           unsigned int ocol = ncol;
1282           ncol = prev_ncol; // save b/c scr_blank_screen_mem uses this
1283           curr_screen = scr_change_screen (PRIMARY);
1284           ncol = ocol;
1285         }
1286
1287       scr_reset ();
1288
1289       if (curr_screen >= 0) /* this is not the first time through */
1290         {
1291           scr_change_screen (curr_screen);
1292           selection_check (old_ncol != ncol ? 4 : 0);
1293         }
1294     }
1295
1296   old_width = szHint.width;
1297   old_height = szHint.height;
1298
1299 #ifdef XPM_BACKGROUND
1300   if (pixmap)
1301     scr_touch (false);
1302 #endif
1303
1304 #ifdef USE_XIM
1305   IMSetStatusPosition ();
1306 #endif
1307 }
1308
1309 /*
1310  * Set the width/height of the vt window in characters.  Units are pixels.
1311  * good for toggling 80/132 columns
1312  */
1313 void
1314 rxvt_term::set_widthheight (unsigned int newwidth, unsigned int newheight)
1315 {
1316   XWindowAttributes wattr;
1317
1318   if (newwidth == 0 || newheight == 0)
1319     {
1320       XGetWindowAttributes (display->display, display->root, &wattr);
1321
1322       if (newwidth == 0)
1323         newwidth = wattr.width - szHint.base_width;
1324       if (newheight == 0)
1325         newheight = wattr.height - szHint.base_height;
1326     }
1327
1328   if (newwidth != width || newheight != height)
1329     {
1330       newwidth += szHint.base_width;
1331       newheight += szHint.base_height;
1332       resize_all_windows (newwidth, newheight, 0);
1333     }
1334 }
1335
1336 /* -------------------------------------------------------------------- *
1337  * -                      X INPUT METHOD ROUTINES                     - *
1338  * -------------------------------------------------------------------- */
1339 #ifdef USE_XIM
1340
1341 void
1342 rxvt_term::im_set_color (unsigned long &fg, unsigned long &bg)
1343 {
1344   fg = pix_colors[Color_fg];
1345   bg = pix_colors[Color_bg];
1346 }
1347
1348 void
1349 rxvt_term::im_set_size (XRectangle &size)
1350 {
1351   // the int_bwidth terms make no sense to me
1352   size.x      = int_bwidth;
1353   size.y      = int_bwidth;
1354   size.width  = Width2Pixel (ncol) + int_bwidth;
1355   size.height = Height2Pixel (nrow) + int_bwidth;
1356 }
1357
1358 void
1359 rxvt_term::im_set_preedit_area (XRectangle &preedit_rect,
1360                                 XRectangle &status_rect,
1361                                 const XRectangle &needed_rect)
1362 {
1363   preedit_rect.x      = needed_rect.width;
1364   preedit_rect.y      = 0;
1365   preedit_rect.width  = Width2Pixel (ncol) - needed_rect.width + 1;
1366   preedit_rect.height = fheight;
1367
1368   status_rect.x       = 0;
1369   status_rect.y       = 0;
1370   status_rect.width   = needed_rect.width ? needed_rect.width : Width2Pixel (ncol) + 1;
1371   status_rect.height  = fheight;
1372 }
1373
1374 /* Checking whether input method is running. */
1375 bool
1376 rxvt_term::IMisRunning ()
1377 {
1378   char *p;
1379   Atom atom;
1380   Window win;
1381   char server[IMBUFSIZ];
1382
1383   /* get current locale modifier */
1384   if ((p = XSetLocaleModifiers (NULL)) != NULL)
1385     {
1386       strcpy (server, "@server=");
1387       strncat (server, & (p[4]), IMBUFSIZ - 9); /* skip "@im=" */
1388
1389       if ((p = strchr (server + 1, '@')) != NULL)      /* first one only */
1390         *p = '\0';
1391
1392       atom = XInternAtom (display->display, server, False);
1393       win = XGetSelectionOwner (display->display, atom);
1394
1395       if (win != None)
1396         return True;
1397     }
1398
1399   return False;
1400 }
1401
1402 void
1403 rxvt_term::IMSendSpot ()
1404 {
1405   XPoint nspot;
1406   XVaNestedList preedit_attr;
1407
1408   if (!Input_Context
1409       || !focus
1410       || !(input_style & XIMPreeditPosition))
1411     return;
1412
1413   im_set_position (nspot);
1414
1415   if (nspot.x == spot.x && nspot.y == spot.y)
1416     return;
1417
1418   spot = nspot;
1419
1420   preedit_attr = XVaCreateNestedList (0, XNSpotLocation, &spot, NULL);
1421   XSetICValues (Input_Context, XNPreeditAttributes, preedit_attr, NULL);
1422   XFree (preedit_attr);
1423 }
1424
1425 void
1426 rxvt_term::im_destroy ()
1427 {
1428   if (input_method)
1429     {
1430       if (Input_Context && input_method->xim)
1431         XDestroyIC (Input_Context);
1432
1433       display->put_xim (input_method);
1434       input_method = 0;
1435     }
1436
1437   Input_Context = 0;
1438 }
1439
1440 /*
1441  * Try to open a XIM with the current modifiers, then see if we can
1442  * open a suitable preedit type
1443  */
1444 bool
1445 rxvt_term::IM_get_IC (const char *modifiers)
1446 {
1447   int i, j, found;
1448   XIM xim;
1449   XPoint spot;
1450   XRectangle rect, status_rect, needed_rect;
1451   unsigned long fg, bg;
1452   const char *p;
1453   char **s;
1454   XIMStyles *xim_styles;
1455
1456   TEMP_ENV;
1457
1458   if (! ((p = XSetLocaleModifiers (modifiers)) && *p))
1459     return false;
1460
1461   D_MAIN ((stderr, "rxvt_IM_get_IC ()"));
1462   input_method = display->get_xim (locale, modifiers);
1463   if (input_method == NULL)
1464     return false;
1465
1466   xim = input_method->xim;
1467   spot.x = spot.y = -1;
1468
1469   xim_styles = NULL;
1470   if (XGetIMValues (xim, XNQueryInputStyle, &xim_styles, NULL)
1471       || !xim_styles || !xim_styles->count_styles)
1472     {
1473       im_destroy ();
1474       return false;
1475     }
1476
1477   const char *pet[] = { rs[Rs_preeditType], "OverTheSpot,OffTheSpot,Root,None" };
1478
1479   for (int pi = 0; pi < 2; pi++)
1480     {
1481       p = pet[pi];
1482
1483       if (!p)
1484         continue;
1485
1486       s = rxvt_splitcommastring (p);
1487
1488       for (i = found = 0; !found && s[i]; i++)
1489         {
1490           if (!strcmp (s[i], "OverTheSpot"))
1491             input_style = (XIMPreeditPosition | XIMStatusNothing);
1492           else if (!strcmp (s[i], "OffTheSpot"))
1493             input_style = (XIMPreeditArea | XIMStatusArea);
1494           else if (!strcmp (s[i], "Root"))
1495             input_style = (XIMPreeditNothing | XIMStatusNothing);
1496           else if (!strcmp (s[i], "None"))
1497             input_style = (XIMPreeditNone | XIMStatusNone);
1498
1499           for (j = 0; j < xim_styles->count_styles; j++)
1500             if (input_style == xim_styles->supported_styles[j])
1501               {
1502                 rxvt_freecommastring (s);
1503
1504                 found = 1;
1505                 goto foundpet;
1506               }
1507
1508         }
1509
1510       rxvt_freecommastring (s);
1511     }
1512
1513 foundpet:
1514
1515   XFree (xim_styles);
1516
1517   if (!found)
1518     {
1519       im_destroy ();
1520       return false;
1521     }
1522
1523   XFontSet fs = 0;
1524   XVaNestedList preedit_attr = 0, status_attr = 0;
1525
1526   if (input_style & (XIMPreeditPosition | XIMPreeditArea))
1527     {
1528       // fake us a font-set, please
1529       char **missing_charset_list;
1530       int missing_charset_count;
1531       char *def_string;
1532       char pat[512];
1533
1534       sprintf (pat,
1535                "-*-*-*-R-*-*-%d-*-*-*-*-*-*,"
1536                "-*-*-*-R-*-*-%d-*-*-*-*-*-*,"
1537                "-*-*-*-R-*-*-%d-*-*-*-*-*-*,"
1538                "-*-*-*-R-*-*-%d-*-*-*-*-*-*,"
1539                "-*-*-*-R-*-*-%d-*-*-*-*-*-*,"
1540                "*",
1541                fheight,
1542                fheight + 1, fheight - 1,
1543                fheight - 2, fheight + 2);
1544
1545       fs = XCreateFontSet (display->display, rs[Rs_imFont] ? rs[Rs_imFont] : pat,
1546                            &missing_charset_list, &missing_charset_count, &def_string);
1547
1548       if (missing_charset_list)
1549         XFreeStringList (missing_charset_list);
1550
1551       if (!fs)
1552         {
1553           input_style &= ~(XIMPreeditPosition | XIMPreeditArea);
1554           rxvt_warn ("unable to create fontset for input method, try \"-pt Root\". Continuing.\n");
1555         }
1556     }
1557
1558   if (input_style & XIMPreeditPosition)
1559     {
1560       im_set_size (rect);
1561       im_set_position (spot);
1562       im_set_color (fg, bg);
1563
1564       preedit_attr = XVaCreateNestedList (0,
1565                                           XNForeground, fg,
1566                                           XNBackground, bg,
1567                                           XNArea, &rect,
1568                                           XNSpotLocation, &spot,
1569                                           XNFontSet, fs,
1570                                           NULL);
1571     }
1572   else if (input_style & XIMPreeditArea)
1573     {
1574       im_set_color (fg, bg);
1575
1576       /*
1577        * The necessary width of preedit area is unknown
1578        * until create input context.
1579        */
1580       needed_rect.width = 0;
1581       im_set_preedit_area (rect, status_rect, needed_rect);
1582
1583       preedit_attr = XVaCreateNestedList (0,
1584                                           XNForeground, fg,
1585                                           XNBackground, bg,
1586                                           XNArea, &rect,
1587                                           XNFontSet, fs,
1588                                           NULL);
1589       status_attr = XVaCreateNestedList (0,
1590                                          XNForeground, fg,
1591                                          XNBackground, bg,
1592                                          XNArea, &status_rect,
1593                                          XNFontSet, fs,
1594                                          NULL);
1595     }
1596
1597   Input_Context = XCreateIC (xim,
1598                              XNInputStyle, input_style,
1599                              XNClientWindow, vt,
1600                              XNFocusWindow, parent[0],
1601                              preedit_attr ? XNPreeditAttributes : NULL,
1602                              preedit_attr,
1603                              status_attr ? XNStatusAttributes : NULL,
1604                              status_attr, NULL);
1605
1606   if (preedit_attr) XFree (preedit_attr);
1607   if (status_attr) XFree (status_attr);
1608   if (fs) XFreeFontSet (display->display, fs);
1609
1610   if (Input_Context == NULL)
1611     {
1612       rxvt_warn ("failed to create input context, continuing without XIM.\n");
1613       im_destroy ();
1614       return false;
1615     }
1616
1617   if (input_style & XIMPreeditArea)
1618     IMSetStatusPosition ();
1619
1620   D_MAIN ((stderr, "rxvt_IM_get_IC () - successful connection"));
1621   return true;
1622 }
1623
1624 void
1625 rxvt_term::im_cb ()
1626 {
1627   int i;
1628   const char *p;
1629   char **s;
1630   char buf[IMBUFSIZ];
1631
1632   SET_R (this);
1633
1634   im_destroy ();
1635
1636   D_MAIN ((stderr, "rxvt_IMInstantiateCallback ()"));
1637   if (Input_Context)
1638     return;
1639
1640 #if defined(HAVE_XSETLOCALE) || defined(HAVE_SETLOCALE)
1641   if (rs[Rs_imLocale])
1642     SET_LOCALE (rs[Rs_imLocale]);
1643 #endif
1644
1645   p = rs[Rs_inputMethod];
1646   if (p && *p)
1647     {
1648       bool found = false;
1649
1650       s = rxvt_splitcommastring (p);
1651
1652       for (i = 0; s[i]; i++)
1653         {
1654           if (*s[i])
1655             {
1656               strcpy (buf, "@im=");
1657               strncat (buf, s[i], IMBUFSIZ - 5);
1658               if (IM_get_IC (buf))
1659                 {
1660                   found = true;
1661                   break;
1662                 }
1663             }
1664         }
1665
1666       rxvt_freecommastring (s);
1667
1668       if (found)
1669         goto done;
1670     }
1671
1672   /* try with XMODIFIERS env. var. */
1673   if (IM_get_IC (""))
1674     goto done;
1675
1676   /* try with no modifiers base IF the user didn't specify an IM */
1677   if (IM_get_IC ("@im=none"))
1678     goto done;
1679
1680 done:
1681 #if defined(HAVE_XSETLOCALE) || defined(HAVE_SETLOCALE)
1682   if (rs[Rs_imLocale])
1683     SET_LOCALE (locale);
1684 #endif
1685 }
1686
1687 void
1688 rxvt_term::IMSetStatusPosition ()
1689 {
1690   XRectangle preedit_rect, status_rect, *needed_rect;
1691   XVaNestedList preedit_attr, status_attr;
1692
1693   if (!Input_Context
1694       || !focus
1695       || !(input_style & XIMPreeditArea)
1696       || !IMisRunning ())
1697     return;
1698
1699   /* Getting the necessary width of preedit area */
1700   status_attr = XVaCreateNestedList (0, XNAreaNeeded, &needed_rect, NULL);
1701   XGetICValues (Input_Context, XNStatusAttributes, status_attr, NULL);
1702   XFree (status_attr);
1703
1704   im_set_preedit_area (preedit_rect, status_rect, *needed_rect);
1705   XFree (needed_rect);
1706
1707   preedit_attr = XVaCreateNestedList (0, XNArea, &preedit_rect, NULL);
1708   status_attr = XVaCreateNestedList (0, XNArea, &status_rect, NULL);
1709
1710   XSetICValues (Input_Context,
1711                 XNPreeditAttributes, preedit_attr,
1712                 XNStatusAttributes, status_attr, NULL);
1713
1714   XFree (preedit_attr);
1715   XFree (status_attr);
1716 }
1717 #endif                          /* USE_XIM */
1718
1719 /*----------------------------------------------------------------------*/
1720 rxvt_t          rxvt_current_term;
1721
1722 /*----------------------- end-of-file (C source) -----------------------*/