terminal.c (2764B)
1 /*************************************************************************** 2 * _ _ ____ _ 3 * Project ___| | | | _ \| | 4 * / __| | | | |_) | | 5 * | (__| |_| | _ <| |___ 6 * \___|\___/|_| \_\_____| 7 * 8 * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. 9 * 10 * This software is licensed as described in the file COPYING, which 11 * you should have received as part of this distribution. The terms 12 * are also available at https://curl.se/docs/copyright.html. 13 * 14 * You may opt to use, copy, modify, merge, publish, distribute and/or sell 15 * copies of the Software, and permit persons to whom the Software is 16 * furnished to do so, under the terms of the COPYING file. 17 * 18 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY 19 * KIND, either express or implied. 20 * 21 * SPDX-License-Identifier: curl 22 * 23 ***************************************************************************/ 24 #include "tool_setup.h" 25 26 #ifdef HAVE_SYS_IOCTL_H 27 #include <sys/ioctl.h> 28 #endif 29 30 #include "terminal.h" 31 #include "memdebug.h" /* keep this as LAST include */ 32 33 #ifdef HAVE_TERMIOS_H 34 # include <termios.h> 35 #elif defined(HAVE_TERMIO_H) 36 # include <termio.h> 37 #endif 38 39 /* 40 * get_terminal_columns() returns the number of columns in the current 41 * terminal. It will return 79 on failure. Also, the number can be big. 42 */ 43 44 unsigned int get_terminal_columns(void) 45 { 46 unsigned int width = 0; 47 char *colp = curl_getenv("COLUMNS"); 48 if(colp) { 49 curl_off_t num; 50 const char *p = colp; 51 if(!curlx_str_number(&p, &num, 10000) && (num > 20)) 52 width = (unsigned int)num; 53 curl_free(colp); 54 } 55 56 if(!width) { 57 int cols = 0; 58 59 #ifdef TIOCGSIZE 60 struct ttysize ts; 61 if(!ioctl(STDIN_FILENO, TIOCGSIZE, &ts)) 62 cols = ts.ts_cols; 63 #elif defined(TIOCGWINSZ) 64 struct winsize ts; 65 if(!ioctl(STDIN_FILENO, TIOCGWINSZ, &ts)) 66 cols = (int)ts.ws_col; 67 #elif defined(_WIN32) && !defined(CURL_WINDOWS_UWP) && !defined(UNDER_CE) 68 { 69 HANDLE stderr_hnd = GetStdHandle(STD_ERROR_HANDLE); 70 CONSOLE_SCREEN_BUFFER_INFO console_info; 71 72 if((stderr_hnd != INVALID_HANDLE_VALUE) && 73 GetConsoleScreenBufferInfo(stderr_hnd, &console_info)) { 74 /* 75 * Do not use +1 to get the true screen-width since writing a 76 * character at the right edge will cause a line wrap. 77 */ 78 cols = (int) 79 (console_info.srWindow.Right - console_info.srWindow.Left); 80 } 81 } 82 #endif /* TIOCGSIZE */ 83 if(cols >= 0 && cols < 10000) 84 width = (unsigned int)cols; 85 } 86 if(!width) 87 width = 79; 88 return width; /* 79 for unknown, might also be tiny or enormous */ 89 }