1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 | 'use strict';
|
9 |
|
10 | var os = require('os');
|
11 | var isNumber = require('is-number');
|
12 | var cp = require('child_process');
|
13 |
|
14 | function windowSize(options) {
|
15 | options = options || {};
|
16 | return streamSize(options, 'stdout') ||
|
17 | streamSize(options, 'stderr') ||
|
18 | envSize() ||
|
19 | ttySize(options);
|
20 | }
|
21 |
|
22 | function streamSize(options, name) {
|
23 | var stream = (process && process[name]) || options[name];
|
24 | var size;
|
25 |
|
26 | if (!stream) return;
|
27 | if (typeof stream.getWindowSize === 'function') {
|
28 | size = stream.getWindowSize();
|
29 | if (isSize(size)) {
|
30 | return {
|
31 | width: size[0],
|
32 | height: size[1],
|
33 | type: name
|
34 | };
|
35 | }
|
36 | }
|
37 |
|
38 | size = [stream.columns, stream.rows];
|
39 | if (isSize(size)) {
|
40 | return {
|
41 | width: Number(size[0]),
|
42 | height: Number(size[1]),
|
43 | type: name
|
44 | };
|
45 | }
|
46 | }
|
47 |
|
48 | function envSize() {
|
49 | if (process && process.env) {
|
50 | var size = [process.env.COLUMNS, process.env.ROWS];
|
51 | if (isSize(size)) {
|
52 | return {
|
53 | width: Number(size[0]),
|
54 | height: Number(size[1]),
|
55 | type: 'process.env'
|
56 | };
|
57 | }
|
58 | }
|
59 | }
|
60 |
|
61 | function ttySize(options, stdout) {
|
62 | var tty = options.tty || require('tty');
|
63 | if (tty && typeof tty.getWindowSize === 'function') {
|
64 | var size = tty.getWindowSize(stdout);
|
65 | if (isSize(size)) {
|
66 | return {
|
67 | width: Number(size[1]),
|
68 | height: Number(size[0]),
|
69 | type: 'tty'
|
70 | };
|
71 | }
|
72 | }
|
73 | }
|
74 |
|
75 | function winSize() {
|
76 | if (os.release().startsWith('10')) {
|
77 | var cmd = 'wmic path Win32_VideoController get CurrentHorizontalResolution,CurrentVerticalResolution';
|
78 | var numberPattern = /\d+/g;
|
79 | var code = cp.execSync(cmd).toString();
|
80 | var size = code.match(numberPattern);
|
81 | if (isSize(size)) {
|
82 | return {
|
83 | width: Number(size[0]),
|
84 | height: Number(size[1]),
|
85 | type: 'windows'
|
86 | };
|
87 | }
|
88 | }
|
89 | }
|
90 |
|
91 | function tputSize() {
|
92 | try {
|
93 | var buf = cp.execSync('tput cols && tput lines', {stdio: ['ignore', 'pipe', process.stderr]});
|
94 | var size = buf.toString().trim().split('\n');
|
95 | if (isSize(size)) {
|
96 | return {
|
97 | width: Number(size[0]),
|
98 | height: Number(size[1]),
|
99 | type: 'tput'
|
100 | };
|
101 | }
|
102 | } catch (err) {}
|
103 | }
|
104 |
|
105 |
|
106 |
|
107 |
|
108 |
|
109 |
|
110 | function isSize(size) {
|
111 | return Array.isArray(size) && isNumber(size[0]) && isNumber(size[1]);
|
112 | }
|
113 |
|
114 |
|
115 |
|
116 |
|
117 |
|
118 | module.exports = {
|
119 | get: windowSize,
|
120 | env: envSize,
|
121 | tty: ttySize,
|
122 | tput: tputSize,
|
123 | win: winSize
|
124 | };
|