Added UTF-8 char length lookup table
[elinks.git] / src / osdep / osdep.c
blob1df9e3320d504574932a0a5fe06e595124779873
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 /* GNU Screen's clipboard */
353 if (is_gnuscreen()) {
354 struct string str;
356 if (!init_string(&str)) return NULL;
358 add_to_string(&str, "screen -X paste .");
359 if (str.length) exe(str.source);
360 if (str.source) done_string(&str);
363 return stracpy(empty_string_or_(clipboard));
366 void
367 set_clipboard_text(unsigned char *data)
369 /* GNU Screen's clipboard */
370 if (is_gnuscreen()) {
371 struct string str;
373 if (!init_string(&str)) return;
375 add_to_string(&str, "screen -X register . ");
376 add_shell_quoted_to_string(&str, data, strlen(data));
378 if (str.length) exe(str.source);
379 if (str.source) done_string(&str);
382 /* Shouldn't complain about leaks. */
383 if (clipboard) free(clipboard);
384 clipboard = strdup(data);
387 /* Set xterm-like term window's title. */
388 void
389 set_window_title(unsigned char *title)
391 unsigned char *s;
392 int xsize, ysize;
393 int j = 0;
395 #ifndef HAVE_SYS_CYGWIN_H
396 /* Check if we're in a xterm-like terminal. */
397 if (!is_xterm() && !is_gnuscreen()) return;
398 #endif
400 /* Retrieve terminal dimensions. */
401 get_terminal_size(0, &xsize, &ysize);
403 /* Check if terminal width is reasonnable. */
404 if (xsize < 1 || xsize > 1024) return;
406 /* Allocate space for title + 3 ending points + null char. */
407 s = mem_alloc(xsize + 3 + 1);
408 if (!s) return;
410 /* Copy title to s if different from NULL */
411 if (title) {
412 int i;
414 /* We limit title length to terminal width and ignore control
415 * chars if any. Note that in most cases window decoration
416 * reduces printable width, so it's just a precaution. */
417 /* Note that this is the right place where to do it, since
418 * potential alternative set_window_title() routines might
419 * want to take different precautions. */
420 for (i = 0; title[i] && i < xsize; i++) {
421 /* 0x80 .. 0x9f are ISO-8859-* control characters.
422 * In some other encodings they could be used for
423 * legitimate characters, though (ie. in Kamenicky).
424 * We should therefore maybe check for these only
425 * if the terminal is running in an ISO- encoding. */
426 if (iscntrl(title[i]) || (title[i] & 0x7f) < 0x20
427 || title[i] == 0x7f)
428 continue;
430 s[j++] = title[i];
433 /* If title is truncated, add "..." */
434 if (i == xsize) {
435 s[j++] = '.';
436 s[j++] = '.';
437 s[j++] = '.';
440 s[j] = '\0';
442 /* Send terminal escape sequence + title string */
443 printf("\033]0;%s\a", s);
445 #if 0
446 /* Miciah don't like this so it is disabled because it changes the
447 * default window name. --jonas */
448 /* Set the GNU screen window name */
449 if (is_gnuscreen())
450 printf("\033k%s\033\134", s);
451 #endif
453 fflush(stdout);
455 mem_free(s);
458 #ifdef HAVE_X11
459 static int x_error = 0;
461 static int
462 catch_x_error(void)
464 x_error = 1;
465 return 0;
467 #endif
469 unsigned char *
470 get_window_title(void)
472 #ifdef HAVE_X11
473 /* Following code is stolen from our beloved vim. */
474 unsigned char *winid;
475 Display *display;
476 Window window, root, parent, *children;
477 XTextProperty text_prop;
478 Status status;
479 unsigned int num_children;
480 unsigned char *ret = NULL;
482 if (!is_xterm())
483 return NULL;
485 winid = getenv("WINDOWID");
486 if (!winid)
487 return NULL;
488 window = (Window) atol(winid);
489 if (!window)
490 return NULL;
492 display = XOpenDisplay(NULL);
493 if (!display)
494 return NULL;
496 /* If WINDOWID is bad, we don't want X to abort us. */
497 x_error = 0;
498 XSetErrorHandler((int (*)(Display *, XErrorEvent *)) catch_x_error);
500 status = XGetWMName(display, window, &text_prop);
501 /* status = XGetWMIconName(x11_display, x11_window, &text_prop); */
502 while (!x_error && (!status || !text_prop.value)) {
503 if (!XQueryTree(display, window, &root, &parent, &children, &num_children))
504 break;
505 if (children)
506 XFree((void *) children);
507 if (parent == root || parent == 0)
508 break;
509 window = parent;
510 status = XGetWMName(display, window, &text_prop);
513 if (!x_error && status && text_prop.value) {
514 ret = stracpy(text_prop.value);
515 XFree(text_prop.value);
518 XCloseDisplay(display);
520 return ret;
521 #else
522 /* At least reset the window title to a blank one. */
523 return stracpy("");
524 #endif
528 resize_window(int width, int height, int old_width, int old_height)
530 #ifdef HAVE_X11
531 /* Following code is stolen from our beloved vim. */
532 unsigned char *winid;
533 Display *display;
534 Window window;
535 Status status;
536 XWindowAttributes attributes;
538 if (!is_xterm())
539 return -1;
541 winid = getenv("WINDOWID");
542 if (!winid)
543 return -1;
544 window = (Window) atol(winid);
545 if (!window)
546 return -1;
548 display = XOpenDisplay(NULL);
549 if (!display)
550 return -1;
552 /* If WINDOWID is bad, we don't want X to abort us. */
553 x_error = 0;
554 XSetErrorHandler((int (*)(Display *, XErrorEvent *)) catch_x_error);
556 status = XGetWindowAttributes(display, window, &attributes);
558 while (!x_error && !status) {
559 Window root, parent, *children;
560 unsigned int num_children;
562 if (!XQueryTree(display, window, &root, &parent, &children, &num_children))
563 break;
564 if (children)
565 XFree((void *) children);
566 if (parent == root || parent == 0)
567 break;
568 window = parent;
569 status = XGetWindowAttributes(display, window, &attributes);
572 if (!x_error && status) {
573 double ratio_width = (double) attributes.width / old_width;
574 double ratio_height = (double) attributes.height / old_height;
576 width = (int) ((double) width * ratio_width);
577 height = (int) ((double) height * ratio_height);
579 status = XResizeWindow(display, window, width, height);
580 while (!x_error && !status) {
581 Window root, parent, *children;
582 unsigned int num_children;
584 if (!XQueryTree(display, window, &root, &parent, &children, &num_children))
585 break;
586 if (children)
587 XFree((void *) children);
588 if (parent == root || parent == 0)
589 break;
590 window = parent;
591 status = XResizeWindow(display, window, width, height);
595 XCloseDisplay(display);
597 return 0;
598 #else
599 return -1;
600 #endif
603 #endif
606 /* Threads */
608 #if defined(HAVE_BEGINTHREAD) || defined(CONFIG_OS_BEOS)
610 struct tdata {
611 void (*fn)(void *, int);
612 int h;
613 unsigned char data[1];
616 void
617 bgt(struct tdata *t)
619 #ifdef SIGPIPE
620 signal(SIGPIPE, SIG_IGN);
621 #endif
622 t->fn(t->data, t->h);
623 write(t->h, "x", 1);
624 close(t->h);
625 free(t);
628 #else
631 start_thread(void (*fn)(void *, int), void *ptr, int l)
633 int p[2];
634 pid_t pid;
636 if (c_pipe(p) < 0) return -1;
637 if (set_nonblocking_fd(p[0]) < 0) return -1;
638 if (set_nonblocking_fd(p[1]) < 0) return -1;
640 pid = fork();
641 if (!pid) {
642 struct terminal *term;
644 /* Close input in this thread; otherwise, if it will live
645 * longer than its parent, it'll block the terminal until it'll
646 * quit as well; this way it will hopefully just die unseen and
647 * in background, causing no trouble. */
648 /* Particularly, when async dns resolving was in progress and
649 * someone quitted ELinks, it could make a delay before the
650 * terminal would be really freed and returned to shell. */
651 foreach (term, terminals)
652 if (term->fdin > 0)
653 close(term->fdin);
655 close(p[0]);
656 fn(ptr, p[1]);
657 write(p[1], "x", 1);
658 close(p[1]);
659 /* We use _exit() here instead of exit(), see
660 * http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC6 for
661 * reasons. Fixed by Sven Neumann <sven@convergence.de>. */
662 _exit(0);
664 if (pid == -1) {
665 close(p[0]);
666 close(p[1]);
667 return -1;
670 close(p[1]);
671 return p[0];
674 #endif
677 #ifndef OS2_MOUSE
678 void
679 want_draw(void)
683 void
684 done_draw(void)
687 #endif
690 #if !defined(CONFIG_OS_WIN32)
692 get_output_handle(void)
694 return 1;
698 get_ctl_handle(void)
700 static int fd = -1;
702 if (isatty(0)) return 0;
703 if (fd < 0) fd = open("/dev/tty", O_RDONLY);
704 return fd;
706 #endif
709 #if !defined(CONFIG_OS_BEOS) && !(defined(HAVE_BEGINTHREAD) && defined(HAVE_READ_KBD)) \
710 && !defined(CONFIG_OS_WIN32)
713 get_input_handle(void)
715 return get_ctl_handle();
718 #endif
720 #ifndef CONFIG_OS_WIN32
722 void
723 init_osdep(void)
725 #ifdef HAVE_LOCALE_H
726 setlocale(LC_ALL, "");
727 #endif
730 #endif
732 #if defined(CONFIG_OS_UNIX) || defined(CONFIG_OS_OS2) || defined(CONFIG_OS_RISCOS)
734 void
735 terminate_osdep(void)
739 #endif
741 #ifndef CONFIG_OS_BEOS
743 void
744 block_stdin(void)
748 void
749 unblock_stdin(void)
753 #endif
756 void
757 elinks_cfmakeraw(struct termios *t)
759 #ifdef HAVE_CFMAKERAW
760 cfmakeraw(t);
761 #ifdef VMIN
762 t->c_cc[VMIN] = 1; /* cfmakeraw() is broken on AIX --mikulas */
763 #endif
764 #else
765 t->c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
766 t->c_oflag &= ~OPOST;
767 t->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
768 t->c_cflag &= ~(CSIZE|PARENB);
769 t->c_cflag |= CS8;
770 t->c_cc[VMIN] = 1;
771 t->c_cc[VTIME] = 0;
772 #endif
775 #if !defined(CONFIG_MOUSE) || (!defined(CONFIG_GPM) && !defined(CONFIG_SYSMOUSE) && !defined(OS2_MOUSE))
777 void *
778 handle_mouse(int cons, void (*fn)(void *, unsigned char *, int),
779 void *data)
781 return NULL;
784 void
785 unhandle_mouse(void *data)
789 void
790 suspend_mouse(void *data)
794 void
795 resume_mouse(void *data)
799 #endif
801 #ifndef CONFIG_OS_WIN32
802 /* Create a bitmask consisting from system-independent envirnoment modifiers.
803 * This is then complemented by system-specific modifiers in an appropriate
804 * get_system_env() routine. */
805 static int
806 get_common_env(void)
808 int env = 0;
810 if (is_xterm()) env |= ENV_XWIN;
811 if (is_twterm()) env |= ENV_TWIN;
812 if (is_gnuscreen()) env |= ENV_SCREEN;
814 /* ENV_CONSOLE is always set now and indicates that we are working w/ a
815 * displaying-capable character-adressed terminal. Sounds purely
816 * theoretically now, but it already makes some things easier and it
817 * could give us interesting opportunities later (after graphical
818 * frontends will be introduced, when working in some mysterious daemon
819 * mode or who knows what ;). --pasky */
820 env |= ENV_CONSOLE;
822 return env;
824 #endif
826 #if defined(CONFIG_OS_UNIX) || defined(CONFIG_OS_RISCOS)
828 get_system_env(void)
830 return get_common_env();
832 #endif
836 can_resize_window(int environment)
838 return !!(environment & (ENV_OS2VIO | ENV_XWIN));
841 #ifndef CONFIG_OS_OS2
843 can_open_os_shell(int environment)
845 return 1;
848 void
849 set_highpri(void)
852 #endif
855 unsigned char *
856 get_system_str(int xwin)
858 return xwin ? SYSTEM_STR "-xwin" : SYSTEM_STR;