aboutsummaryrefslogtreecommitdiff
path: root/safetitle.c
diff options
context:
space:
mode:
Diffstat (limited to 'safetitle.c')
-rw-r--r--safetitle.c104
1 files changed, 104 insertions, 0 deletions
diff --git a/safetitle.c b/safetitle.c
new file mode 100644
index 0000000..b9d8be0
--- /dev/null
+++ b/safetitle.c
@@ -0,0 +1,104 @@
+/*
+ * safetitle sets the title of the terminal window to the given string,
+ * unless the terminal type is blacklisted.
+ */
+
+#include <err.h>
+#include <fcntl.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/select.h>
+#include <termios.h>
+#include <unistd.h>
+
+#define WSCONS_DA (char[]){27,91,62,50,52,59,50,48,59,48,99,0}
+#define SCREEN_DA (char[]){27,91,62,56,51,59,52,48,56,48,48,59,48,99,0}
+
+int screen = 0;
+
+int
+blacklisted(int fd)
+{
+ char *buf, c;
+ fd_set fds;
+ int i, r;
+ struct timeval timeout;
+
+ if((buf = malloc(200*sizeof(char)))==NULL)
+ err(1, "malloc");
+
+ /* check if GNU screen */
+ write(fd, "\033[>c", 4);
+ i = 0;
+ while(r = read(fd, &c, 1)){
+ if(r==-1)
+ return 1;
+ buf[i++] = c;
+ if(c=='c') break;
+ }
+ buf[i] = '\0';
+ screen = strcmp(buf, SCREEN_DA)==0;
+
+ /* ignore strange trailing nul before reading response */
+ FD_ZERO(&fds);
+ FD_SET(fd, &fds);
+ timeout.tv_sec = 0;
+ timeout.tv_usec = 0;
+ while(select(fd+1, &fds, NULL, NULL, &timeout)>0)
+ read(fd, &c, 1);
+
+ /* check (real) terminal type(s) */
+ if(screen) write(fd, "\033P\033[>c\033\\", 8);
+ else write(fd, "\033[>c", 4);
+
+ i = 0;
+ while(r = read(fd, &c, 1)){
+loop:
+ if(r==-1)
+ return 1;
+ buf[i++] = c;
+ if(c==99) break;
+ }
+ buf[i] = '\0';
+
+ if(strcmp(buf, WSCONS_DA)==0)
+ return 1;
+
+ /* go back and check remaining responses (if any) */
+check:
+ FD_ZERO(&fds);
+ FD_SET(fd, &fds);
+ timeout.tv_sec = 0;
+ timeout.tv_usec = 1; /* it takes a millisecond sometimes */
+ if(screen && select(fd+1, &fds, NULL, NULL, &timeout)>0){
+ /* ignore strange trailing nul before reading response */
+ if(read(fd, &c, 1)==-1)
+ return 1;
+ i = 0;
+ if(c==0) goto check;
+ else goto loop;
+ }
+
+ return 0;
+}
+
+void
+safetitle(char *title)
+{
+ int ttyfd;
+
+ if((ttyfd = open("/dev/tty", O_RDWR))==-1)
+ err(1, "open");
+
+ /* get device attributes for real terminal */
+ if(blacklisted(ttyfd))
+ return;
+
+ if(strncmp(title, "/home/", 6)==0)
+ title += 6;
+
+ /* set title */
+ if(screen) dprintf(ttyfd, "\033P\033]2;%s\007\033\\", title);
+ else dprintf(ttyfd, "\033]2;%s\007", title);
+}