Bug 1004: NEWS and AUTHORS
[elinks/kon.git] / src / osdep / osdep.c
blob74eab68a1e9ca55629595b29b942c211b89cddfa
1 /* Features which vary with the OS */
3 #ifdef HAVE_CONFIG_H
4 #include "config.h"
5 #endif
7 #include <errno.h>
8 #ifdef HAVE_IO_H
9 #include <io.h> /* For win32 && set_bin(). */
10 #endif
11 #include <signal.h>
12 #include <stdio.h>
13 #include <stdlib.h>
14 #include <string.h>
15 #ifdef HAVE_SYS_IOCTL_H
16 #include <sys/ioctl.h>
17 #endif
18 #ifdef HAVE_SYS_SIGNAL_H
19 #include <sys/signal.h>
20 #endif
21 #include <sys/types.h>
22 #ifdef HAVE_SYS_SOCKET_H
23 #include <sys/socket.h> /* Need to be after sys/types.h */
24 #endif
25 #ifdef HAVE_FCNTL_H
26 #include <fcntl.h> /* OS/2 needs this after sys/types.h */
27 #endif
29 /* We need to have it here. Stupid BSD. */
30 #ifdef HAVE_NETINET_IN_H
31 #include <netinet/in.h>
32 #endif
33 #ifdef HAVE_ARPA_INET_H
34 #include <arpa/inet.h>
35 #endif
37 /* This is for some exotic TOS mangling when handling passive FTP sockets. */
38 #ifdef HAVE_NETINET_IN_SYSTM_H
39 #include <netinet/in_systm.h>
40 #else
41 #ifdef HAVE_NETINET_IN_SYSTEM_H
42 #include <netinet/in_system.h>
43 #endif
44 #endif
45 #ifdef HAVE_NETINET_IP_H
46 #include <netinet/ip.h>
47 #endif
49 #ifdef HAVE_TERMIOS_H
50 #include <termios.h>
51 #endif
53 #ifdef HAVE_UNISTD_H
54 #include <unistd.h>
55 #endif
57 #ifdef HAVE_LOCALE_H
58 /* For the sake of SunOS, keep this away from files including
59 * intl/gettext/libintl.h because <locale.h> includes system <libintl.h> which
60 * either includes system gettext header or contains gettext function
61 * declarations. */
62 #include <locale.h>
63 #endif
65 #ifdef HAVE_X11
66 #include <X11/Xlib.h>
67 #include <X11/Xutil.h>
68 #endif
71 #include "elinks.h"
73 #include "main/select.h"
74 #include "osdep/osdep.h"
75 #include "osdep/signals.h"
76 #include "terminal/terminal.h"
77 #include "util/conv.h"
78 #include "util/memory.h"
79 #include "util/string.h"
82 /* Set a file descriptor to non-blocking mode. It returns a non-zero value
83 * on error. */
84 int
85 set_nonblocking_fd(int fd)
87 #if defined(O_NONBLOCK) || defined(O_NDELAY)
88 int flags = fcntl(fd, F_GETFL, 0);
90 if (flags < 0) return -1;
91 #if defined(O_NONBLOCK)
92 return fcntl(fd, F_SETFL, flags | O_NONBLOCK);
93 #else
94 return fcntl(fd, F_SETFL, flags | O_NDELAY);
95 #endif
97 #elif defined(FIONBIO)
98 int flag = 1;
100 return ioctl(fd, FIONBIO, &flag);
101 #else
102 return 0;
103 #endif
106 /* Set a file descriptor to blocking mode. It returns a non-zero value on
107 * error. */
109 set_blocking_fd(int fd)
111 #if defined(O_NONBLOCK) || defined(O_NDELAY)
112 int flags = fcntl(fd, F_GETFL, 0);
114 if (flags < 0) return -1;
115 #if defined(O_NONBLOCK)
116 return fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
117 #else
118 return fcntl(fd, F_SETFL, flags & ~O_NDELAY);
119 #endif
121 #elif defined(FIONBIO)
122 int flag = 0;
124 return ioctl(fd, FIONBIO, &flag);
125 #else
126 return 0;
127 #endif
130 void
131 set_ip_tos_throughput(int socket)
133 #if defined(IP_TOS) && defined(IPTOS_THROUGHPUT)
134 int on = IPTOS_THROUGHPUT;
136 setsockopt(socket, IPPROTO_IP, IP_TOS, (char *) &on, sizeof(on));
137 #endif
141 get_e(unsigned char *env)
143 char *v = getenv(env);
145 return (v ? atoi(v) : 0);
148 unsigned char *
149 get_cwd(void)
151 int bufsize = 128;
152 unsigned char *buf;
154 while (1) {
155 buf = mem_alloc(bufsize);
156 if (!buf) return NULL;
157 if (getcwd(buf, bufsize)) return buf;
158 mem_free(buf);
160 if (errno == EINTR) continue;
161 if (errno != ERANGE) return NULL;
162 bufsize += 128;
165 return NULL;
168 void
169 set_cwd(unsigned char *path)
171 if (path) while (chdir(path) && errno == EINTR);
174 unsigned char *
175 get_shell(void)
177 unsigned char *shell = GETSHELL;
179 if (!shell || !*shell)
180 shell = DEFAULT_SHELL;
182 return shell;
186 /* Terminal size */
188 #if !defined(CONFIG_OS_OS2) && !defined(CONFIG_OS_WIN32)
190 static void
191 sigwinch(void *s)
193 ((void (*)(void)) s)();
196 void
197 handle_terminal_resize(int fd, void (*fn)(void))
199 install_signal_handler(SIGWINCH, sigwinch, fn, 0);
202 void
203 unhandle_terminal_resize(int fd)
205 install_signal_handler(SIGWINCH, NULL, NULL, 0);
208 void
209 get_terminal_size(int fd, int *x, int *y)
211 struct winsize ws;
213 if (ioctl(1, TIOCGWINSZ, &ws) != -1) {
214 *x = ws.ws_col;
215 *y = ws.ws_row;
216 } else {
217 *x = 0;
218 *y = 0;
221 if (!*x) {
222 *x = get_e("COLUMNS");
223 if (!*x) *x = DEFAULT_TERMINAL_WIDTH;
225 if (!*y) {
226 *y = get_e("LINES");
227 if (!*y) *y = DEFAULT_TERMINAL_HEIGHT;
231 #endif
233 /* Pipe */
235 #if defined(CONFIG_OS_UNIX) || defined(CONFIG_OS_BEOS) || defined(CONFIG_OS_RISCOS)
237 void
238 set_bin(int fd)
243 c_pipe(int *fd)
245 return pipe(fd);
248 #elif defined(CONFIG_OS_OS2) || defined(CONFIG_OS_WIN32)
250 void
251 set_bin(int fd)
253 setmode(fd, O_BINARY);
257 c_pipe(int *fd)
259 int r = pipe(fd);
261 if (!r) {
262 set_bin(fd[0]);
263 set_bin(fd[1]);
266 return r;
269 #endif
271 /* Exec */
274 is_twterm(void) /* Check if it make sense to call a twterm. */
276 static int tw = -1;
278 if (tw == -1) tw = !!getenv("TWDISPLAY");
280 return tw;
284 is_gnuscreen(void)
286 static int screen = -1;
288 if (screen == -1) screen = !!getenv("STY");
290 return screen;
294 #if defined(CONFIG_OS_UNIX) || defined(CONFIG_OS_WIN32)
297 is_xterm(void)
299 static int xt = -1;
301 if (xt == -1) {
302 /* Paraphrased from debian bug 228977:
304 * It is not enough to simply check the DISPLAY env variable,
305 * as it is pretty legal to have a DISPLAY set. While these
306 * days this practice is pretty uncommon, it still makes sense
307 * sometimes, especially for people who prefer the text mode
308 * for some reason. Only relying on DISPLAY will results in bad
309 * codes being written to the terminal.
311 * Any real xterm derivative sets WINDOWID as well.
312 * Unfortunately, konsole is an exception, and it needs to be
313 * checked for separately.
315 * FIXME: The code below still fails to detect some terminals
316 * that do support a title (like the popular PuTTY ssh client).
317 * In general, proper xterm detection is a nightmarish task...
319 * -- Adam Borowski <kilobyte@mimuw.edu.pl> */
320 unsigned char *display = getenv("DISPLAY");
321 unsigned char *windowid = getenv("WINDOWID");
323 if (!windowid || !*windowid)
324 windowid = getenv("KONSOLE_DCOP_SESSION");
325 xt = (display && *display && windowid && *windowid);
328 return xt;
331 #endif
333 unsigned int resize_count = 0;
335 #ifndef CONFIG_OS_OS2
337 #if !(defined(CONFIG_OS_BEOS) && defined(HAVE_SETPGID)) && !defined(CONFIG_OS_WIN32)
340 exe(unsigned char *path)
342 return system(path);
345 #endif
347 static unsigned char *clipboard;
349 unsigned char *
350 get_clipboard_text(void)
352 /* The following support for GNU Screen's clipboard is
353 * disabled for two reasons:
355 * 1. It does not actually return the string from that
356 * clipboard, but rather causes the clipboard contents to
357 * appear in stdin. get_clipboard_text is normally called
358 * because the user pressed a Paste key in an input field,
359 * so the characters end up being inserted in that field;
360 * but if there are newlines in the clipboard, then the
361 * field may lose focus, in which case the remaining
362 * characters may trigger arbitrary actions in ELinks.
364 * 2. It pastes from both GNU Screen's clipboard and the ELinks
365 * internal clipboard. Because set_clipboard_text also sets
366 * them both, the same text would typically get pasted twice.
368 * Users can instead use the GNU Screen key bindings to run the
369 * paste command. This method still suffers from problem 1 but
370 * any user of GNU Screen should know that already. */
371 #if 0
372 /* GNU Screen's clipboard */
373 if (is_gnuscreen()) {
374 struct string str;
376 if (!init_string(&str)) return NULL;
378 add_to_string(&str, "screen -X paste .");
379 if (str.length) exe(str.source);
380 if (str.source) done_string(&str);
382 #endif
384 return stracpy(empty_string_or_(clipboard));
387 void
388 set_clipboard_text(unsigned char *data)
390 /* GNU Screen's clipboard */
391 if (is_gnuscreen()) {
392 struct string str;
394 if (!init_string(&str)) return;
396 add_to_string(&str, "screen -X register . ");
397 add_shell_quoted_to_string(&str, data, strlen(data));
399 if (str.length) exe(str.source);
400 if (str.source) done_string(&str);
403 /* Shouldn't complain about leaks. */
404 if (clipboard) free(clipboard);
405 clipboard = strdup(data);
408 /* Set xterm-like term window's title. */
409 void
410 set_window_title(unsigned char *title)
412 unsigned char *s;
413 int xsize, ysize;
414 int j = 0;
416 #ifndef HAVE_SYS_CYGWIN_H
417 /* Check if we're in a xterm-like terminal. */
418 if (!is_xterm() && !is_gnuscreen()) return;
419 #endif
421 /* Retrieve terminal dimensions. */
422 get_terminal_size(0, &xsize, &ysize);
424 /* Check if terminal width is reasonnable. */
425 if (xsize < 1 || xsize > 1024) return;
427 /* Allocate space for title + 3 ending points + null char. */
428 s = mem_alloc(xsize + 3 + 1);
429 if (!s) return;
431 /* Copy title to s if different from NULL */
432 if (title) {
433 int i;
435 /* We limit title length to terminal width and ignore control
436 * chars if any. Note that in most cases window decoration
437 * reduces printable width, so it's just a precaution. */
438 /* Note that this is the right place where to do it, since
439 * potential alternative set_window_title() routines might
440 * want to take different precautions. */
441 for (i = 0; title[i] && i < xsize; i++) {
442 /* 0x80 .. 0x9f are ISO-8859-* control characters.
443 * In some other encodings they could be used for
444 * legitimate characters, though (ie. in Kamenicky).
445 * We should therefore maybe check for these only
446 * if the terminal is running in an ISO- encoding. */
447 if (iscntrl(title[i]) || (title[i] & 0x7f) < 0x20
448 || title[i] == 0x7f)
449 continue;
451 s[j++] = title[i];
454 /* If title is truncated, add "..." */
455 if (i == xsize) {
456 s[j++] = '.';
457 s[j++] = '.';
458 s[j++] = '.';
461 s[j] = '\0';
463 /* Send terminal escape sequence + title string */
464 printf("\033]0;%s\a", s);
466 #if 0
467 /* Miciah don't like this so it is disabled because it changes the
468 * default window name. --jonas */
469 /* Set the GNU screen window name */
470 if (is_gnuscreen())
471 printf("\033k%s\033\134", s);
472 #endif
474 fflush(stdout);
476 mem_free(s);
479 #ifdef HAVE_X11
480 static int x_error = 0;
482 static int
483 catch_x_error(void)
485 x_error = 1;
486 return 0;
488 #endif
490 unsigned char *
491 get_window_title(void)
493 #ifdef HAVE_X11
494 /* Following code is stolen from our beloved vim. */
495 unsigned char *winid;
496 Display *display;
497 Window window, root, parent, *children;
498 XTextProperty text_prop;
499 Status status;
500 unsigned int num_children;
501 unsigned char *ret = NULL;
503 if (!is_xterm())
504 return NULL;
506 winid = getenv("WINDOWID");
507 if (!winid)
508 return NULL;
509 window = (Window) atol(winid);
510 if (!window)
511 return NULL;
513 display = XOpenDisplay(NULL);
514 if (!display)
515 return NULL;
517 /* If WINDOWID is bad, we don't want X to abort us. */
518 x_error = 0;
519 XSetErrorHandler((int (*)(Display *, XErrorEvent *)) catch_x_error);
521 status = XGetWMName(display, window, &text_prop);
522 /* status = XGetWMIconName(x11_display, x11_window, &text_prop); */
523 while (!x_error && (!status || !text_prop.value)) {
524 if (!XQueryTree(display, window, &root, &parent, &children, &num_children))
525 break;
526 if (children)
527 XFree((void *) children);
528 if (parent == root || parent == 0)
529 break;
530 window = parent;
531 status = XGetWMName(display, window, &text_prop);
534 if (!x_error && status && text_prop.value) {
535 ret = stracpy(text_prop.value);
536 XFree(text_prop.value);
539 XCloseDisplay(display);
541 return ret;
542 #else
543 /* At least reset the window title to a blank one. */
544 return stracpy("");
545 #endif
549 resize_window(int width, int height, int old_width, int old_height)
551 #ifdef HAVE_X11
552 /* Following code is stolen from our beloved vim. */
553 unsigned char *winid;
554 Display *display;
555 Window window;
556 Status status;
557 XWindowAttributes attributes;
559 if (!is_xterm())
560 return -1;
562 winid = getenv("WINDOWID");
563 if (!winid)
564 return -1;
565 window = (Window) atol(winid);
566 if (!window)
567 return -1;
569 display = XOpenDisplay(NULL);
570 if (!display)
571 return -1;
573 /* If WINDOWID is bad, we don't want X to abort us. */
574 x_error = 0;
575 XSetErrorHandler((int (*)(Display *, XErrorEvent *)) catch_x_error);
577 status = XGetWindowAttributes(display, window, &attributes);
579 while (!x_error && !status) {
580 Window root, parent, *children;
581 unsigned int num_children;
583 if (!XQueryTree(display, window, &root, &parent, &children, &num_children))
584 break;
585 if (children)
586 XFree((void *) children);
587 if (parent == root || parent == 0)
588 break;
589 window = parent;
590 status = XGetWindowAttributes(display, window, &attributes);
593 if (!x_error && status) {
594 XSizeHints *size_hints;
595 long mask;
596 int px_width = 0;
597 int px_height = 0;
599 /* With xterm 210, a window with 80x24 characters at
600 * a 6x13 font appears to have 484x316 pixels; both
601 * the width and height include four extra pixels.
602 * Computing a new size by scaling these values often
603 * results in windows that cannot display as many
604 * characters as was intended. We can do better if we
605 * can find out the actual size of character cells.
606 * If the terminal emulator has set a window size
607 * increment, assume that is the cell size. */
608 size_hints = XAllocSizeHints();
609 if (size_hints != NULL
610 && XGetWMNormalHints(display, window, size_hints, &mask)
611 && (mask & PResizeInc) != 0) {
612 px_width = attributes.width
613 + (width - old_width) * size_hints->width_inc;
614 px_height = attributes.height
615 + (height - old_height) * size_hints->height_inc;
617 if (px_width <= 0 || px_height <= 0) {
618 double ratio_width = (double) attributes.width / old_width;
619 double ratio_height = (double) attributes.height / old_height;
621 px_width = (int) ((double) width * ratio_width);
622 px_height = (int) ((double) height * ratio_height);
625 if (size_hints)
626 XFree(size_hints);
628 status = XResizeWindow(display, window, px_width, px_height);
629 while (!x_error && !status) {
630 Window root, parent, *children;
631 unsigned int num_children;
633 if (!XQueryTree(display, window, &root, &parent, &children, &num_children))
634 break;
635 if (children)
636 XFree((void *) children);
637 if (parent == root || parent == 0)
638 break;
639 window = parent;
640 status = XResizeWindow(display, window, px_width, px_height);
644 XCloseDisplay(display);
646 return 0;
647 #else
648 return -1;
649 #endif
652 #endif
655 /* Threads */
657 #if defined(HAVE_BEGINTHREAD) || defined(CONFIG_OS_BEOS)
659 struct tdata {
660 void (*fn)(void *, int);
661 int h;
662 unsigned char data[1];
665 void
666 bgt(struct tdata *t)
668 #ifdef SIGPIPE
669 signal(SIGPIPE, SIG_IGN);
670 #endif
671 t->fn(t->data, t->h);
672 write(t->h, "x", 1);
673 close(t->h);
674 free(t);
677 #else
680 start_thread(void (*fn)(void *, int), void *ptr, int l)
682 int p[2];
683 pid_t pid;
685 if (c_pipe(p) < 0) return -1;
686 if (set_nonblocking_fd(p[0]) < 0) return -1;
687 if (set_nonblocking_fd(p[1]) < 0) return -1;
689 pid = fork();
690 if (!pid) {
691 struct terminal *term;
693 /* Close input in this thread; otherwise, if it will live
694 * longer than its parent, it'll block the terminal until it'll
695 * quit as well; this way it will hopefully just die unseen and
696 * in background, causing no trouble. */
697 /* Particularly, when async dns resolving was in progress and
698 * someone quitted ELinks, it could make a delay before the
699 * terminal would be really freed and returned to shell. */
700 foreach (term, terminals)
701 if (term->fdin > 0)
702 close(term->fdin);
704 close(p[0]);
705 fn(ptr, p[1]);
706 write(p[1], "x", 1);
707 close(p[1]);
708 /* We use _exit() here instead of exit(), see
709 * http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC6 for
710 * reasons. Fixed by Sven Neumann <sven@convergence.de>. */
711 _exit(0);
713 if (pid == -1) {
714 close(p[0]);
715 close(p[1]);
716 return -1;
719 close(p[1]);
720 return p[0];
723 #endif
726 #ifndef OS2_MOUSE
727 void
728 want_draw(void)
732 void
733 done_draw(void)
736 #endif
739 #if !defined(CONFIG_OS_WIN32)
741 get_output_handle(void)
743 return 1;
747 get_ctl_handle(void)
749 static int fd = -1;
751 if (isatty(0)) return 0;
752 if (fd < 0) fd = open("/dev/tty", O_RDONLY);
753 return fd;
755 #endif
758 #if !defined(CONFIG_OS_BEOS) && !(defined(HAVE_BEGINTHREAD) && defined(HAVE_READ_KBD)) \
759 && !defined(CONFIG_OS_WIN32)
762 get_input_handle(void)
764 return get_ctl_handle();
767 #endif
769 #ifndef CONFIG_OS_WIN32
771 void
772 init_osdep(void)
774 #ifdef HAVE_LOCALE_H
775 setlocale(LC_ALL, "");
776 #endif
779 #endif
781 #if defined(CONFIG_OS_UNIX) || defined(CONFIG_OS_OS2) || defined(CONFIG_OS_RISCOS)
783 void
784 terminate_osdep(void)
788 #endif
790 #ifndef CONFIG_OS_BEOS
792 void
793 block_stdin(void)
797 void
798 unblock_stdin(void)
802 #endif
805 void
806 elinks_cfmakeraw(struct termios *t)
808 /* This elinks_cfmakeraw() intentionally leaves the following
809 * settings unchanged, even though the standard cfmakeraw()
810 * would change some of them:
812 * - c_cflag & CSIZE: number of bits per character.
813 * Bug 54 asked ELinks not to change this.
814 * - c_cflag & (PARENB | PARODD): parity bit in characters.
815 * Bug 54 asked ELinks not to change this.
816 * - c_iflag & (IXON | IXOFF | IXANY): XON/XOFF flow control.
818 * The reasoning is, if the user has set up unusual values for
819 * those settings before starting ELinks, then the terminal
820 * probably expects those values and ELinks should not mess
821 * with them. */
822 t->c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL);
823 t->c_oflag &= ~OPOST;
824 t->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
825 t->c_cc[VMIN] = 1;
826 t->c_cc[VTIME] = 0;
829 #if !defined(CONFIG_MOUSE) || (!defined(CONFIG_GPM) && !defined(CONFIG_SYSMOUSE) && !defined(OS2_MOUSE))
831 void *
832 handle_mouse(int cons, void (*fn)(void *, unsigned char *, int),
833 void *data)
835 return NULL;
838 void
839 unhandle_mouse(void *data)
843 void
844 suspend_mouse(void *data)
848 void
849 resume_mouse(void *data)
853 #endif
855 #ifndef CONFIG_OS_WIN32
856 /* Create a bitmask consisting from system-independent envirnoment modifiers.
857 * This is then complemented by system-specific modifiers in an appropriate
858 * get_system_env() routine. */
859 static int
860 get_common_env(void)
862 int env = 0;
864 if (is_xterm()) env |= ENV_XWIN;
865 if (is_twterm()) env |= ENV_TWIN;
866 if (is_gnuscreen()) env |= ENV_SCREEN;
868 /* ENV_CONSOLE is always set now and indicates that we are working w/ a
869 * displaying-capable character-adressed terminal. Sounds purely
870 * theoretically now, but it already makes some things easier and it
871 * could give us interesting opportunities later (after graphical
872 * frontends will be introduced, when working in some mysterious daemon
873 * mode or who knows what ;). --pasky */
874 env |= ENV_CONSOLE;
876 return env;
878 #endif
880 #if defined(CONFIG_OS_UNIX) || defined(CONFIG_OS_RISCOS)
882 get_system_env(void)
884 return get_common_env();
886 #endif
890 can_resize_window(int environment)
892 return !!(environment & (ENV_OS2VIO | ENV_XWIN));
895 #ifndef CONFIG_OS_OS2
897 can_open_os_shell(int environment)
899 return 1;
902 void
903 set_highpri(void)
906 #endif
909 unsigned char *
910 get_system_str(int xwin)
912 return xwin ? SYSTEM_STR "-xwin" : SYSTEM_STR;