##// END OF EJS Templates
Merge pull request #10587 from Carreau/vendor-terminal-size...
Thomas Kluyver -
r23698:b8b3943a merge
parent child Browse files
Show More
@@ -0,0 +1,131 b''
1 # vendored version of backports.get_terminal_size as nemesapece package are a
2 # mess and break, especially on ubuntu. This file is under MIT Licence.
3 # See https://pypi.python.org/pypi/backports.shutil_get_terminal_size
4 #
5 # commit: afc5714b1545a5a3aa44cfb5e078d39165bf76ab (Feb 20, 2016)
6 # from
7 # https://github.com/chrippa/backports.shutil_get_terminal_size
8 #
9 # The MIT License (MIT)
10 #
11 # Copyright (c) 2014 Christopher Rosell
12 #
13 # Permission is hereby granted, free of charge, to any person obtaining a copy
14 # of this software and associated documentation files (the "Software"), to deal
15 # in the Software without restriction, including without limitation the rights
16 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
17 # copies of the Software, and to permit persons to whom the Software is
18 # furnished to do so, subject to the following conditions:
19 #
20 # The above copyright notice and this permission notice shall be included in
21 # all copies or substantial portions of the Software.
22 #
23 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
26 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
28 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
29 # THE SOFTWARE.
30 #
31 """This is a backport of shutil.get_terminal_size from Python 3.3.
32
33 The original implementation is in C, but here we use the ctypes and
34 fcntl modules to create a pure Python version of os.get_terminal_size.
35 """
36
37 import os
38 import struct
39 import sys
40
41 from collections import namedtuple
42
43 __all__ = ["get_terminal_size"]
44
45
46 terminal_size = namedtuple("terminal_size", "columns lines")
47
48 try:
49 from ctypes import windll, create_string_buffer, WinError
50
51 _handle_ids = {
52 0: -10,
53 1: -11,
54 2: -12,
55 }
56
57 def _get_terminal_size(fd):
58 handle = windll.kernel32.GetStdHandle(_handle_ids[fd])
59 if handle == 0:
60 raise OSError('handle cannot be retrieved')
61 if handle == -1:
62 raise WinError()
63 csbi = create_string_buffer(22)
64 res = windll.kernel32.GetConsoleScreenBufferInfo(handle, csbi)
65 if res:
66 res = struct.unpack("hhhhHhhhhhh", csbi.raw)
67 left, top, right, bottom = res[5:9]
68 columns = right - left + 1
69 lines = bottom - top + 1
70 return terminal_size(columns, lines)
71 else:
72 raise WinError()
73
74 except ImportError:
75 import fcntl
76 import termios
77
78 def _get_terminal_size(fd):
79 try:
80 res = fcntl.ioctl(fd, termios.TIOCGWINSZ, b"\x00" * 4)
81 except IOError as e:
82 raise OSError(e)
83 lines, columns = struct.unpack("hh", res)
84
85 return terminal_size(columns, lines)
86
87
88 def get_terminal_size(fallback=(80, 24)):
89 """Get the size of the terminal window.
90
91 For each of the two dimensions, the environment variable, COLUMNS
92 and LINES respectively, is checked. If the variable is defined and
93 the value is a positive integer, it is used.
94
95 When COLUMNS or LINES is not defined, which is the common case,
96 the terminal connected to sys.__stdout__ is queried
97 by invoking os.get_terminal_size.
98
99 If the terminal size cannot be successfully queried, either because
100 the system doesn't support querying, or because we are not
101 connected to a terminal, the value given in fallback parameter
102 is used. Fallback defaults to (80, 24) which is the default
103 size used by many terminal emulators.
104
105 The value returned is a named tuple of type os.terminal_size.
106 """
107 # Try the environment first
108 try:
109 columns = int(os.environ["COLUMNS"])
110 except (KeyError, ValueError):
111 columns = 0
112
113 try:
114 lines = int(os.environ["LINES"])
115 except (KeyError, ValueError):
116 lines = 0
117
118 # Only query if necessary
119 if columns <= 0 or lines <= 0:
120 try:
121 size = _get_terminal_size(sys.__stdout__.fileno())
122 except (NameError, OSError):
123 size = terminal_size(*fallback)
124
125 if columns <= 0:
126 columns = size.columns
127 if lines <= 0:
128 lines = size.lines
129
130 return terminal_size(columns, lines)
131
@@ -1,120 +1,125 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """
2 """
3 Utilities for working with terminals.
3 Utilities for working with terminals.
4
4
5 Authors:
5 Authors:
6
6
7 * Brian E. Granger
7 * Brian E. Granger
8 * Fernando Perez
8 * Fernando Perez
9 * Alexander Belchenko (e-mail: bialix AT ukr.net)
9 * Alexander Belchenko (e-mail: bialix AT ukr.net)
10 """
10 """
11
11
12 from __future__ import absolute_import
13
12 # Copyright (c) IPython Development Team.
14 # Copyright (c) IPython Development Team.
13 # Distributed under the terms of the Modified BSD License.
15 # Distributed under the terms of the Modified BSD License.
14
16
15 import os
17 import os
16 import sys
18 import sys
17 import warnings
19 import warnings
18 try:
20 try:
19 from shutil import get_terminal_size as _get_terminal_size
21 from shutil import get_terminal_size as _get_terminal_size
20 except ImportError:
22 except ImportError:
21 # use backport on Python 2
23 # use backport on Python 2
22 from backports.shutil_get_terminal_size import get_terminal_size as _get_terminal_size
24 try:
25 from backports.shutil_get_terminal_size import get_terminal_size as _get_terminal_size
26 except ImportError:
27 from ._get_terminal_size import _get_terminal_size
23
28
24 from . import py3compat
29 from . import py3compat
25
30
26 #-----------------------------------------------------------------------------
31 #-----------------------------------------------------------------------------
27 # Code
32 # Code
28 #-----------------------------------------------------------------------------
33 #-----------------------------------------------------------------------------
29
34
30 # This variable is part of the expected API of the module:
35 # This variable is part of the expected API of the module:
31 ignore_termtitle = True
36 ignore_termtitle = True
32
37
33
38
34
39
35 if os.name == 'posix':
40 if os.name == 'posix':
36 def _term_clear():
41 def _term_clear():
37 os.system('clear')
42 os.system('clear')
38 elif sys.platform == 'win32':
43 elif sys.platform == 'win32':
39 def _term_clear():
44 def _term_clear():
40 os.system('cls')
45 os.system('cls')
41 else:
46 else:
42 def _term_clear():
47 def _term_clear():
43 pass
48 pass
44
49
45
50
46
51
47 def toggle_set_term_title(val):
52 def toggle_set_term_title(val):
48 """Control whether set_term_title is active or not.
53 """Control whether set_term_title is active or not.
49
54
50 set_term_title() allows writing to the console titlebar. In embedded
55 set_term_title() allows writing to the console titlebar. In embedded
51 widgets this can cause problems, so this call can be used to toggle it on
56 widgets this can cause problems, so this call can be used to toggle it on
52 or off as needed.
57 or off as needed.
53
58
54 The default state of the module is for the function to be disabled.
59 The default state of the module is for the function to be disabled.
55
60
56 Parameters
61 Parameters
57 ----------
62 ----------
58 val : bool
63 val : bool
59 If True, set_term_title() actually writes to the terminal (using the
64 If True, set_term_title() actually writes to the terminal (using the
60 appropriate platform-specific module). If False, it is a no-op.
65 appropriate platform-specific module). If False, it is a no-op.
61 """
66 """
62 global ignore_termtitle
67 global ignore_termtitle
63 ignore_termtitle = not(val)
68 ignore_termtitle = not(val)
64
69
65
70
66 def _set_term_title(*args,**kw):
71 def _set_term_title(*args,**kw):
67 """Dummy no-op."""
72 """Dummy no-op."""
68 pass
73 pass
69
74
70
75
71 def _set_term_title_xterm(title):
76 def _set_term_title_xterm(title):
72 """ Change virtual terminal title in xterm-workalikes """
77 """ Change virtual terminal title in xterm-workalikes """
73 sys.stdout.write('\033]0;%s\007' % title)
78 sys.stdout.write('\033]0;%s\007' % title)
74
79
75 if os.name == 'posix':
80 if os.name == 'posix':
76 TERM = os.environ.get('TERM','')
81 TERM = os.environ.get('TERM','')
77 if TERM.startswith('xterm'):
82 if TERM.startswith('xterm'):
78 _set_term_title = _set_term_title_xterm
83 _set_term_title = _set_term_title_xterm
79 elif sys.platform == 'win32':
84 elif sys.platform == 'win32':
80 try:
85 try:
81 import ctypes
86 import ctypes
82
87
83 SetConsoleTitleW = ctypes.windll.kernel32.SetConsoleTitleW
88 SetConsoleTitleW = ctypes.windll.kernel32.SetConsoleTitleW
84 SetConsoleTitleW.argtypes = [ctypes.c_wchar_p]
89 SetConsoleTitleW.argtypes = [ctypes.c_wchar_p]
85
90
86 def _set_term_title(title):
91 def _set_term_title(title):
87 """Set terminal title using ctypes to access the Win32 APIs."""
92 """Set terminal title using ctypes to access the Win32 APIs."""
88 SetConsoleTitleW(title)
93 SetConsoleTitleW(title)
89 except ImportError:
94 except ImportError:
90 def _set_term_title(title):
95 def _set_term_title(title):
91 """Set terminal title using the 'title' command."""
96 """Set terminal title using the 'title' command."""
92 global ignore_termtitle
97 global ignore_termtitle
93
98
94 try:
99 try:
95 # Cannot be on network share when issuing system commands
100 # Cannot be on network share when issuing system commands
96 curr = py3compat.getcwd()
101 curr = py3compat.getcwd()
97 os.chdir("C:")
102 os.chdir("C:")
98 ret = os.system("title " + title)
103 ret = os.system("title " + title)
99 finally:
104 finally:
100 os.chdir(curr)
105 os.chdir(curr)
101 if ret:
106 if ret:
102 # non-zero return code signals error, don't try again
107 # non-zero return code signals error, don't try again
103 ignore_termtitle = True
108 ignore_termtitle = True
104
109
105
110
106 def set_term_title(title):
111 def set_term_title(title):
107 """Set terminal title using the necessary platform-dependent calls."""
112 """Set terminal title using the necessary platform-dependent calls."""
108 if ignore_termtitle:
113 if ignore_termtitle:
109 return
114 return
110 _set_term_title(title)
115 _set_term_title(title)
111
116
112
117
113 def freeze_term_title():
118 def freeze_term_title():
114 warnings.warn("This function is deprecated, use toggle_set_term_title()")
119 warnings.warn("This function is deprecated, use toggle_set_term_title()")
115 global ignore_termtitle
120 global ignore_termtitle
116 ignore_termtitle = True
121 ignore_termtitle = True
117
122
118
123
119 def get_terminal_size(defaultx=80, defaulty=25):
124 def get_terminal_size(defaultx=80, defaulty=25):
120 return _get_terminal_size((defaultx, defaulty))
125 return _get_terminal_size((defaultx, defaulty))
General Comments 0
You need to be logged in to leave comments. Login now