aboutsummaryrefslogtreecommitdiffhomepage
path: root/crates/shirabe-external-packages/src/symfony/console/terminal.rs
blob: cc8f8128eb84702248e6a7cd7cb95ec46106da39 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
//! ref: composer/vendor/symfony/console/Terminal.php

use shirabe_php_shim::PhpMixed;
use std::cell::Cell;

thread_local! {
    static WIDTH: Cell<Option<i64>> = const { Cell::new(None) };
    static HEIGHT: Cell<Option<i64>> = const { Cell::new(None) };
    static STTY: Cell<Option<bool>> = const { Cell::new(None) };
}

#[derive(Debug)]
pub struct Terminal;

impl Default for Terminal {
    fn default() -> Self {
        Self::new()
    }
}

impl Terminal {
    pub fn new() -> Self {
        Terminal
    }

    /// Gets the terminal width.
    pub fn get_width(&self) -> i64 {
        let width = shirabe_php_shim::getenv("COLUMNS");
        if let Some(width) = width {
            return shirabe_php_shim::intval(&PhpMixed::String(shirabe_php_shim::trim(
                &width.to_string_lossy(),
                None,
            )));
        }

        if WIDTH.with(|w| w.get()).is_none() {
            Self::init_dimensions();
        }

        WIDTH.with(|w| w.get()).filter(|&v| v != 0).unwrap_or(80)
    }

    /// Gets the terminal height.
    pub fn get_height(&self) -> i64 {
        let height = shirabe_php_shim::getenv("LINES");
        if let Some(height) = height {
            return shirabe_php_shim::intval(&PhpMixed::String(shirabe_php_shim::trim(
                &height.to_string_lossy(),
                None,
            )));
        }

        if HEIGHT.with(|h| h.get()).is_none() {
            Self::init_dimensions();
        }

        HEIGHT.with(|h| h.get()).filter(|&v| v != 0).unwrap_or(50)
    }

    pub fn has_stty_available() -> bool {
        if let Some(stty) = STTY.with(|s| s.get()) {
            return stty;
        }

        // skip check if shell_exec function is disabled
        if !shirabe_php_shim::function_exists("shell_exec") {
            return false;
        }

        let result = shirabe_php_shim::shell_exec(&format!(
            "stty 2> {}",
            if shirabe_php_shim::DIRECTORY_SEPARATOR == "\\" {
                "NUL"
            } else {
                "/dev/null"
            }
        ))
        .is_some();
        STTY.with(|s| s.set(Some(result)));
        result
    }

    fn init_dimensions() {
        if shirabe_php_shim::DIRECTORY_SEPARATOR == "\\" {
            let ansicon = shirabe_php_shim::getenv("ANSICON");
            let mut matches: Vec<Option<String>> = Vec::new();
            if let Some(ansicon) = &ansicon
                && shirabe_php_shim::preg_match(
                    "/^(\\d+)x(\\d+)(?: \\((\\d+)x(\\d+)\\))?$/",
                    &shirabe_php_shim::trim(&ansicon.to_string_lossy(), None),
                    &mut matches,
                )
            {
                // extract [w, H] from "wxh (WxH)"
                // or [w, h] from "wxh"
                WIDTH.with(|w| {
                    w.set(Some(shirabe_php_shim::intval(&PhpMixed::String(
                        matches[1].clone().unwrap_or_default(),
                    ))))
                });
                HEIGHT.with(|h| {
                    let value = if matches.get(4).map(|m| m.is_some()).unwrap_or(false) {
                        shirabe_php_shim::intval(&PhpMixed::String(
                            matches[4].clone().unwrap_or_default(),
                        ))
                    } else {
                        shirabe_php_shim::intval(&PhpMixed::String(
                            matches[2].clone().unwrap_or_default(),
                        ))
                    };
                    h.set(Some(value));
                });
                return;
            }

            if !Self::has_vt100_support() && Self::has_stty_available() {
                // only use stty on Windows if the terminal does not support vt100 (e.g. Windows 7 + git-bash)
                // testing for stty in a Windows 10 vt100-enabled console will implicitly disable vt100 support on STDOUT
                Self::init_dimensions_using_stty();
            } else if let Some(dimensions) = Self::get_console_mode() {
                // extract [w, h] from "wxh"
                WIDTH.with(|w| w.set(Some(dimensions[0])));
                HEIGHT.with(|h| h.set(Some(dimensions[1])));
            }
        } else {
            Self::init_dimensions_using_stty();
        }
    }

    /// Returns whether STDOUT has vt100 support (some Windows 10+ configurations).
    fn has_vt100_support() -> bool {
        shirabe_php_shim::function_exists("sapi_windows_vt100_support") && {
            let stream = shirabe_php_shim::php_fopen_resource("php://stdout", "w");
            shirabe_php_shim::sapi_windows_vt100_support(&stream)
        }
    }

    /// Initializes dimensions using the output of an stty columns line.
    fn init_dimensions_using_stty() {
        if let Some(stty_string) = Self::get_stty_columns() {
            if stty_string.is_empty() {
                return;
            }
            let mut matches: Vec<Option<String>> = Vec::new();
            if shirabe_php_shim::preg_match(
                "/rows.(\\d+);.columns.(\\d+);/i",
                &stty_string,
                &mut matches,
            ) {
                // extract [w, h] from "rows h; columns w;"
                WIDTH.with(|w| {
                    w.set(Some(shirabe_php_shim::intval(&PhpMixed::String(
                        matches[2].clone().unwrap_or_default(),
                    ))))
                });
                HEIGHT.with(|h| {
                    h.set(Some(shirabe_php_shim::intval(&PhpMixed::String(
                        matches[1].clone().unwrap_or_default(),
                    ))))
                });
            } else if shirabe_php_shim::preg_match(
                "/;.(\\d+).rows;.(\\d+).columns/i",
                &stty_string,
                &mut matches,
            ) {
                // extract [w, h] from "; h rows; w columns"
                WIDTH.with(|w| {
                    w.set(Some(shirabe_php_shim::intval(&PhpMixed::String(
                        matches[2].clone().unwrap_or_default(),
                    ))))
                });
                HEIGHT.with(|h| {
                    h.set(Some(shirabe_php_shim::intval(&PhpMixed::String(
                        matches[1].clone().unwrap_or_default(),
                    ))))
                });
            }
        }
    }

    /// Runs and parses mode CON if it's available, suppressing any error output.
    ///
    /// Returns an array composed of the width and the height or null if it could not be parsed.
    fn get_console_mode() -> Option<Vec<i64>> {
        let info = Self::read_from_process("mode CON");

        let info = info?;
        let mut matches: Vec<Option<String>> = Vec::new();
        if !shirabe_php_shim::preg_match(
            "/--------+\\r?\\n.+?(\\d+)\\r?\\n.+?(\\d+)\\r?\\n/",
            &info,
            &mut matches,
        ) {
            return None;
        }

        Some(vec![
            shirabe_php_shim::intval(&PhpMixed::String(matches[2].clone().unwrap_or_default())),
            shirabe_php_shim::intval(&PhpMixed::String(matches[1].clone().unwrap_or_default())),
        ])
    }

    /// Runs and parses stty -a if it's available, suppressing any error output.
    fn get_stty_columns() -> Option<String> {
        Self::read_from_process("stty -a | grep columns")
    }

    fn read_from_process(command: &str) -> Option<String> {
        if !shirabe_php_shim::function_exists("proc_open") {
            return None;
        }

        // Sparse PHP descriptorspec `[1 => ['pipe', 'w'], 2 => ['pipe', 'w']]`: fd 0 is inherited.
        let descriptorspec = [
            shirabe_php_shim::Descriptor::Inherit,
            shirabe_php_shim::Descriptor::Pipe("w".to_string()),
            shirabe_php_shim::Descriptor::Pipe("w".to_string()),
        ];

        let cp = if shirabe_php_shim::function_exists("sapi_windows_cp_set") {
            shirabe_php_shim::sapi_windows_cp_get(None)
        } else {
            0
        };

        let mut pipes: indexmap::IndexMap<i64, shirabe_php_shim::PhpResource> =
            indexmap::IndexMap::new();
        let process = match shirabe_php_shim::proc_open(
            command,
            &descriptorspec,
            &mut pipes,
            None,
            None,
            None,
        ) {
            Ok(process) => process,
            Err(_) => return None,
        };

        let info = pipes
            .get(&1)
            .and_then(shirabe_php_shim::stream_get_contents);
        if let Some(pipe) = pipes.get(&1) {
            shirabe_php_shim::fclose(pipe);
        }
        if let Some(pipe) = pipes.get(&2) {
            shirabe_php_shim::fclose(pipe);
        }
        shirabe_php_shim::proc_close(&process);

        if cp != 0 {
            shirabe_php_shim::sapi_windows_cp_set(cp);
        }

        info
    }
}