5ad9cd22f93c37a3b7d6987e50ab3f4bf62b8465
[dana/urxvt.git] / src / init.C
1 /*----------------------------------------------------------------------*
2  * File:        init.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) 1996      Chuck Blake <cblake@BBN.COM>
11  * Copyright (c) 1997      mj olesen <olesen@me.queensu.ca>
12  * Copyright (c) 1997,1998 Oezguer Kesim <kesim@math.fu-berlin.de>
13  * Copyright (c) 1998-2001 Geoff Wing <gcw@pobox.com>
14  *                              - extensive modifications
15  * Copyright (c) 2003-2008 Marc Lehmann <pcg@goof.com>
16  *
17  * This program is free software; you can redistribute it and/or modify
18  * it under the terms of the GNU General Public License as published by
19  * the Free Software Foundation; either version 2 of the License, or
20  * (at your option) any later version.
21  *
22  * This program is distributed in the hope that it will be useful,
23  * but WITHOUT ANY WARRANTY; without even the implied warranty of
24  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
25  * GNU General Public License for more details.
26  *
27  * You should have received a copy of the GNU General Public License
28  * along with this program; if not, write to the Free Software
29  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
30  *---------------------------------------------------------------------*/
31 /*
32  * Initialisation routines.
33  */
34
35 #include "../config.h"          /* NECESSARY */
36 #include "rxvt.h"               /* NECESSARY */
37 #include "rxvtutil.h"
38 #include "init.h"
39 #include "keyboard.h"
40
41 #include <limits>
42
43 #include <csignal>
44
45 #include <fcntl.h>
46
47 #ifdef HAVE_XSETLOCALE
48 # define X_LOCALE
49 # include <X11/Xlocale.h>
50 #else
51 # ifdef HAVE_SETLOCALE
52 #  include <clocale>
53 # endif
54 #endif
55
56 #ifdef HAVE_NL_LANGINFO
57 # include <langinfo.h>
58 #endif
59
60 #ifdef DISPLAY_IS_IP
61 /* On Solaris link with -lsocket and -lnsl */
62 #include <sys/types.h>
63 #include <sys/socket.h>
64
65 /* these next two are probably only on Sun (not Solaris) */
66 #ifdef HAVE_SYS_SOCKIO_H
67 #include <sys/sockio.h>
68 #endif
69 #ifdef HAVE_SYS_BYTEORDER_H
70 #include <sys/byteorder.h>
71 #endif
72
73 #include <netinet/in.h>
74 #include <arpa/inet.h>
75 #include <net/if.h>
76 #include <net/if_arp.h>
77
78 static char *
79 rxvt_network_display (const char *display)
80 {
81   char            buffer[1024], *rval = NULL;
82   struct ifconf   ifc;
83   struct ifreq   *ifr;
84   int             i, skfd;
85
86   if (display[0] != ':' && strncmp (display, "unix:", 5))
87     return (char *) display;            /* nothing to do */
88
89   ifc.ifc_len = sizeof (buffer);        /* Get names of all ifaces */
90   ifc.ifc_buf = buffer;
91
92   if ((skfd = socket (AF_INET, SOCK_DGRAM, 0)) < 0)
93     {
94       perror ("socket");
95       return NULL;
96     }
97
98   if (ioctl (skfd, SIOCGIFCONF, &ifc) < 0)
99     {
100       perror ("SIOCGIFCONF");
101       close (skfd);
102       return NULL;
103     }
104
105   for (i = 0, ifr = ifc.ifc_req;
106        i < (ifc.ifc_len / sizeof (struct ifreq));
107        i++, ifr++)
108     {
109       struct ifreq ifr2;
110
111       strcpy (ifr2.ifr_name, ifr->ifr_name);
112
113       if (ioctl (skfd, SIOCGIFADDR, &ifr2) >= 0)
114         {
115           unsigned long addr;
116           struct sockaddr_in *p_addr;
117
118           p_addr = (struct sockaddr_in *) &ifr2.ifr_addr;
119           addr = htonl ((unsigned long)p_addr->sin_addr.s_addr);
120
121           /*
122            * not "0.0.0.0" or "127.0.0.1" - so format the address
123            */
124           if (addr && addr != 0x7F000001)
125             {
126               char *colon = strchr (display, ':');
127
128               if (colon == NULL)
129                 colon = ":0.0";
130
131               rval = rxvt_malloc (strlen (colon) + 16);
132               sprintf (rval, "%d.%d.%d.%d%s",
133                       (int) ((addr >> 030) & 0xFF),
134                       (int) ((addr >> 020) & 0xFF),
135                       (int) ((addr >> 010) & 0xFF),
136                       (int) (addr & 0xFF), colon);
137               break;
138             }
139         }
140     }
141
142   close (skfd);
143
144   return rval;
145 }
146 #endif
147
148 const char *const def_colorName[] =
149   {
150     COLOR_FOREGROUND,
151     COLOR_BACKGROUND,
152     /* low-intensity colors */
153     "rgb:00/00/00",             // 0: black             (Black)
154     "rgb:cd/00/00",             // 1: red               (Red3)
155     "rgb:00/cd/00",             // 2: green             (Green3)
156     "rgb:cd/cd/00",             // 3: yellow            (Yellow3)
157     "rgb:00/00/cd",             // 4: blue              (Blue3)
158     "rgb:cd/00/cd",             // 5: magenta           (Magenta3)
159     "rgb:00/cd/cd",             // 6: cyan              (Cyan3)
160 # ifdef XTERM_COLORS
161     "rgb:e5/e5/e5",             // 7: white             (Grey90)
162 # else
163     "rgb:fa/eb/d7",             // 7: white             (AntiqueWhite)
164 # endif
165     /* high-intensity colors */
166 # ifdef XTERM_COLORS
167     "rgb:4d/4d/4d",             // 8: bright black      (Grey30)
168 # else
169     "rgb:40/40/40",             // 8: bright black      (Grey25)
170 # endif
171     "rgb:ff/00/00",             // 1/9: bright red      (Reed)
172     "rgb:00/ff/00",             // 2/10: bright green   (Green)
173     "rgb:ff/ff/00",             // 3/11: bright yellow  (Yellow)
174     "rgb:00/00/ff",             // 4/12: bright blue    (Blue)
175     "rgb:ff/00/ff",             // 5/13: bright magenta (Magenta)
176     "rgb:00/ff/ff",             // 6/14: bright cyan    (Cyan)
177     "rgb:ff/ff/ff",             // 7/15: bright white   (White)
178
179     // 88 xterm colours
180     "rgb:00/00/00",
181     "rgb:00/00/8b",
182     "rgb:00/00/cd",
183     "rgb:00/00/ff",
184     "rgb:00/8b/00",
185     "rgb:00/8b/8b",
186     "rgb:00/8b/cd",
187     "rgb:00/8b/ff",
188     "rgb:00/cd/00",
189     "rgb:00/cd/8b",
190     "rgb:00/cd/cd",
191     "rgb:00/cd/ff",
192     "rgb:00/ff/00",
193     "rgb:00/ff/8b",
194     "rgb:00/ff/cd",
195     "rgb:00/ff/ff",
196     "rgb:8b/00/00",
197     "rgb:8b/00/8b",
198     "rgb:8b/00/cd",
199     "rgb:8b/00/ff",
200     "rgb:8b/8b/00",
201     "rgb:8b/8b/8b",
202     "rgb:8b/8b/cd",
203     "rgb:8b/8b/ff",
204     "rgb:8b/cd/00",
205     "rgb:8b/cd/8b",
206     "rgb:8b/cd/cd",
207     "rgb:8b/cd/ff",
208     "rgb:8b/ff/00",
209     "rgb:8b/ff/8b",
210     "rgb:8b/ff/cd",
211     "rgb:8b/ff/ff",
212     "rgb:cd/00/00",
213     "rgb:cd/00/8b",
214     "rgb:cd/00/cd",
215     "rgb:cd/00/ff",
216     "rgb:cd/8b/00",
217     "rgb:cd/8b/8b",
218     "rgb:cd/8b/cd",
219     "rgb:cd/8b/ff",
220     "rgb:cd/cd/00",
221     "rgb:cd/cd/8b",
222     "rgb:cd/cd/cd",
223     "rgb:cd/cd/ff",
224     "rgb:cd/ff/00",
225     "rgb:cd/ff/8b",
226     "rgb:cd/ff/cd",
227     "rgb:cd/ff/ff",
228     "rgb:ff/00/00",
229     "rgb:ff/00/8b",
230     "rgb:ff/00/cd",
231     "rgb:ff/00/ff",
232     "rgb:ff/8b/00",
233     "rgb:ff/8b/8b",
234     "rgb:ff/8b/cd",
235     "rgb:ff/8b/ff",
236     "rgb:ff/cd/00",
237     "rgb:ff/cd/8b",
238     "rgb:ff/cd/cd",
239     "rgb:ff/cd/ff",
240     "rgb:ff/ff/00",
241     "rgb:ff/ff/8b",
242     "rgb:ff/ff/cd",
243     "rgb:ff/ff/ff",
244     "rgb:2e/2e/2e",
245     "rgb:5c/5c/5c",
246     "rgb:73/73/73",
247     "rgb:8b/8b/8b",
248     "rgb:a2/a2/a2",
249     "rgb:b9/b9/b9",
250     "rgb:d0/d0/d0",
251     "rgb:e7/e7/e7",
252
253 #ifndef NO_CURSORCOLOR
254     COLOR_CURSOR_BACKGROUND,
255     COLOR_CURSOR_FOREGROUND,
256 #endif /* ! NO_CURSORCOLOR */
257     NULL,                       /* Color_pointer_fg               */
258     NULL,                       /* Color_pointer_bg               */
259     NULL,                       /* Color_border                   */
260 #ifndef NO_BOLD_UNDERLINE_REVERSE
261     NULL,                       /* Color_BD                       */
262     NULL,                       /* Color_IT                       */
263     NULL,                       /* Color_UL                       */
264     NULL,                       /* Color_RV                       */
265 #endif /* ! NO_BOLD_UNDERLINE_REVERSE */
266 #if ENABLE_FRILLS
267     NULL,                       // Color_underline
268 #endif
269 #ifdef OPTION_HC
270     NULL,
271 #endif
272     COLOR_SCROLLBAR,
273 #ifdef RXVT_SCROLLBAR
274     COLOR_SCROLLTROUGH,
275 #endif
276 #if ENABLE_TRANSPARENCY
277     NULL,
278 #endif
279 #if OFF_FOCUS_FADING
280     "rgb:00/00/00",
281 #endif
282   };
283
284 void
285 rxvt_term::init_vars ()
286 {
287   pix_colors = pix_colors_focused;
288
289   MEvent.time = CurrentTime;
290   MEvent.button = AnyButton;
291   want_refresh = 1;
292   priv_modes = SavedModes = PrivMode_Default;
293   ncol = 80;
294   nrow = 24;
295   int_bwidth = INTERNALBORDERWIDTH;
296   ext_bwidth = EXTERNALBORDERWIDTH;
297   lineSpace = LINESPACE;
298   letterSpace = LETTERSPACE;
299   saveLines = SAVELINES;
300
301   refresh_type = SLOW_REFRESH;
302
303   oldcursor.row = oldcursor.col = -1;
304
305   set_option (Opt_scrollBar);
306   set_option (Opt_scrollTtyOutput);
307   set_option (Opt_jumpScroll);
308   set_option (Opt_skipScroll);
309   set_option (Opt_secondaryScreen);
310   set_option (Opt_secondaryScroll);
311   set_option (Opt_pastableTabs);
312   set_option (Opt_intensityStyles);
313   set_option (Opt_iso14755);
314   set_option (Opt_iso14755_52);
315   set_option (Opt_buffered);
316 }
317
318 static void
319 init_secondary ()
320 {
321   int i;
322
323   if ((i = open ("/dev/null", O_RDONLY)) < 0)
324     {
325       dup2 (STDERR_FILENO, STDIN_FILENO);
326     }
327   else if (i != STDIN_FILENO)
328     {
329       dup2 (i, STDIN_FILENO);
330       close (i);
331     }
332
333   dup2 (STDERR_FILENO, STDOUT_FILENO);
334 }
335
336 /*----------------------------------------------------------------------*/
337 const char **
338 rxvt_term::init_resources (int argc, const char *const *argv)
339 {
340   int i, r_argc;
341   const char **cmd_argv, **r_argv;
342
343   /*
344    * Look for -e option. Find => split and make cmd_argv[] of command args
345    */
346   for (r_argc = 0; r_argc < argc; r_argc++)
347     if (!strcmp (argv[r_argc], "-e"))
348       break;
349
350   if (r_argc == argc)
351     cmd_argv = NULL;
352   else if (!argv[r_argc + 1])
353     rxvt_fatal ("option '-e' requires an argument, aborting.\n");
354   else
355     {
356       cmd_argv = (const char **)rxvt_malloc (sizeof (char *) * (argc - r_argc));
357
358       for (i = 0; i < argc - r_argc - 1; i++)
359         cmd_argv[i] = (const char *)argv[i + r_argc + 1];
360
361       cmd_argv[i] = NULL;
362     }
363
364   r_argv = (const char **)rxvt_malloc (sizeof (char *) * (r_argc + 1));
365
366   for (i = 0; i < r_argc; i++)
367     r_argv[i] = (const char *)argv[i];
368
369   r_argv[i] = NULL;
370
371   rs[Rs_name] = rxvt_basename (argv[0]);
372
373   /*
374    * Open display, get options/resources and create the window
375    */
376
377   if ((rs[Rs_display_name] = getenv ("DISPLAY")) == NULL)
378     rs[Rs_display_name] = ":0";
379
380   get_options (r_argc, r_argv);
381
382   if (!(display = displays.get (rs[Rs_display_name])))
383     {
384       free (r_argv);
385       rxvt_fatal ("can't open display %s, aborting.\n", rs[Rs_display_name]);
386     }
387
388   // using a local pointer decreases code size a lot
389   xa = display->xa;
390
391   set (display);
392   extract_resources ();
393
394 #if XFT
395   if (rs[Rs_depth])
396     select_visual (strtol (rs[Rs_depth], 0, 0));
397 #endif
398
399   free (r_argv);
400
401   for (int i = NUM_RESOURCES; i--; )
402     if (rs [i] == resval_undef)
403       rs [i] = 0;
404
405 #ifdef HAVE_AFTERIMAGE
406   set_application_name ((char *)rs[Rs_name]);
407   set_output_threshold (OUTPUT_LEVEL_WARNING);
408 #endif
409
410 #if ENABLE_PERL
411   if (!rs[Rs_perl_ext_1])
412     rs[Rs_perl_ext_1] = "default";
413
414   if ((rs[Rs_perl_ext_1] && *rs[Rs_perl_ext_1])
415       || (rs[Rs_perl_ext_2] && *rs[Rs_perl_ext_2])
416       || (rs[Rs_perl_eval] && *rs[Rs_perl_eval]))
417     {
418       rxvt_perl.init (this);
419       HOOK_INVOKE ((this, HOOK_INIT, DT_END));
420     }
421 #endif
422
423   /*
424    * set any defaults not already set
425    */
426   if (cmd_argv && cmd_argv[0])
427     {
428       if (!rs[Rs_title])
429         rs[Rs_title] = rxvt_basename (cmd_argv[0]);
430
431       if (!rs[Rs_iconName])
432         rs[Rs_iconName] = rs[Rs_title];
433     }
434   else
435     {
436       if (!rs[Rs_title])
437         rs[Rs_title] = rs[Rs_name];
438
439       if (!rs[Rs_iconName])
440         rs[Rs_iconName] = rs[Rs_name];
441     }
442
443   if (rs[Rs_saveLines] && (i = atoi (rs[Rs_saveLines])) >= 0)
444     saveLines = min (i, MAX_SAVELINES);
445
446 #if ENABLE_FRILLS
447   if (rs[Rs_int_bwidth] && (i = atoi (rs[Rs_int_bwidth])) >= 0)
448     int_bwidth = min (i, std::numeric_limits<int16_t>::max ());
449
450   if (rs[Rs_ext_bwidth] && (i = atoi (rs[Rs_ext_bwidth])) >= 0)
451     ext_bwidth = min (i, std::numeric_limits<int16_t>::max ());
452
453   if (rs[Rs_lineSpace] && (i = atoi (rs[Rs_lineSpace])) >= 0)
454     lineSpace = min (i, std::numeric_limits<int16_t>::max ());
455
456   if (rs[Rs_letterSpace])
457     letterSpace = atoi (rs[Rs_letterSpace]);
458 #endif
459
460 #ifdef POINTER_BLANK
461   if (rs[Rs_pointerBlankDelay] && (i = atoi (rs[Rs_pointerBlankDelay])) >= 0)
462     pointerBlankDelay = i;
463   else
464     pointerBlankDelay = 2;
465 #endif
466
467   /* no point having a scrollbar without having any scrollback! */
468   if (!saveLines)
469     set_option (Opt_scrollBar, 0);
470
471   if (!rs[Rs_cutchars])
472     rs[Rs_cutchars] = CUTCHARS;
473
474 #ifndef NO_BACKSPACE_KEY
475   if (!rs[Rs_backspace_key])
476 # ifdef DEFAULT_BACKSPACE
477     rs[Rs_backspace_key] = DEFAULT_BACKSPACE;
478 # else
479     rs[Rs_backspace_key] = "DEC";       /* can toggle between \010 or \177 */
480 # endif
481 #endif
482
483 #ifndef NO_DELETE_KEY
484   if (!rs[Rs_delete_key])
485 # ifdef DEFAULT_DELETE
486     rs[Rs_delete_key] = DEFAULT_DELETE;
487 # else
488     rs[Rs_delete_key] = "\033[3~";
489 # endif
490 #endif
491
492     scrollBar.setup (this);
493
494 #ifdef XTERM_REVERSE_VIDEO
495   /* this is how xterm implements reverseVideo */
496   if (option (Opt_reverseVideo))
497     {
498       if (!rs[Rs_color + Color_fg])
499         rs[Rs_color + Color_fg] = def_colorName[Color_bg];
500
501       if (!rs[Rs_color + Color_bg])
502         rs[Rs_color + Color_bg] = def_colorName[Color_fg];
503     }
504 #endif
505
506   for (i = 0; i < NRS_COLORS; i++)
507     if (!rs[Rs_color + i])
508       rs[Rs_color + i] = def_colorName[i];
509
510 #ifndef XTERM_REVERSE_VIDEO
511   /* this is how we implement reverseVideo */
512   if (option (Opt_reverseVideo))
513     ::swap (rs[Rs_color + Color_fg], rs[Rs_color + Color_bg]);
514 #endif
515
516   /* convenient aliases for setting fg/bg to colors */
517   color_aliases (Color_fg);
518   color_aliases (Color_bg);
519 #ifndef NO_CURSORCOLOR
520   color_aliases (Color_cursor);
521   color_aliases (Color_cursor2);
522 #endif /* NO_CURSORCOLOR */
523   color_aliases (Color_pointer_fg);
524   color_aliases (Color_pointer_bg);
525   color_aliases (Color_border);
526 #ifndef NO_BOLD_UNDERLINE_REVERSE
527   color_aliases (Color_BD);
528   color_aliases (Color_UL);
529   color_aliases (Color_RV);
530 #endif /* ! NO_BOLD_UNDERLINE_REVERSE */
531
532   if (!rs[Rs_color + Color_border])
533     rs[Rs_color + Color_border] = rs[Rs_color + Color_bg];
534
535   return cmd_argv;
536 }
537
538 /*----------------------------------------------------------------------*/
539 void
540 rxvt_term::init (int argc, const char *const *argv, stringvec *envv)
541 {
542   this->envv = envv;
543
544   SET_R (this);
545   set_locale ("");
546   set_environ (envv); // a few things in X do not call setlocale :(
547
548   init_vars ();
549
550   init_secondary ();
551
552   const char **cmd_argv = init_resources (argc, argv);
553
554 #ifdef KEYSYM_RESOURCE
555   keyboard->register_done ();
556 #endif
557
558   if (const char *path = rs[Rs_chdir])
559     if (*path) // ignored if empty
560       {
561         if (*path != '/')
562           rxvt_fatal ("specified shell working directory must start with a slash, aborting.\n");
563
564         if (chdir (path))
565           rxvt_fatal ("unable to change into specified shell working directory, aborting.\n");
566       }
567
568   if (option (Opt_scrollBar))
569     scrollBar.state = STATE_IDLE;    /* set existence for size calculations */
570
571   pty = ptytty::create ();
572
573   create_windows (argc, argv);
574
575   init_xlocale ();
576
577   scr_poweron (); // initialize screen
578
579 #if 0
580   XSynchronize (dpy, True);
581 #endif
582
583   if (option (Opt_scrollBar))
584     scrollBar.resize ();      /* create and map scrollbar */
585 #ifdef HAVE_BG_PIXMAP
586   {
587     bgPixmap.set_target (this);
588     bgPixmap.invalidate ();
589
590 #ifdef ENABLE_TRANSPARENCY
591     if (option (Opt_transparent))
592       {
593         bgPixmap.set_transparent ();
594
595 #ifdef HAVE_AFTERIMAGE
596         if (rs [Rs_blurradius])
597           bgPixmap.set_blur_radius (rs [Rs_blurradius]);
598 #endif
599         if (ISSET_PIXCOLOR (Color_tint))
600           bgPixmap.set_tint (pix_colors_focused [Color_tint]);
601
602         if (rs [Rs_shade])
603           bgPixmap.set_shade (rs [Rs_shade]);
604
605         bgPixmap.set_root_pixmap ();
606         XSelectInput (dpy, display->root, PropertyChangeMask);
607         rootwin_ev.start (display, display->root);
608       }
609 #endif
610
611 #ifdef BG_IMAGE_FROM_FILE
612     if (rs[Rs_backgroundPixmap])
613       {
614         const char *p = rs[Rs_backgroundPixmap];
615
616         if ((p = strchr (p, ';')) != 0)
617           {
618             p++;
619             bgPixmap.set_geometry (p);
620           }
621         else
622           bgPixmap.set_defaultGeometry ();
623
624         if (bgPixmap.set_file (rs[Rs_backgroundPixmap]))
625           if (!bgPixmap.window_position_sensitive ())
626             update_background ();
627       }
628 #endif
629   }
630 #endif
631
632 #if ENABLE_PERL
633   rootwin_ev.start (display, display->root);
634 #endif
635
636   set_colorfgbg ();
637
638   init_command (cmd_argv);
639
640   free (cmd_argv);
641
642   if (pty->pty >= 0)
643     pty_ev.start (pty->pty, ev::READ);
644
645   HOOK_INVOKE ((this, HOOK_START, DT_END));
646
647 #if ENABLE_XEMBED
648   if (rs[Rs_embed])
649     {
650       long info[2] = { 0, XEMBED_MAPPED };
651
652       XChangeProperty (dpy, parent[0], xa[XA_XEMBED_INFO], xa[XA_XEMBED_INFO],
653                        32, PropModeReplace, (unsigned char *)&info, 2);
654     }
655 #endif
656
657   XMapWindow (dpy, vt);
658   XMapWindow (dpy, parent[0]);
659
660   refresh_check ();
661 }
662
663 /*----------------------------------------------------------------------*/
664 void
665 rxvt_term::init_env ()
666 {
667   int i;
668   char *val;
669
670 #ifdef DISPLAY_IS_IP
671   /* Fixup display_name for export over pty to any interested terminal
672    * clients via "ESC[7n" (e.g. shells).  Note we use the pure IP number
673    * (for the first non-loopback interface) that we get from
674    * rxvt_network_display ().  This is more "name-resolution-portable", if you
675    * will, and probably allows for faster x-client startup if your name
676    * server is beyond a slow link or overloaded at client startup.  Of
677    * course that only helps the shell's child processes, not us.
678    *
679    * Giving out the display_name also affords a potential security hole
680    */
681   val = rxvt_network_display (rs[Rs_display_name]);
682   rs[Rs_display_name] = (const char *)val;
683
684   if (val == NULL)
685 #endif /* DISPLAY_IS_IP */
686     val = XDisplayString (dpy);
687
688   if (rs[Rs_display_name] == NULL)
689     rs[Rs_display_name] = val;   /* use broken `:0' value */
690
691   i = strlen (val);
692   env_display = (char *)rxvt_malloc (i + 9);
693
694   sprintf (env_display, "DISPLAY=%s", val);
695
696   sprintf (env_windowid, "WINDOWID=%lu", (unsigned long)parent[0]);
697
698   /* add entries to the environment:
699    * @ DISPLAY:   in case we started with -display
700    * @ WINDOWID:  X window id number of the window
701    * @ COLORTERM: terminal sub-name and also indicates its color
702    * @ TERM:      terminal name
703    * @ TERMINFO:  path to terminfo directory
704    * @ COLORFGBG: fg;bg color codes
705    */
706   putenv (env_display);
707   putenv (env_windowid);
708
709   if (env_colorfgbg)
710     putenv (env_colorfgbg);
711
712 #ifdef RXVT_TERMINFO
713   putenv ("TERMINFO=" RXVT_TERMINFO);
714 #endif
715
716   if (depth <= 2)
717     putenv ("COLORTERM=" COLORTERMENV "-mono");
718   else
719     putenv ("COLORTERM=" COLORTERMENVFULL);
720
721   if (rs[Rs_term_name] != NULL)
722     {
723       env_term = (char *)rxvt_malloc (strlen (rs[Rs_term_name]) + 6);
724       sprintf (env_term, "TERM=%s", rs[Rs_term_name]);
725       putenv (env_term);
726     }
727   else
728     putenv ("TERM=" TERMENV);
729
730 #ifdef HAVE_UNSETENV
731   /* avoid passing old settings and confusing term size */
732   unsetenv ("LINES");
733   unsetenv ("COLUMNS");
734   unsetenv ("TERMCAP");        /* terminfo should be okay */
735 #endif /* HAVE_UNSETENV */
736 }
737
738 /*----------------------------------------------------------------------*/
739 /*
740  * This is more or less stolen straight from XFree86 xterm.
741  * This should support all European type languages.
742  */
743 void
744 rxvt_term::set_locale (const char *locale)
745 {
746   set_environ (envv);
747
748 #if HAVE_XSETLOCALE || HAVE_SETLOCALE
749   free (this->locale);
750   this->locale = setlocale (LC_CTYPE, locale);
751
752   if (!this->locale)
753     {
754       if (*locale)
755         {
756           rxvt_warn ("unable to set locale \"%s\", using C locale instead.\n", locale);
757           setlocale (LC_CTYPE, "C");
758         }
759       else
760         rxvt_warn ("default locale unavailable, check LC_* and LANG variables. Continuing.\n");
761
762       this->locale = "C";
763     }
764
765
766   this->locale = strdup (this->locale);
767   SET_LOCALE (this->locale);
768   mbstate.reset ();
769 #endif
770
771 #if HAVE_NL_LANGINFO
772   char *codeset = strdup (nl_langinfo (CODESET));
773   // /^UTF.?8/i
774   enc_utf8 = (codeset[0] == 'U' || codeset[0] == 'u')
775           && (codeset[1] == 'T' || codeset[1] == 't')
776           && (codeset[2] == 'F' || codeset[2] == 'f')
777           && (codeset[3] == '8' || codeset[4] == '8');
778   free (codeset);
779 #else
780   enc_utf8 = 0;
781 #endif
782 }
783
784 void
785 rxvt_term::init_xlocale ()
786 {
787   set_environ (envv);
788
789 #ifdef USE_XIM
790   if (!locale)
791     rxvt_warn ("setting locale failed, working without locale support.\n");
792   else
793     {
794       set_string_property (xa[XA_WM_LOCALE_NAME], locale);
795
796       if (!XSupportsLocale ())
797         {
798           rxvt_warn ("the locale is not supported by Xlib, working without locale support.\n");
799           return;
800         }
801
802       im_ev.start (display);
803
804       /* see if we can connect already */
805       im_cb ();
806     }
807 #endif
808 }
809
810 /*----------------------------------------------------------------------*/
811 void
812 rxvt_term::init_command (const char *const *argv)
813 {
814   /*
815    * Initialize the command connection.
816    * This should be called after the X server connection is established.
817    */
818
819 #ifdef META8_OPTION
820   meta_char = option (Opt_meta8) ? 0x80 : C0_ESC;
821 #endif
822
823   get_ourmods ();
824
825   if (!option (Opt_scrollTtyOutput))
826     priv_modes |= PrivMode_TtyOutputInh;
827   if (option (Opt_scrollTtyKeypress))
828     priv_modes |= PrivMode_Keypress;
829   if (!option (Opt_jumpScroll))
830     priv_modes |= PrivMode_smoothScroll;
831
832 #ifndef NO_BACKSPACE_KEY
833   if (strcmp (rs[Rs_backspace_key], "DEC") == 0)
834     priv_modes |= PrivMode_HaveBackSpace;
835 #endif
836
837   /* add value for scrollBar */
838   if (scrollBar.state)
839     {
840       priv_modes |= PrivMode_scrollBar;
841       SavedModes |= PrivMode_scrollBar;
842     }
843
844   run_command (argv);
845 }
846
847 /*----------------------------------------------------------------------*/
848 void
849 rxvt_term::get_colours ()
850 {
851   int i;
852
853 #ifdef OFF_FOCUS_FADING
854   pix_colors = pix_colors_focused;
855 #endif
856
857   for (i = 0; i < (depth <= 2 ? 2 : NRS_COLORS); i++)
858     {
859       const char *name = rs[Rs_color + i];
860
861       if (!name)
862         continue;
863
864       rxvt_color xcol;
865
866       if (!set_color (xcol, name))
867         {
868 #ifndef XTERM_REVERSE_VIDEO
869           if (i < 2 && option (Opt_reverseVideo))
870             name = def_colorName [1 - i];
871           else
872 #endif
873             name = def_colorName [i];
874
875           if (!name)
876             continue;
877
878           if (!set_color (xcol, name))
879             {
880               switch (i)
881                 {
882                   case Color_fg:
883                   case Color_bg:
884                     rxvt_warn ("unable to get foreground/background colour, continuing.\n");
885                     name = "";
886                     break;
887 #ifndef NO_CURSORCOLOR
888                   case Color_cursor2:
889 #endif
890                   case Color_pointer_fg:
891                     name = rs[Rs_color + Color_fg];
892                     xcol.set (this, name);
893                     break;
894                   default:
895                     name = rs[Rs_color + Color_bg];
896                     xcol.set (this, name);
897                     break;
898                 }
899             }
900         }
901
902       pix_colors[i] = xcol;
903       rs[Rs_color + i] = name;
904     }
905
906   if (depth <= 2)
907     {
908       if (!rs[Rs_color + Color_pointer_fg]) alias_color (Color_pointer_fg, Color_fg);
909       if (!rs[Rs_color + Color_pointer_bg]) alias_color (Color_pointer_bg, Color_bg);
910       if (!rs[Rs_color + Color_border]    ) alias_color (Color_border,     Color_fg);
911     }
912
913   /*
914    * get scrollBar shadow colors
915    *
916    * The calculations of topShadow/bottomShadow values are adapted
917    * from the fvwm window manager.
918    */
919 #ifdef RXVT_SCROLLBAR
920   if (depth <= 2)
921     {
922       /* Monochrome */
923       alias_color (Color_scroll,       Color_fg);
924       alias_color (Color_topShadow,    Color_bg);
925       alias_color (Color_bottomShadow, Color_bg);
926     }
927   else
928     {
929       pix_colors [Color_scroll].fade (this, 50, pix_colors [Color_bottomShadow]);
930
931       rgba cscroll;
932       pix_colors [Color_scroll].get (cscroll);
933
934       /* topShadowColor */
935       if (!pix_colors[Color_topShadow].set (this,
936                        rgba (
937                          min ((int)rgba::MAX_CC, max (cscroll.r / 5, cscroll.r) * 7 / 5),
938                          min ((int)rgba::MAX_CC, max (cscroll.g / 5, cscroll.g) * 7 / 5),
939                          min ((int)rgba::MAX_CC, max (cscroll.b / 5, cscroll.b) * 7 / 5),
940                          cscroll.a)
941                        ))
942         alias_color (Color_topShadow, Color_White);
943     }
944 #endif
945
946 #ifdef OFF_FOCUS_FADING
947   for (i = 0; i < (depth <= 2 ? 2 : NRS_COLORS); i++)
948     update_fade_color (i);
949 #endif
950 }
951
952 /*----------------------------------------------------------------------*/
953 /* color aliases, fg/bg bright-bold */
954 void
955 rxvt_term::color_aliases (int idx)
956 {
957   if (rs[Rs_color + idx] && isdigit (* (rs[Rs_color + idx])))
958     {
959       int i = atoi (rs[Rs_color + idx]);
960
961       if (i >= 8 && i <= 15)
962         /* bright colors */
963         rs[Rs_color + idx] = rs[Rs_color + minBrightCOLOR + i - 8];
964       else if (i >= 0 && i <= 7)
965         /* normal colors */
966         rs[Rs_color + idx] = rs[Rs_color + minCOLOR + i];
967     }
968 }
969
970 /*----------------------------------------------------------------------*/
971 /*
972  * Probe the modifier keymap to get the Meta (Alt) and Num_Lock settings
973  * Use resource ``modifier'' to override the Meta modifier
974  */
975 void
976 rxvt_term::get_ourmods ()
977 {
978   int i, j, k;
979   int requestedmeta, realmeta, realalt;
980   const char *cm, *rsmod;
981   XModifierKeymap *map;
982   KeyCode *kc;
983   const unsigned int modmasks[] =
984     {
985       Mod1Mask, Mod2Mask, Mod3Mask, Mod4Mask, Mod5Mask
986     };
987
988   requestedmeta = realmeta = realalt = 0;
989   rsmod = rs[Rs_modifier];
990
991   if (rsmod
992       && strcasecmp (rsmod, "mod1") >= 0 && strcasecmp (rsmod, "mod5") <= 0)
993     requestedmeta = rsmod[3] - '0';
994
995   map = XGetModifierMapping (dpy);
996   kc = map->modifiermap;
997
998   for (i = 1; i < 6; i++)
999     {
1000       k = (i + 2) * map->max_keypermod;       /* skip shift/lock/control */
1001
1002       for (j = map->max_keypermod; j--; k++)
1003         {
1004           if (kc[k] == 0)
1005             break;
1006
1007           switch (XKeycodeToKeysym (dpy, kc[k], 0))
1008             {
1009               case XK_Num_Lock:
1010                 ModNumLockMask = modmasks[i - 1];
1011                 continue;
1012
1013               case XK_ISO_Level3_Shift:
1014                 ModLevel3Mask = modmasks[i - 1];
1015                 continue;
1016
1017               case XK_Meta_L:
1018               case XK_Meta_R:
1019                 cm = "meta";
1020                 realmeta = i;
1021                 break;
1022
1023               case XK_Alt_L:
1024               case XK_Alt_R:
1025                 cm = "alt";
1026                 realalt = i;
1027                 break;
1028
1029               case XK_Super_L:
1030               case XK_Super_R:
1031                 cm = "super";
1032                 break;
1033
1034               case XK_Hyper_L:
1035               case XK_Hyper_R:
1036                 cm = "hyper";
1037                 break;
1038
1039               default:
1040                 continue;
1041             }
1042
1043           if (rsmod && strncasecmp (rsmod, cm, strlen (cm)) == 0)
1044             requestedmeta = i;
1045         }
1046     }
1047
1048   XFreeModifiermap (map);
1049
1050   i = requestedmeta ? requestedmeta
1051     : realmeta      ? realmeta
1052     : realalt       ? realalt
1053     : 0;
1054
1055   if (i)
1056     ModMetaMask = modmasks[i - 1];
1057 }
1058
1059 /*----------------------------------------------------------------------*/
1060 /* rxvt_Create_Windows () - Open and map the window */
1061 void
1062 rxvt_term::create_windows (int argc, const char *const *argv)
1063 {
1064   XClassHint classHint;
1065   XWMHints wmHint;
1066 #if ENABLE_FRILLS
1067   MWMHints mwmhints = { };
1068 #endif
1069   XGCValues gcvalue;
1070   XSetWindowAttributes attributes;
1071   Window top, parent;
1072
1073   dLocal (Display *, dpy);
1074
1075   /* grab colors before netscape does */
1076   get_colours ();
1077
1078   if (!set_fonts ())
1079     rxvt_fatal ("unable to load base fontset, please specify a valid one using -fn, aborting.\n");
1080
1081   parent = display->root;
1082
1083   attributes.override_redirect = !!option (Opt_override_redirect);
1084
1085 #if ENABLE_FRILLS
1086   if (option (Opt_borderLess))
1087     {
1088       if (XInternAtom (dpy, "_MOTIF_WM_INFO", True) == None)
1089         {
1090           // rxvt_warn("Window Manager does not support MWM hints.  Bypassing window manager control for borderless window.\n");
1091           attributes.override_redirect = true;
1092         }
1093       else
1094         {
1095           mwmhints.flags = MWM_HINTS_DECORATIONS;
1096         }
1097     }
1098 #endif
1099
1100 #if ENABLE_XEMBED
1101   if (rs[Rs_embed])
1102     {
1103       XWindowAttributes wattr;
1104
1105       parent = strtol (rs[Rs_embed], 0, 0);
1106
1107       if (!XGetWindowAttributes (dpy, parent, &wattr))
1108         rxvt_fatal ("invalid window-id specified with -embed, aborting.\n");
1109
1110       window_calc (wattr.width, wattr.height);
1111     }
1112 #endif
1113
1114   window_calc (0, 0);
1115
1116   /* sub-window placement & size in rxvt_resize_subwindows () */
1117   attributes.background_pixel = pix_colors_focused [Color_border];
1118   attributes.border_pixel     = pix_colors_focused [Color_border];
1119   attributes.colormap         = cmap;
1120
1121   top = XCreateWindow (dpy, parent,
1122                        szHint.x, szHint.y,
1123                        szHint.width, szHint.height,
1124                        ext_bwidth,
1125                        depth, InputOutput, visual,
1126                        CWColormap | CWBackPixel | CWBorderPixel | CWOverrideRedirect,
1127                        &attributes);
1128
1129   this->parent[0] = top;
1130
1131   old_width = szHint.width;
1132   old_height = szHint.height;
1133
1134   set_title     (rs [Rs_title]);
1135   set_icon_name (rs [Rs_iconName]);
1136
1137   classHint.res_name  = (char *)rs[Rs_name];
1138   classHint.res_class = (char *)RESCLASS;
1139
1140   wmHint.flags         = InputHint | StateHint | WindowGroupHint;
1141   wmHint.input         = True;
1142   wmHint.initial_state = option (Opt_iconic) ? IconicState : NormalState;
1143   wmHint.window_group  = top;
1144
1145   XmbSetWMProperties (dpy, top, NULL, NULL, (char **)argv, argc,
1146                       &szHint, &wmHint, &classHint);
1147 #if ENABLE_EWMH
1148 # ifdef HAVE_AFTERIMAGE
1149   /*
1150    * set up icon hint
1151    * rs [Rs_iconfile] is path to icon, asv has been created in init_resources
1152    */
1153
1154   if (rs [Rs_iconfile])
1155     {
1156       init_asv ();
1157
1158       ASImage *im = file2ASImage (rs [Rs_iconfile], 0xFFFFFFFF, SCREEN_GAMMA, 0, NULL);
1159       if (asv && im)
1160         {
1161           int w = im->width;
1162           int h = im->height;
1163           long *buffer = (long *)malloc ((2 + w * h) * sizeof (long));
1164           ASImage *result = scale_asimage (asv, im,
1165                                            w, h, ASA_ARGB32,
1166                                            100, ASIMAGE_QUALITY_DEFAULT);
1167           destroy_asimage (&im);
1168
1169           if (buffer && result)
1170             {
1171               ARGB32 *asbuf = result->alt.argb32;
1172               buffer [0] = w;
1173               buffer [1] = h;
1174
1175               for (unsigned int i = 0; i < w * h; ++i)
1176                 buffer [i + 2] = asbuf [i];
1177
1178               destroy_asimage (&result);
1179               XChangeProperty (dpy, top, xa[XA_NET_WM_ICON], XA_CARDINAL, 32,
1180                                PropModeReplace, (const unsigned char *) buffer, 2 + w * h);
1181               free (buffer);
1182             }
1183           else
1184             {
1185               if (!buffer)
1186                 rxvt_warn ("Memory allocation for icon hint failed, continuing without.\n");
1187
1188               if (!result)
1189                 rxvt_warn ("Icon image transformation to ARGB failed, continuing without.\n");
1190             }
1191         }
1192       else
1193         rxvt_warn ("Loading image icon failed, continuing without.\n");
1194     }
1195 # endif
1196 #endif
1197
1198 #if ENABLE_FRILLS
1199   if (mwmhints.flags)
1200     XChangeProperty (dpy, top, xa[XA_MOTIF_WM_HINTS], xa[XA_MOTIF_WM_HINTS], 32,
1201                      PropModeReplace, (unsigned char *)&mwmhints, PROP_MWM_HINTS_ELEMENTS);
1202 #endif
1203
1204   Atom protocols[] = {
1205     xa[XA_WM_DELETE_WINDOW],
1206 #if ENABLE_EWMH
1207     xa[XA_NET_WM_PING],
1208 #endif
1209   };
1210
1211   XSetWMProtocols (dpy, top, protocols, sizeof (protocols) / sizeof (protocols[0]));
1212
1213 #if ENABLE_FRILLS
1214   if (rs[Rs_transient_for])
1215     XSetTransientForHint (dpy, top, (Window)strtol (rs[Rs_transient_for], 0, 0));
1216 #endif
1217
1218 #if ENABLE_EWMH
1219   long pid = getpid ();
1220
1221   XChangeProperty (dpy, top,
1222                    xa[XA_NET_WM_PID], XA_CARDINAL, 32,
1223                    PropModeReplace, (unsigned char *)&pid, 1);
1224
1225   // _NET_WM_WINDOW_TYPE is NORMAL, which is the default
1226 #endif
1227
1228   XSelectInput (dpy, top,
1229                 KeyPressMask
1230 #if (MOUSE_WHEEL && MOUSE_SLIP_WHEELING) || ENABLE_FRILLS || ISO_14755
1231                 | KeyReleaseMask
1232 #endif
1233                 | FocusChangeMask | VisibilityChangeMask
1234                 | ExposureMask | StructureNotifyMask);
1235
1236   termwin_ev.start (display, top);
1237
1238   /* vt cursor: Black-on-White is standard, but this is more popular */
1239   TermWin_cursor = XCreateFontCursor (dpy, XC_xterm);
1240
1241   /* the vt window */
1242   vt = XCreateSimpleWindow (dpy, top,
1243                             window_vt_x, window_vt_y,
1244                             width, height,
1245                             0,
1246                             pix_colors_focused[Color_fg],
1247                             pix_colors_focused[Color_bg]);
1248
1249   attributes.bit_gravity = NorthWestGravity;
1250   XChangeWindowAttributes (dpy, vt, CWBitGravity, &attributes);
1251
1252   vt_emask = ExposureMask | ButtonPressMask | ButtonReleaseMask | PropertyChangeMask;
1253
1254   if (option (Opt_pointerBlank))
1255     vt_emask |= PointerMotionMask;
1256   else
1257     vt_emask |= Button1MotionMask | Button3MotionMask;
1258
1259   vt_select_input ();
1260
1261   vt_ev.start (display, vt);
1262
1263   /* graphics context for the vt window */
1264   gcvalue.foreground         = pix_colors[Color_fg];
1265   gcvalue.background         = pix_colors[Color_bg];
1266   gcvalue.graphics_exposures = 0;
1267
1268   gc = XCreateGC (dpy, vt,
1269                   GCForeground | GCBackground | GCGraphicsExposures,
1270                   &gcvalue);
1271
1272   drawable = new rxvt_drawable (this, vt);
1273
1274 #ifdef OFF_FOCUS_FADING
1275   // initially we are in unfocused state
1276   if (rs[Rs_fade])
1277     pix_colors = pix_colors_unfocused;
1278 #endif
1279
1280   pointer_unblank ();
1281   scr_recolour ();
1282 }
1283
1284 /* ------------------------------------------------------------------------- *
1285  *                            GET TTY CURRENT STATE                          *
1286  * ------------------------------------------------------------------------- */
1287 void
1288 rxvt_get_ttymode (struct termios *tio, int erase)
1289 {
1290   /*
1291    * standard System V termios interface
1292    */
1293   if (tcgetattr (STDIN_FILENO, tio) < 0)
1294     {
1295       // return error - use system defaults,
1296       // where possible, and zero elsewhere
1297       memset (tio, 0, sizeof (struct termios));
1298
1299       tio->c_cc[VINTR] = CINTR;
1300       tio->c_cc[VQUIT] = CQUIT;
1301       tio->c_cc[VERASE] = CERASE;
1302 #ifdef VERASE2
1303       tio->c_cc[VERASE2] = CERASE2;
1304 #endif
1305       tio->c_cc[VKILL] = CKILL;
1306       tio->c_cc[VSTART] = CSTART;
1307       tio->c_cc[VSTOP] = CSTOP;
1308       tio->c_cc[VSUSP] = CSUSP;
1309 # ifdef VDSUSP
1310       tio->c_cc[VDSUSP] = CDSUSP;
1311 # endif
1312 # ifdef VREPRINT
1313       tio->c_cc[VREPRINT] = CRPRNT;
1314 # endif
1315 # ifdef VDISCRD
1316       tio->c_cc[VDISCRD] = CFLUSH;
1317 # endif
1318 # ifdef VWERSE
1319       tio->c_cc[VWERSE] = CWERASE;
1320 # endif
1321 # ifdef VLNEXT
1322       tio->c_cc[VLNEXT] = CLNEXT;
1323 # endif
1324     }
1325
1326   tio->c_cc[VEOF] = CEOF;
1327   tio->c_cc[VEOL] = VDISABLE;
1328 # ifdef VEOL2
1329   tio->c_cc[VEOL2] = VDISABLE;
1330 # endif
1331 # ifdef VSWTC
1332   tio->c_cc[VSWTC] = VDISABLE;
1333 # endif
1334 # ifdef VSWTCH
1335   tio->c_cc[VSWTCH] = VDISABLE;
1336 # endif
1337 # if VMIN != VEOF
1338   tio->c_cc[VMIN] = 1;
1339 # endif
1340 # if VTIME != VEOL
1341   tio->c_cc[VTIME] = 0;
1342 # endif
1343
1344   if (erase != -1)
1345     tio->c_cc[VERASE] = (char)erase;
1346
1347   /* input modes */
1348   tio->c_iflag = (BRKINT | IGNPAR | ICRNL
1349 # ifdef IMAXBEL
1350                   | IMAXBEL
1351 # endif
1352                   | IXON);
1353
1354   /* output modes */
1355   tio->c_oflag = (OPOST | ONLCR);
1356
1357   /* control modes */
1358   tio->c_cflag = (CS8 | CREAD);
1359
1360   /* line discipline modes */
1361   tio->c_lflag = (ISIG | ICANON | IEXTEN | ECHO
1362 # if defined (ECHOCTL) && defined (ECHOKE)
1363                   | ECHOCTL | ECHOKE
1364 # endif
1365                   | ECHOE | ECHOK);
1366
1367   /*
1368    * Debugging
1369    */
1370 #ifdef DEBUG_TTYMODE
1371   /* c_iflag bits */
1372   fprintf (stderr, "Input flags\n");
1373
1374   /* cpp token stringize doesn't work on all machines <sigh> */
1375 # define FOO(flag,name)                 \
1376     if ((tio->c_iflag) & flag)          \
1377         fprintf (stderr, "%s ", name)
1378
1379   /* c_iflag bits */
1380   FOO (IGNBRK, "IGNBRK");
1381   FOO (BRKINT, "BRKINT");
1382   FOO (IGNPAR, "IGNPAR");
1383   FOO (PARMRK, "PARMRK");
1384   FOO (INPCK, "INPCK");
1385   FOO (ISTRIP, "ISTRIP");
1386   FOO (INLCR, "INLCR");
1387   FOO (IGNCR, "IGNCR");
1388   FOO (ICRNL, "ICRNL");
1389   FOO (IXON, "IXON");
1390   FOO (IXOFF, "IXOFF");
1391 # ifdef IUCLC
1392   FOO (IUCLC, "IUCLC");
1393 # endif
1394 # ifdef IXANY
1395   FOO (IXANY, "IXANY");
1396 # endif
1397 # ifdef IMAXBEL
1398   FOO (IMAXBEL, "IMAXBEL");
1399 # endif
1400
1401   fprintf (stderr, "\n");
1402
1403 # undef FOO
1404 # define FOO(entry, name)                                       \
1405     fprintf (stderr, "%-8s = %#04o\n", name, tio->c_cc [entry])
1406
1407   FOO (VINTR, "VINTR");
1408   FOO (VQUIT, "VQUIT");
1409   FOO (VERASE, "VERASE");
1410   FOO (VKILL, "VKILL");
1411   FOO (VEOF, "VEOF");
1412   FOO (VEOL, "VEOL");
1413 # ifdef VEOL2
1414   FOO (VEOL2, "VEOL2");
1415 # endif
1416 # ifdef VSWTC
1417   FOO (VSWTC, "VSWTC");
1418 # endif
1419 # ifdef VSWTCH
1420   FOO (VSWTCH, "VSWTCH");
1421 # endif
1422   FOO (VSTART, "VSTART");
1423   FOO (VSTOP, "VSTOP");
1424   FOO (VSUSP, "VSUSP");
1425 # ifdef VDSUSP
1426   FOO (VDSUSP, "VDSUSP");
1427 # endif
1428 # ifdef VREPRINT
1429   FOO (VREPRINT, "VREPRINT");
1430 # endif
1431 # ifdef VDISCRD
1432   FOO (VDISCRD, "VDISCRD");
1433 # endif
1434 # ifdef VWERSE
1435   FOO (VWERSE, "VWERSE");
1436 # endif
1437 # ifdef VLNEXT
1438   FOO (VLNEXT, "VLNEXT");
1439 # endif
1440
1441   fprintf (stderr, "\n");
1442 # undef FOO
1443 #endif /* DEBUG_TTYMODE */
1444 }
1445
1446 /*----------------------------------------------------------------------*/
1447 /*
1448  * Run the command in a subprocess and return a file descriptor for the
1449  * master end of the pseudo-teletype pair with the command talking to
1450  * the slave.
1451  */
1452 void
1453 rxvt_term::run_command (const char *const *argv)
1454 {
1455 #if ENABLE_FRILLS
1456   if (rs[Rs_pty_fd])
1457     {
1458       pty->pty = atoi (rs[Rs_pty_fd]);
1459
1460       if (pty->pty >= 0)
1461         {
1462           if (getfd_hook)
1463             pty->pty = (*getfd_hook) (pty->pty);
1464
1465           if (pty->pty < 0 || fcntl (pty->pty, F_SETFL, O_NONBLOCK))
1466             rxvt_fatal ("unusable pty-fd filehandle, aborting.\n");
1467         }
1468     }
1469   else
1470 #endif
1471     if (!pty->get ())
1472       rxvt_fatal ("can't initialize pseudo-tty, aborting.\n");
1473
1474   int er;
1475
1476 #ifndef NO_BACKSPACE_KEY
1477   if (rs[Rs_backspace_key][0] && !rs[Rs_backspace_key][1])
1478     er = rs[Rs_backspace_key][0];
1479   else if (strcmp (rs[Rs_backspace_key], "DEC") == 0)
1480     er = '\177';            /* the initial state anyway */
1481   else
1482 #endif
1483     er = -1;
1484
1485   rxvt_get_ttymode (&tio, er);
1486   /* init terminal attributes */
1487   cfsetospeed (&tio, BAUDRATE);
1488   cfsetispeed (&tio, BAUDRATE);
1489   tcsetattr (pty->tty, TCSANOW, &tio);
1490   pty->set_utf8_mode (enc_utf8);
1491
1492   /* set initial window size */
1493   tt_winch ();
1494
1495 #if ENABLE_FRILLS
1496   if (rs[Rs_pty_fd])
1497     return;
1498 #endif
1499
1500   /* spin off the command interpreter */
1501   switch (cmd_pid = fork ())
1502     {
1503       case -1:
1504         {
1505           cmd_pid = 0;
1506           rxvt_fatal ("can't fork, aborting.\n");
1507         }
1508       case 0:
1509         init_env ();
1510
1511         if (!pty->make_controlling_tty ())
1512           fprintf (stderr, "%s: could not obtain control of tty.", RESNAME);
1513         else
1514           {
1515             /* Reopen stdin, stdout and stderr over the tty file descriptor */
1516             dup2 (pty->tty, STDIN_FILENO);
1517             dup2 (pty->tty, STDOUT_FILENO);
1518             dup2 (pty->tty, STDERR_FILENO);
1519
1520             // close all our file handles that we do no longer need
1521             for (rxvt_term **t = termlist.begin (); t < termlist.end (); t++)
1522               {
1523                 if ((*t)->pty->pty > 2) close ((*t)->pty->pty);
1524                 if ((*t)->pty->tty > 2) close ((*t)->pty->tty);
1525               }
1526
1527             run_child (argv);
1528             fprintf (stderr, "%s: unable to exec child.", RESNAME);
1529           }
1530
1531         _exit (EXIT_FAILURE);
1532
1533       default:
1534         if (!option (Opt_utmpInhibit))
1535           pty->login (cmd_pid, option (Opt_loginShell), rs[Rs_display_name]);
1536
1537         pty->close_tty ();
1538
1539         child_ev.start (cmd_pid);
1540
1541         HOOK_INVOKE ((this, HOOK_CHILD_START, DT_INT, cmd_pid, DT_END));
1542         break;
1543     }
1544 }
1545
1546 /* ------------------------------------------------------------------------- *
1547  *                          CHILD PROCESS OPERATIONS                         *
1548  * ------------------------------------------------------------------------- */
1549 /*
1550  * The only open file descriptor is the slave tty - so no error messages.
1551  * returns are fatal
1552  */
1553 int
1554 rxvt_term::run_child (const char *const *argv)
1555 {
1556   char *login;
1557
1558   if (option (Opt_console))
1559     {
1560       /* be virtual console, fail silently */
1561 #ifdef TIOCCONS
1562       unsigned int on = 1;
1563
1564       ioctl (STDIN_FILENO, TIOCCONS, &on);
1565 #elif defined (SRIOCSREDIR)
1566       int fd;
1567
1568       fd = open (CONSOLE, O_WRONLY, 0);
1569       if (fd >= 0)
1570         if (ioctl (fd, SRIOCSREDIR, NULL) < 0)
1571           close (fd);
1572 #endif /* SRIOCSREDIR */
1573     }
1574
1575   /* reset signals and spin off the command interpreter */
1576   signal (SIGINT,  SIG_DFL);
1577   signal (SIGQUIT, SIG_DFL);
1578   signal (SIGCHLD, SIG_DFL);
1579   signal (SIGHUP,  SIG_DFL);
1580   signal (SIGPIPE, SIG_DFL);
1581   /*
1582    * mimick login's behavior by disabling the job control signals
1583    * a shell that wants them can turn them back on
1584    */
1585 #ifdef SIGTSTP
1586   signal (SIGTSTP, SIG_IGN);
1587   signal (SIGTTIN, SIG_IGN);
1588   signal (SIGTTOU, SIG_IGN);
1589 #endif /* SIGTSTP */
1590
1591   /* command interpreter path */
1592   if (argv)
1593     {
1594 # ifdef DEBUG_CMD
1595       int             i;
1596
1597       for (i = 0; argv[i]; i++)
1598         fprintf (stderr, "argv [%d] = \"%s\"\n", i, argv[i]);
1599 # endif
1600
1601       execvp (argv[0], (char *const *)argv);
1602       /* no error message: STDERR is closed! */
1603     }
1604   else
1605     {
1606       const char *argv0, *shell;
1607
1608       if ((shell = getenv ("SHELL")) == NULL || *shell == '\0')
1609         shell = "/bin/sh";
1610
1611       argv0 = rxvt_basename (shell);
1612
1613       if (option (Opt_loginShell))
1614         {
1615           login = (char *)rxvt_malloc (strlen (argv0) + 2);
1616
1617           login[0] = '-';
1618           strcpy (&login[1], argv0);
1619           argv0 = login;
1620         }
1621
1622       execlp (shell, argv0, (char *)0);
1623       /* no error message: STDERR is closed! */
1624     }
1625
1626   return -1;
1627 }
1628
1629 /*----------------------- end-of-file (C source) -----------------------*/