termux-app
76 строк · 2.2 Кб
1package com.termux.shared.shell;
2
3import androidx.annotation.NonNull;
4import androidx.annotation.Nullable;
5
6import com.termux.shared.file.FileUtils;
7import com.termux.terminal.TerminalBuffer;
8import com.termux.terminal.TerminalEmulator;
9import com.termux.terminal.TerminalSession;
10
11import java.lang.reflect.Field;
12
13import java.util.ArrayList;
14import java.util.Collections;
15import java.util.List;
16
17public class ShellUtils {
18
19/** Get process id of {@link Process}. */
20public static int getPid(Process p) {
21try {
22Field f = p.getClass().getDeclaredField("pid");
23f.setAccessible(true);
24try {
25return f.getInt(p);
26} finally {
27f.setAccessible(false);
28}
29} catch (Throwable e) {
30return -1;
31}
32}
33
34/** Setup shell command arguments for the execute. */
35@NonNull
36public static String[] setupShellCommandArguments(@NonNull String executable, @Nullable String[] arguments) {
37List<String> result = new ArrayList<>();
38result.add(executable);
39if (arguments != null) Collections.addAll(result, arguments);
40return result.toArray(new String[0]);
41}
42
43/** Get basename for executable. */
44@Nullable
45public static String getExecutableBasename(@Nullable String executable) {
46return FileUtils.getFileBasename(executable);
47}
48
49
50
51/** Get transcript for {@link TerminalSession}. */
52public static String getTerminalSessionTranscriptText(TerminalSession terminalSession, boolean linesJoined, boolean trim) {
53if (terminalSession == null) return null;
54
55TerminalEmulator terminalEmulator = terminalSession.getEmulator();
56if (terminalEmulator == null) return null;
57
58TerminalBuffer terminalBuffer = terminalEmulator.getScreen();
59if (terminalBuffer == null) return null;
60
61String transcriptText;
62
63if (linesJoined)
64transcriptText = terminalBuffer.getTranscriptTextWithFullLinesJoined();
65else
66transcriptText = terminalBuffer.getTranscriptTextWithoutJoinedLines();
67
68if (transcriptText == null) return null;
69
70if (trim)
71transcriptText = transcriptText.trim();
72
73return transcriptText;
74}
75
76}
77