blob: ea551e26c811771f5a12f5dc7495444bac2eadd9 [file] [log] [blame]
bigbiff bigbiffe60683a2013-02-22 20:55:50 -05001/*
2 * No copyright is claimed. This code is in the public domain; do with
3 * it what you wish.
4 *
5 * Written by Karel Zak <kzak@redhat.com>
6 */
7#include <ctype.h>
8
9#include "c.h"
10#include "ttyutils.h"
11
12int get_terminal_width(void)
13{
14#ifdef TIOCGSIZE
15 struct ttysize t_win;
16#endif
17#ifdef TIOCGWINSZ
18 struct winsize w_win;
19#endif
20 const char *cp;
21
22#ifdef TIOCGSIZE
bigbiff7b4c7a62015-01-01 19:44:14 -050023 if (ioctl (STDIN_FILENO, TIOCGSIZE, &t_win) == 0)
bigbiff bigbiffe60683a2013-02-22 20:55:50 -050024 return t_win.ts_cols;
25#endif
26#ifdef TIOCGWINSZ
bigbiff7b4c7a62015-01-01 19:44:14 -050027 if (ioctl (STDIN_FILENO, TIOCGWINSZ, &w_win) == 0)
bigbiff bigbiffe60683a2013-02-22 20:55:50 -050028 return w_win.ws_col;
29#endif
30 cp = getenv("COLUMNS");
31 if (cp) {
32 char *end = NULL;
33 long c;
34
35 errno = 0;
36 c = strtol(cp, &end, 10);
37
38 if (errno == 0 && end && *end == '\0' && end > cp &&
39 c > 0 && c <= INT_MAX)
40 return c;
41 }
42 return 0;
43}
44
bigbiff7b4c7a62015-01-01 19:44:14 -050045int get_terminal_name(int fd,
46 const char **path,
bigbiff bigbiffe60683a2013-02-22 20:55:50 -050047 const char **name,
48 const char **number)
49{
50 const char *tty;
51 const char *p;
52
53 if (name)
54 *name = NULL;
55 if (path)
56 *path = NULL;
57 if (number)
58 *number = NULL;
59
bigbiff7b4c7a62015-01-01 19:44:14 -050060 tty = ttyname(fd);
bigbiff bigbiffe60683a2013-02-22 20:55:50 -050061 if (!tty)
62 return -1;
63 if (path)
64 *path = tty;
65 tty = strncmp(tty, "/dev/", 5) == 0 ? tty + 5 : tty;
66 if (name)
67 *name = tty;
68 if (number) {
69 for (p = tty; p && *p; p++) {
70 if (isdigit(*p)) {
71 *number = p;
72 break;
73 }
74 }
75 }
76 return 0;
77}
78
79
80#ifdef TEST_PROGRAM
81# include <stdlib.h>
82int main(void)
83{
84 const char *path, *name, *num;
85
bigbiff7b4c7a62015-01-01 19:44:14 -050086 if (get_terminal_name(STDERR_FILENO, &path, &name, &num) == 0) {
bigbiff bigbiffe60683a2013-02-22 20:55:50 -050087 fprintf(stderr, "tty path: %s\n", path);
88 fprintf(stderr, "tty name: %s\n", name);
89 fprintf(stderr, "tty number: %s\n", num);
90 }
91 fprintf(stderr, "tty width: %d\n", get_terminal_width());
92
93 return EXIT_SUCCESS;
94}
95#endif